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 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected tree of n vertices.
Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.
How many nice edges are there in the given tree?
Input
The first line contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of vertices in the tree.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2) — the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored.
The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
Output
Print a single integer — the number of nice edges in the given tree.
Examples
Input
5
2 0 0 1 2
1 2
2 3
2 4
2 5
Output
1
Input
5
1 0 0 0 2
1 2
2 3
3 4
4 5
Output
4
Input
3
1 1 2
2 3
1 3
Output
0
Note
Here is the tree from the first example:
<image>
The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.
Here is the tree from the second example:
<image>
Every edge is nice in it.
Here is the tree from the third example:
<image>
Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
for i in arr:
stdout.write(str(i)+' ')
stdout.write('\n')
range = xrange # not for python 3.0+
n=input()
l=in_arr()
d=defaultdict(list)
b=l.count(2)
r=l.count(1)
for i in range(n-1):
u,v=in_arr()
d[u].append(v)
d[v].append(u)
q=[1]
vis=[0]*(n+1)
pos=0
vis[1]=1
while pos<n:
x=q[pos]
pos+=1
for i in d[x]:
if not vis[i]:
vis[i]=1
q.append(i)
dp=[[0,0] for i in range(n+1)]
while q:
x=q.pop()
vis[x]=0
if l[x-1]==1:
dp[x][0]=1
elif l[x-1]==2:
dp[x][1]=1
for i in d[x]:
if not vis[i]:
dp[x][0]+=dp[i][0]
dp[x][1]+=dp[i][1]
q=[1]
vis[1]=1
ans=0
while q:
x=q.pop(0)
for i in d[x]:
if not vis[i]:
vis[i]=1
q.append(i)
if ((dp[i][1]==b) and (dp[i][0]==0)) or (dp[i][1]==0 and r-dp[i][0]==r):
#print x,i,b-dp[i][1],r-dp[i][0]
ans+=1
pr_num(ans)
``` | instruction | 0 | 4,206 | 13 | 8,412 |
No | output | 1 | 4,206 | 13 | 8,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices numbered 1, …, n. A tree is a connected simple graph without cycles.
Let dist(u, v) be the number of edges in the unique simple path connecting vertices u and v.
Let diam(l, r) = max dist(u, v) over all pairs u, v such that l ≤ u, v ≤ r.
Compute ∑_{1 ≤ l ≤ r ≤ n} diam(l, r).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree.
The next n - 1 lines describe the tree edges. Each of these lines contains two integers u, v (1 ≤ u, v ≤ n) — endpoint indices of the respective tree edge. It is guaranteed that the edge list indeed describes a tree.
Output
Print a single integer — ∑_{1 ≤ l ≤ r ≤ n} diam(l, r).
Examples
Input
4
1 2
2 4
3 2
Output
10
Input
10
1 8
2 9
5 6
4 8
4 2
7 9
3 6
10 4
3 9
Output
224
Submitted Solution:
```
a = input()
a = list(a)
b = input()
b = list(b)
l = []
for i in range(len(a)):
if a[i] != b[i]: l.append('1')
else: l.append('0')
print(''.join(l))
``` | instruction | 0 | 4,415 | 13 | 8,830 |
No | output | 1 | 4,415 | 13 | 8,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd.
<image>
The problem is:
You are given a connected tree rooted at node 1.
You should assign a character a or b to every node in the tree so that the total number of a's is equal to x and the total number of b's is equal to n - x.
Let's define a string for each node v of the tree as follows:
* if v is root then the string is just one character assigned to v:
* otherwise, let's take a string defined for the v's parent p_v and add to the end of it a character assigned to v.
You should assign every node a character in a way that minimizes the number of distinct strings among the strings of all nodes.
Input
The first line contains two integers n and x (1 ≤ n ≤ 10^5; 0 ≤ x ≤ n) — the number of vertices in the tree the number of a's.
The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_i ≤ n; p_i ≠ i), where p_i is the parent of node i.
It is guaranteed that the input describes a connected tree.
Output
In the first line, print the minimum possible total number of distinct strings.
In the second line, print n characters, where all characters are either a or b and the i-th character is the character assigned to the i-th node.
Make sure that the total number of a's is equal to x and the total number of b's is equal to n - x.
If there is more than one answer you can print any of them.
Example
Input
9 3
1 2 2 4 4 4 3 1
Output
4
aabbbbbba
Note
The tree from the sample is shown below:
<image>
The tree after assigning characters to every node (according to the output) is the following:
<image>
Strings for all nodes are the following:
* string of node 1 is: a
* string of node 2 is: aa
* string of node 3 is: aab
* string of node 4 is: aab
* string of node 5 is: aabb
* string of node 6 is: aabb
* string of node 7 is: aabb
* string of node 8 is: aabb
* string of node 9 is: aa
The set of unique strings is \{a, aa, aab, aabb\}, so the number of distinct strings is 4.
Submitted Solution:
```
line_1=input()
line_2=input()
line_1=line_1.split(' ')
num=int(line_1[1])
line_2=line_2.split(' ')
ans=0
count=0
a_list=[]
for x in line_2:
count+=1
if int(x)<int(num):
if int(num)+1>count:
a_list.append('a')
else:
a_list.append('b')
ans+=1
else:
a_list.append('b')
print(ans)
for g in a_list:
print(g,end='')
``` | instruction | 0 | 4,416 | 13 | 8,832 |
No | output | 1 | 4,416 | 13 | 8,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd.
<image>
The problem is:
You are given a connected tree rooted at node 1.
You should assign a character a or b to every node in the tree so that the total number of a's is equal to x and the total number of b's is equal to n - x.
Let's define a string for each node v of the tree as follows:
* if v is root then the string is just one character assigned to v:
* otherwise, let's take a string defined for the v's parent p_v and add to the end of it a character assigned to v.
You should assign every node a character in a way that minimizes the number of distinct strings among the strings of all nodes.
Input
The first line contains two integers n and x (1 ≤ n ≤ 10^5; 0 ≤ x ≤ n) — the number of vertices in the tree the number of a's.
The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_i ≤ n; p_i ≠ i), where p_i is the parent of node i.
It is guaranteed that the input describes a connected tree.
Output
In the first line, print the minimum possible total number of distinct strings.
In the second line, print n characters, where all characters are either a or b and the i-th character is the character assigned to the i-th node.
Make sure that the total number of a's is equal to x and the total number of b's is equal to n - x.
If there is more than one answer you can print any of them.
Example
Input
9 3
1 2 2 4 4 4 3 1
Output
4
aabbbbbba
Note
The tree from the sample is shown below:
<image>
The tree after assigning characters to every node (according to the output) is the following:
<image>
Strings for all nodes are the following:
* string of node 1 is: a
* string of node 2 is: aa
* string of node 3 is: aab
* string of node 4 is: aab
* string of node 5 is: aabb
* string of node 6 is: aabb
* string of node 7 is: aabb
* string of node 8 is: aabb
* string of node 9 is: aa
The set of unique strings is \{a, aa, aab, aabb\}, so the number of distinct strings is 4.
Submitted Solution:
```
from sys import stdin, stdout
meta = stdin.readline()
tree = stdin.readline()
for i in tree:
print(tree)
``` | instruction | 0 | 4,417 | 13 | 8,834 |
No | output | 1 | 4,417 | 13 | 8,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd.
<image>
The problem is:
You are given a connected tree rooted at node 1.
You should assign a character a or b to every node in the tree so that the total number of a's is equal to x and the total number of b's is equal to n - x.
Let's define a string for each node v of the tree as follows:
* if v is root then the string is just one character assigned to v:
* otherwise, let's take a string defined for the v's parent p_v and add to the end of it a character assigned to v.
You should assign every node a character in a way that minimizes the number of distinct strings among the strings of all nodes.
Input
The first line contains two integers n and x (1 ≤ n ≤ 10^5; 0 ≤ x ≤ n) — the number of vertices in the tree the number of a's.
The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_i ≤ n; p_i ≠ i), where p_i is the parent of node i.
It is guaranteed that the input describes a connected tree.
Output
In the first line, print the minimum possible total number of distinct strings.
In the second line, print n characters, where all characters are either a or b and the i-th character is the character assigned to the i-th node.
Make sure that the total number of a's is equal to x and the total number of b's is equal to n - x.
If there is more than one answer you can print any of them.
Example
Input
9 3
1 2 2 4 4 4 3 1
Output
4
aabbbbbba
Note
The tree from the sample is shown below:
<image>
The tree after assigning characters to every node (according to the output) is the following:
<image>
Strings for all nodes are the following:
* string of node 1 is: a
* string of node 2 is: aa
* string of node 3 is: aab
* string of node 4 is: aab
* string of node 5 is: aabb
* string of node 6 is: aabb
* string of node 7 is: aabb
* string of node 8 is: aabb
* string of node 9 is: aa
The set of unique strings is \{a, aa, aab, aabb\}, so the number of distinct strings is 4.
Submitted Solution:
```
def dfs(root, tree_list, cur_level, levels):
for leaf in tree_list[root]:
if len(levels)<=cur_level+1:
levels.append([])
levels[cur_level+1].append(leaf)
levels = dfs(leaf, tree_list, cur_level+1, levels)
return levels
def solve(n, x, original_tree):
tree = [[] for i in range(len(original_tree)+1)]
for i in range(len(original_tree)):
tree[original_tree[i]-1].append(i+1)
levels = dfs(0, tree, 0, [[0]])
level_num = [len(i) for i in levels]
a, b = x, n-x
sol = ['' for i in range(n)]
flag = False
for index, num in enumerate(level_num):
if a >= num:
a -= num
for node in levels[index]:
sol[node] = 'a'
elif b >= num:
b -= num
for node in levels[index]:
sol[node] = 'b'
else:
for node in levels[index]:
if a > 0:
a-=1
sol[node] = 'a'
flag = True
else:
sol[node] = 'b'
ans_num = len(level_num)
if flag:
ans_num+=1
return ans_num, ''.join(sol)
q_n, q_x = map(int, input().split())
q_tree = list(map(int,input().split()))
ans_num, solution = solve(q_n, q_x, q_tree)
print(ans_num)
print(solution)
``` | instruction | 0 | 4,418 | 13 | 8,836 |
No | output | 1 | 4,418 | 13 | 8,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd.
<image>
The problem is:
You are given a connected tree rooted at node 1.
You should assign a character a or b to every node in the tree so that the total number of a's is equal to x and the total number of b's is equal to n - x.
Let's define a string for each node v of the tree as follows:
* if v is root then the string is just one character assigned to v:
* otherwise, let's take a string defined for the v's parent p_v and add to the end of it a character assigned to v.
You should assign every node a character in a way that minimizes the number of distinct strings among the strings of all nodes.
Input
The first line contains two integers n and x (1 ≤ n ≤ 10^5; 0 ≤ x ≤ n) — the number of vertices in the tree the number of a's.
The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_i ≤ n; p_i ≠ i), where p_i is the parent of node i.
It is guaranteed that the input describes a connected tree.
Output
In the first line, print the minimum possible total number of distinct strings.
In the second line, print n characters, where all characters are either a or b and the i-th character is the character assigned to the i-th node.
Make sure that the total number of a's is equal to x and the total number of b's is equal to n - x.
If there is more than one answer you can print any of them.
Example
Input
9 3
1 2 2 4 4 4 3 1
Output
4
aabbbbbba
Note
The tree from the sample is shown below:
<image>
The tree after assigning characters to every node (according to the output) is the following:
<image>
Strings for all nodes are the following:
* string of node 1 is: a
* string of node 2 is: aa
* string of node 3 is: aab
* string of node 4 is: aab
* string of node 5 is: aabb
* string of node 6 is: aabb
* string of node 7 is: aabb
* string of node 8 is: aabb
* string of node 9 is: aa
The set of unique strings is \{a, aa, aab, aabb\}, so the number of distinct strings is 4.
Submitted Solution:
```
print("hello")
``` | instruction | 0 | 4,419 | 13 | 8,838 |
No | output | 1 | 4,419 | 13 | 8,839 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,556 | 13 | 9,112 |
Tags: greedy, math
Correct Solution:
```
# HEY STALKER
n, m = map(int, input().split())
l = list(map(int, input().split()))
ans = 0
for t in range(m):
x, y, c = map(int, input().split())
ans = max(ans, (l[x-1] + l[y-1]) / c)
print(ans)
``` | output | 1 | 4,556 | 13 | 9,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,557 | 13 | 9,114 |
Tags: greedy, math
Correct Solution:
```
import math
def solve():
n, m = [int(i) for i in input().split()]
vw = [int(i) for i in input().split()]
M = 0.0
for _ in range(m):
a, b, c = [int(i) for i in input().split()]
M = max(M, (vw[a - 1] + vw[b - 1]) / c)
print(M)
if __name__ == '__main__':
solve()
``` | output | 1 | 4,557 | 13 | 9,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,558 | 13 | 9,116 |
Tags: greedy, math
Correct Solution:
```
v, e = map(int, input().split())
vertex = list(map(int, input().split()))
ret = 0.0
for i in range(e):
a, b, c = map(int, input().split())
a -= 1;
b -= 1;
ret = max(ret, (vertex[a] + vertex[b]) / c)
print(ret)
``` | output | 1 | 4,558 | 13 | 9,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,559 | 13 | 9,118 |
Tags: greedy, math
Correct Solution:
```
n,m = map(int,input().split())
a = list(map(int,input().split()))
ans = 0
for i in range(m):
ax,bx,x = map(int,input().split())
ans = max(ans,(a[ax-1]+a[bx-1])/x)
print(ans)
``` | output | 1 | 4,559 | 13 | 9,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,560 | 13 | 9,120 |
Tags: greedy, math
Correct Solution:
```
n,m=map(int,input().split());a=list(map(int,input().split()));o=0.0
for i in range(m):
x,y,c=map(int,input().split());o=max(o,(a[x-1]+a[y-1])/c)
print(o)
# Made By Mostafa_Khaled
``` | output | 1 | 4,560 | 13 | 9,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,561 | 13 | 9,122 |
Tags: greedy, math
Correct Solution:
```
nodes , edges = map(int,input().split())
x=list(map(int,input().split()))
error =0
for i in range(edges):
a,b,c=map(int,input().split())
error = max(error , (x[a-1]+x[b-1])/c)
print(error)
``` | output | 1 | 4,561 | 13 | 9,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,562 | 13 | 9,124 |
Tags: greedy, math
Correct Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
n, m = map(int, input().split())
x = [int(i) for i in input().split()]
edge = []
val = 0
for i in range(m):
a, b, c = map(int, input().split())
val = max((x[a-1]+x[b-1])/c, val)
print(val)
``` | output | 1 | 4,562 | 13 | 9,125 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,563 | 13 | 9,126 |
Tags: greedy, math
Correct Solution:
```
n, m = map(int, input().split())
t, v = 0, [0] + list(map(int, input().split()))
for i in range(m):
x, y, d = map(int, input().split())
t = max(t, (v[x] + v[y]) / d)
print(t)
``` | output | 1 | 4,563 | 13 | 9,127 |
Provide tags and a correct Python 2 solution for this coding contest problem.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal. | instruction | 0 | 4,564 | 13 | 9,128 |
Tags: greedy, math
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n,m=in_arr()
l=in_arr()
ans=0.0
for i in range(m):
a,b,c=in_arr()
temp=(l[a-1]+l[b-1])/float(c)
ans=max(ans,temp)
pr_num(float(ans))
``` | output | 1 | 4,564 | 13 | 9,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n, m = map(int, input().split())
v = list(map(int, input().split()))
mini = 0
for i in range(m):
a, b, c = map(int, input().split())
mini = max(mini, (v[a-1]+v[b-1])/c)
print(mini)
``` | instruction | 0 | 4,565 | 13 | 9,130 |
Yes | output | 1 | 4,565 | 13 | 9,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
import sys
from collections import defaultdict
import math
from heapq import *
import itertools
MAXNUM = math.inf
MINNUM = -1 * math.inf
ASCIILOWER = 97
ASCIIUPPER = 65
pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = "<removed-task>" # placeholder for a removed task
counter = itertools.count() # unique sequence count
def add_task(task, priority=0):
"Add a new task or update the priority of an existing task"
if task in entry_finder:
remove_task(task)
count = next(counter)
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
def remove_task(task):
"Mark an existing task as REMOVED. Raise KeyError if not found."
entry = entry_finder.pop(task)
entry[-1] = REMOVED
def pop_task():
"Remove and return the lowest priority task. Raise KeyError if empty."
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError("pop from an empty priority queue")
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write("%.15f" % (ans))
def findParent(a, parents):
cur = a
while parents[cur] != cur:
cur = parents[cur]
parents[a] = cur # reduction of search time on next search
return cur
def union(a, b, parents):
parents[b] = a
def solve(nodeList, edgeList, edgeHeap):
parents = [i for i in range(nodeList)]
minTreeEdges = []
totalEdges = defaultdict(int)
# Get min spanning tree
while edgeHeap:
eVal, n1, n2 = heappop(edgeHeap)
n1Parent = findParent(n1, parents)
n2Parent = findParent(n2, parents)
if n1Parent != n2Parent:
union(n1Parent, n2Parent, parents)
totalEdges[n1] += 1
totalEdges[n2] += 1
add_task(n1, totalEdges[n1])
add_task(n2, totalEdges[n2])
minTreeEdgeList[n1] = (n2, eVal)
minTreeEdgeList[n2] = (n1, eVal)
# prune min spanning tree starting from leaves
def readinput():
heap = []
v, e = getInts()
nodes = [0] + list(getInts())
mx = 0
for i in range(e):
n1, n2, e = getInts()
mx = max(mx, (nodes[n1] + nodes[n2]) / e)
printOutput(mx)
readinput()
``` | instruction | 0 | 4,566 | 13 | 9,132 |
Yes | output | 1 | 4,566 | 13 | 9,133 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n,m=map(int, input().split())
w=list(map(int, input().split()))
ans=0.0
for i in range(m):
u,v,c=map(int, input().split())
ans=max(ans, round( (w[u-1]+w[v-1])/c,9))
print(ans)
``` | instruction | 0 | 4,567 | 13 | 9,134 |
Yes | output | 1 | 4,567 | 13 | 9,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
from sys import stdin
input = stdin.readline
n, m = map(int, input().split())
arr = [int(i) for i in input().split()]
res = 0.0
for _ in range(m):
a, b, c = map(int, input().split())
if c: res = max(res, (arr[a-1] + arr[b-1]) / c)
print(res)
``` | instruction | 0 | 4,568 | 13 | 9,136 |
Yes | output | 1 | 4,568 | 13 | 9,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n,m=map(int, input().split())
w=list(map(int, input().split()))
ans=0.0
for i in range(m):
u,v,c=map(int, input().split())
ns=max(ans, round( (w[u-1]+w[v-1])/c,9))
print(ans)
``` | instruction | 0 | 4,569 | 13 | 9,138 |
No | output | 1 | 4,569 | 13 | 9,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
from sys import *
setrecursionlimit(200000000)
inp = lambda : stdin.readline()
n,m = 0,0
dx = [1,-1,0,0]
dy = [0,0,1,-1]
visited = [ [0 for j in range(104)] for i in range(104)]
def dfs(a,x,y,w):
if visited[x][y] == 1: return
visited[x][y] = 1
if a[x][y] == '.': a[x][y] = w
w2 = 'W' if w == 'B' else 'B'
for i in range(4):
if 0 <= dx[i] + x < n and 0 <= dy[i] + y < m:
dfs(a,dx[i]+x,dy[i]+y,w2)
def main():
global n,m
n,m = map(int,inp().split())
a = [ ['-' for j in range(m)] for i in range(n)]
for i in range(n):
s = inp()[:-1]
a[i] = [c for c in s]
dfs(a,0,0,'B')
for i in a:
print("".join(i))
if __name__ == "__main__":
main()
``` | instruction | 0 | 4,570 | 13 | 9,140 |
No | output | 1 | 4,570 | 13 | 9,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.
An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:
* <image>;
* edge <image> if and only if <image>, and edge <image>;
* the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node.
Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
<image>
Input
The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges.
The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.
Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.
Output
Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.
Examples
Input
1 0
1
Output
0.000000000000000
Input
2 1
1 2
1 2 1
Output
3.000000000000000
Input
5 6
13 56 73 98 17
1 2 56
1 3 29
1 4 42
2 3 95
2 4 88
3 4 63
Output
2.965517241379311
Note
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.
In the second sample, choosing the whole graph is optimal.
Submitted Solution:
```
n,m=map(int, input().split())
g={}
w=list(map(int, input().split()))
edgeweight={}
for i in range(m):
u,v,c=map(int, input().split())
if u in g:
g[u].append(v)
else:
g[u]=[v]
# u,v=v,u
# if u in g:
# g[u].append(v)
# else:
# g[u]=[v]
edgeweight[(u,v)]=c
#edgeweight[(v,u)]=c
ans=0.0
vis=[0]*(n+1)
for i in range(1,n+1):
if not vis[i] and i in g.keys():
for j in g[i]:
vis[j]=1
ans=max(ans, round( (w[i-1]+w[j-1])/edgeweight[(i,j)],10))
print(ans)
``` | instruction | 0 | 4,571 | 13 | 9,142 |
No | output | 1 | 4,571 | 13 | 9,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.
Input
The first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1 ≤ ai, bi ≤ n) and either "LEFT" or "RIGHT" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child.
The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem D1 (9 points), the constraints 1 ≤ n ≤ 100, 1 ≤ c ≤ 50 will hold.
* In subproblem D2 (8 points), the constraints 1 ≤ n ≤ 1000000, 1 ≤ c ≤ 100000 will hold.
Output
Output will be on a single line.
Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices.
If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).
Examples
Input
3 2
1 2 LEFT
1 3 RIGHT
Output
2 1 3
Input
3 2
1 2 RIGHT
1 3 LEFT
Output
IMPOSSIBLE
Note
Consider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3).
Pre-order is the "root – left subtree – right subtree" order. In-order is the "left subtree – root – right subtree" order.
For other information regarding in-order and pre-order, see <http://en.wikipedia.org/wiki/Tree_traversal>.
Submitted Solution:
```
import sys
n, c = map(int, input().split())
COND = []
for i in range(c):
x = input().split()
if int(x[0]) >= int(x[1]):
print("IMPOSSIBLE")
sys.exit(0)
COND.append((int(x[0]), int(x[1]), x[2]))
V = [i + 1 for i in range(n)]
def dfs(curr, s):
for cond in COND:
if cond[0] == s:
s.add(cond[1])
dfs(cond[1])
def build(left_b, right_b):
if left_b == right_b:
return [left_b]
start = left_b
left_b += 1
left = set()
right = set()
for cond in COND:
if cond[0] == start:
if cond[2] == "LEFT":
left.add(cond[1])
dfs(cond[1], left)
else:
right.add(cond[1])
dfs(cond[1], right)
if len(left) > 0 and min(left) < left_b:
print("IMPOSSIBLE")
sys.exit(0)
if len(right) > 0 and max(right) > right_b:
print("IMPOSSIBLE")
sys.exit(0)
if left and right and max(left) >= min(right):
print("IMPOSSIBLE")
sys.exit(0)
mid = (left_b + right_b) // 2
if left and mid < max(left):
mid = max(left)
if right and mid > min(right) - 1:
mid = min(right) - 1
return build(left_b, mid) + [start] + build(mid + 1, right_b)
print(" ".join(map(str, build(1, n))))
``` | instruction | 0 | 4,596 | 13 | 9,192 |
No | output | 1 | 4,596 | 13 | 9,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.
Input
The first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1 ≤ ai, bi ≤ n) and either "LEFT" or "RIGHT" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child.
The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem D1 (9 points), the constraints 1 ≤ n ≤ 100, 1 ≤ c ≤ 50 will hold.
* In subproblem D2 (8 points), the constraints 1 ≤ n ≤ 1000000, 1 ≤ c ≤ 100000 will hold.
Output
Output will be on a single line.
Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices.
If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).
Examples
Input
3 2
1 2 LEFT
1 3 RIGHT
Output
2 1 3
Input
3 2
1 2 RIGHT
1 3 LEFT
Output
IMPOSSIBLE
Note
Consider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3).
Pre-order is the "root – left subtree – right subtree" order. In-order is the "left subtree – root – right subtree" order.
For other information regarding in-order and pre-order, see <http://en.wikipedia.org/wiki/Tree_traversal>.
Submitted Solution:
```
import sys
n, c = map(int, input().split())
COND = []
for i in range(c):
x = input().split()
if int(x[0]) >= int(x[1]):
print("IMPOSSIBLE")
sys.exit(0)
COND.append((int(x[0]), int(x[1]), x[2]))
V = [i + 1 for i in range(n)]
def dfs(curr, s):
for cond in COND:
if cond[0] == s:
s.add(cond[1])
dfs(cond[1])
def build(left_b, right_b):
if left_b == right_b:
return [left_b]
start = left_b
left_b += 1
left = set()
right = set()
for cond in COND:
if cond[0] == start:
if cond[2] == "LEFT":
left.add(cond[1])
dfs(cond[1], left)
else:
right.add(cond[1])
dfs(cond[1], right)
if len(left) > 0 and min(left) < left_b:
print("IMPOSSIBLE")
sys.exit(0)
if len(right) > 0 and max(right) > right_b:
print("IMPOSSIBLE")
sys.exit(0)
if left and right and max(left) >= min(right):
print("IMPOSSIBLE")
sys.exit(0)
if not left and not(right):
return [start] + [i for i in range(left_b, right_b + 1)]
if not left:
return [start] + build(left_b, right_b)
if not right:
return build(left_b, right_b) + [start]
mid = (left_b + right_b) // 2
if left and mid < max(left):
mid = max(left)
if right and mid > min(right) - 1:
mid = min(right) - 1
return build(left_b, mid) + [start] + build(mid + 1, right_b)
print(" ".join(map(str, build(1, n))))
``` | instruction | 0 | 4,597 | 13 | 9,194 |
No | output | 1 | 4,597 | 13 | 9,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,731 | 13 | 9,462 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n = int(input())
edges = [[] for i in range(n)]
for i in range(n-1):
u, v = map(int, input().split())
edges[u-1].append(v-1)
edges[v-1].append(u-1)
colors = [-1 for i in range(n)]
dfs = [(0,0)]
while len(dfs) > 0:
node, color = dfs.pop()
colors[node] = color
for neighbor in edges[node]:
if colors[neighbor] == -1:
dfs.append((neighbor, 1-color))
blue = len([x for x in colors if x==0])
red = n - blue
total_graph_edges = blue*red
print(blue*red - (n-1))
``` | output | 1 | 4,731 | 13 | 9,463 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,732 | 13 | 9,464 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
def main():
for _ in range(1):
# for _ in range(int(input()) if True else 1):
n = int(input())
# n, u, r, d, l = map(int, input().split())
# a = list(map(int, input().split()))
# b = list(map(int, input().split()))
# c = list(map(int, input().split()))
# s = list(input())
# s = input()
d = {}
for i in range(n - 1):
a, b = map(int, input().split())
if a not in d:
d[a] = [b]
else:
d[a] += [b]
if b not in d:
d[b] = [a]
else:
d[b] += [a]
color = [-1] * n
# print(d)
def dfs(n, col):
color[n - 1] = col
# print('going to', d[n])
for child in d[n]:
if color[child - 1] == -1:
dfs(child, col ^ 1)
dfs(1, 1)
# print(color)
ans = color.count(0) * color.count(1) - n + 1 # n-1 edges are already present
print(ans)
t = threading.Thread(target=main)
t.start()
t.join()
``` | output | 1 | 4,732 | 13 | 9,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,733 | 13 | 9,466 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
from sys import stdin,stdout
import bisect
import math
mod=10**9 +7
def st():
return list(stdin.readline().strip())
def inp():
return int(stdin.readline())
def li():
return list(map(int,stdin.readline().split()))
def mp():
return map(int,stdin.readline().split())
def pr(n):
stdout.write(str(n)+"\n")
def DFS(dictionary,vertex,visited):
visited[vertex]=True
stack=[vertex]
print(vertex)
while stack:
a=stack.pop()
for i in dictionary[a]:
if not visited[i]:
print(i)
visited[i]=True
stack.append(i)
def soe(limit):
l=[1]*(limit+1)
l[0]=0
l[1]=0
prime=[]
for i in range(2,limit+1):
if l[i]:
for j in range(i*i,limit+1,i):
l[j]=0
for i in range(2,limit+1):
if l[i]:
prime.append(i)
return prime
def segsoe(low,high):
limit=int(high**0.5)+1
prime=soe(limit)
n=high-low+1
l=[0]*(n+1)
for i in range(len(prime)):
lowlimit=(low//prime[i])*prime[i]
if lowlimit<low:
lowlimit+=prime[i]
if lowlimit==prime[i]:
lowlimit+=prime[i]
for j in range(lowlimit,high+1,prime[i]):
l[j-low]=1
for i in range(low,high+1):
if not l[i-low]:
if i!=1:
print(i)
def gcd(a,b):
while b:
a=a%b
b,a=a,b
return a
def power(a,n):
r=1
while n:
if n&1:
r=(r*a)
a*=a
n=n>>1
return r
def DFS(d,visited,ver,color,value):
value[ver]=color
visited[ver]=True
stack=[ver]
while stack:
a=stack.pop()
for i in d[a]:
if not visited[i]:
visited[i]=True
stack.append(i)
value[i]=value[a]^1
else:
if value[i]==value[a]:
return False
return True
def solve():
n=inp()
visited=[False for i in range(n+1)]
d={i:[] for i in range(1,n+1)}
for i in range(n-1):
a,b=mp()
d[a].append(b)
d[b].append(a)
ans=0
value=[-1]*(n+1)
for i in range(1,n+1):
if not visited[i]:
if not DFS(d,visited,i,0,value):
pr(0)
return
a=value.count(1)
pr(a*(n-a)-(n-1))
for _ in range(1):
solve()
``` | output | 1 | 4,733 | 13 | 9,467 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,734 | 13 | 9,468 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
"""http://codeforces.com/problemset/problem/862/B"""
n = int(input())
edges = dict()
for i in range(n-1):
[v1,v2] = list(map(int,input().split()))
edges.setdefault(v1,[])
edges[v1].append(v2)
edges.setdefault(v2,[])
edges[v2].append(v1)
visited = [False] * (n+1)
queue = [(1,False)]
curr = 0
cntb, cntnotb = 0, 0
while curr < len(queue):
(el, b) = queue[curr]
visited[el] = True
if b:
cntb += 1
else:
cntnotb += 1
for neigh in edges[el]:
if not visited[neigh]:
queue.append((neigh, not b) )
curr += 1
print(cntb*cntnotb - (n-1))
``` | output | 1 | 4,734 | 13 | 9,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,735 | 13 | 9,470 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from collections import defaultdict
from queue import Queue as Q
n = int(input())
e = defaultdict(list)
for i in range(n-1):
x, y = tuple(map(int, input().split()))
e[x].append(y)
e[y].append(x)
def bfs(v):
mark = defaultdict(int)
q = Q()
q.put(v)
mark[v] = 1
while not q.empty():
v = q.get()
for i in e[v]:
if mark[i] == 0:
mark[i] = mark[v]*(-1)
q.put(i)
return sum(value==1 for value in mark.values())
a = bfs(1)
print(a*(n-a)-(n-1))
``` | output | 1 | 4,735 | 13 | 9,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,736 | 13 | 9,472 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n = int(input())
adj = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
visited = [0] * n
value = [-1] * n
q = [0]
value[0] = 0
while q:
x = q.pop(0)
for u in adj[x]:
if visited[u] == 0:
visited[u] = 1
q.append(u)
value[u] = 1 - value[x]
l = value.count(0)
r = value.count(1)
print(l * r - (n-1))
``` | output | 1 | 4,736 | 13 | 9,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,737 | 13 | 9,474 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n = int(input())
e = {}
for i in range(n-1):
a, b = map(int, input().split(' '))
x = e.get(a, [])
x.append(b)
e[a] = x
x = e.get(b, [])
x.append(a)
e[b] = x
c = set()
d = set()
c.add(1)
temp = [1]
seen = set()
while len(temp) > 0:
i = temp.pop(0)
seen.add(i)
if i in c:
for j in e[i]:
d.add(j)
if j not in seen: temp.append(j)
else:
for j in e[i]:
c.add(j)
if j not in seen: temp.append(j)
x = len(c)
y = len(d)
print(x*y-n+1)
``` | output | 1 | 4,737 | 13 | 9,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). | instruction | 0 | 4,738 | 13 | 9,476 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n=int(input())
a=[[]for i in range(n)]
for i in range(n-1):
f,s=map(int,input().split())
a[s-1].append(f)
a[f-1].append(s)
q=[1]
fl=[1]+[0]*n
while len(q)!=0:
x=q.pop()
for i in a[x-1]:
if fl[i-1]==0:
q.append(i)
fl[i-1]=-fl[x-1]
print(fl.count(1)*(n-fl.count(1))-n+1)
``` | output | 1 | 4,738 | 13 | 9,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
from collections import deque, defaultdict
typ = defaultdict(int)
p = defaultdict(list)
n = int(input())
for _ in range(n-1):
tmp = list(map(int,input().split()))
u, v = tmp[0], tmp[1]
p[u].append(v)
p[v].append(u)
deq = deque()
deq.append((1,1))
s1 = 0
s2 = 0
while len(deq):
cur = deq.popleft()
v, t = cur[0], cur[1]
typ[v] = t
if t == 1:
s1 += 1
else:
s2 += 1
for i in p[v]:
if not typ[i]:
deq.append((i,(t*2)%3))
print(s1*s2-n+1)
``` | instruction | 0 | 4,739 | 13 | 9,478 |
Yes | output | 1 | 4,739 | 13 | 9,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
# Махмуд и Ехаб продолжают свои приключения! Каждый житель Злой Страны знает, что Доктор Зло любит двудольные графы, особенно деревья.
#
# Дерево — это связный граф без циклов. Двудольный граф — это граф, вершины которого можно разбить на 2 множества таким образом, что для любого ребра (u, v) графа вершины u и v лежат в разных множествах. Более формальное определение дерева и двудольного графа дано ниже.
#
# Доктор Зло дал Махмуду и Ехабу дерево, состоящее из n рёбер и сказал добавлять рёбра таким образом, чтобы граф оставался двудольным, а также в нём не было петель и кратных рёбер. Какое максимальное число рёбер они могут добавить?
# Входные данные
#
# В первой строке дано целое число n — число вершин в дереве (1 ≤ n ≤ 105).
#
# В следующих n - 1 строках содержатся пары целых чисел u и v (1 ≤ u, v ≤ n, u ≠ v) — описание рёбер дерева.
#
# Гарантируется, что заданный граф является деревом.
# Выходные данные
#
# Выведите одно число — максимальное число рёбер, которые Махмуд и Ехаб могут добавить в граф.
# python3
from collections import Counter
nodes_nr = int(input())
node_idx___neigh_idxes = []
for _ in range(nodes_nr):
node_idx___neigh_idxes.append([])
for _ in range(nodes_nr - 1):
node_idx1, node_idx2 = (int(x) - 1 for x in input().split())
node_idx___neigh_idxes[node_idx1].append(node_idx2)
node_idx___neigh_idxes[node_idx2].append(node_idx1)
node_idx___group = [-1] * nodes_nr
stack = []
stack.append(0)
node_idx___group[0] = 0
while stack:
curr_node_idx = stack.pop()
for neigh_idx in node_idx___neigh_idxes[curr_node_idx]:
if node_idx___group[neigh_idx] == -1:
if node_idx___group[curr_node_idx] == 0:
node_idx___group[neigh_idx] = 1
else:
node_idx___group[neigh_idx] = 0
stack.append(neigh_idx)
counter = Counter(node_idx___group)
ans = counter[0] * counter[1] - nodes_nr + 1
print(ans)
``` | instruction | 0 | 4,740 | 13 | 9,480 |
Yes | output | 1 | 4,740 | 13 | 9,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
import sys
n = int(sys.stdin.readline().strip())
neighbours = {}
for i in range(n-1):
u, v = (int(x) for x in sys.stdin.readline().strip().split(' '))
if u in neighbours:
neighbours[u].append(v)
else:
neighbours[u] = [v]
if v in neighbours:
neighbours[v].append(u)
else:
neighbours[v] =[u]
start = list(neighbours.keys())[0]
stack = [(start, True)]
visited = set()
A = 0
B = 0
while stack:
curr, colour = stack.pop()
if curr in visited:
continue
visited.add(curr)
if colour:
A += 1
else:
B += 1
for neighbour in neighbours[curr]:
if neighbour not in visited:
stack.append((neighbour, not colour))
total_edges = A * B
print(total_edges - n + 1)
``` | instruction | 0 | 4,741 | 13 | 9,482 |
Yes | output | 1 | 4,741 | 13 | 9,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
from collections import defaultdict
n = int(input())
graph = defaultdict(set)
for i in range(n - 1):
a, b = input().split()
graph[a].add(b)
graph[b].add(a)
start = next(iter(graph.keys()))
left, right = set([start]), set()
frontier = [(start, True)]
while frontier:
node, is_left = frontier.pop()
for neighbor in graph[node]:
if is_left and neighbor in right or not is_left and neighbor in left:
continue
frontier.append((neighbor, not is_left))
if is_left:
right.add(neighbor)
else:
left.add(neighbor)
print(sum(len(right) - len(graph[a]) for a in left))
``` | instruction | 0 | 4,742 | 13 | 9,484 |
Yes | output | 1 | 4,742 | 13 | 9,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
n = int(input())
s1 = []
s2 = []
l = [int(x) for x in input().split()]
s1.append(l[0])
s2.append(l[1])
un = []
for i in range(1,n-1):
l = [int(x) for x in input().split()]
if l[0] in s1 and l[1] not in s2:
s2.append(l[1])
elif l[0] in s2 and l[1] not in s1:
s1.append(l[1])
elif l[1] in s1 and l[0] not in s2:
s2.append(l[0])
elif l[1] in s2 and l[0] not in s1:
s1.append(l[0])
else:
un.append(l)
b = 0
while b != len(un):
b = len(un)
for i in range(b-1,-1,-1):
l = un[i]
if l[0] in s1 and l[1] not in s2:
s2.append(l[1])
un.remove(l)
elif l[0] in s2 and l[1] not in s1:
s1.append(l[1])
un.remove(l)
elif l[1] in s1 and l[0] not in s2:
s2.append(l[0])
un.remove(l)
elif l[1] in s1 and l[0] not in s1:
s1.append(l[0])
un.remove(l)
print((len(s1)+len(un))*(len(s2)+len(un))-n+1)
``` | instruction | 0 | 4,743 | 13 | 9,486 |
No | output | 1 | 4,743 | 13 | 9,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
def dfs(p, i):
color[i].append(p)
c = (i + 1) % 2
print(p)
for elem in sorted(a[p]):
if used[elem] == 0:
used[elem] = 1
dfs(elem, c)
n = int(input())
a = [[] for i in range(n)]
used = dict.fromkeys(range(n), 0)
for i in range(n - 1):
s1, s2 = sorted(map(int, input().split()))
a[s1 - 1].append(s2 - 1)
a[s2 - 1].append(s1 - 1)
color = [[], []]
used[0] = 1
dfs(0, 0)
print(color)
print(max(0, len(color[0]) * len(color[1]) - (n - 1)))
``` | instruction | 0 | 4,744 | 13 | 9,488 |
No | output | 1 | 4,744 | 13 | 9,489 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
from collections import defaultdict
def dfs(adj,node,parent,colour,count_colour):
count_colour[colour]+=1
for i in range(len(adj[node])):
if adj[node][i]!=parent:
dfs(adj,adj[node][i],node,not colour,count_colour)
n=int(input())
adj=[[] for i in range(n+1)]
for i in range(n-1):
a,b=input().split()
adj[int(a)].append(int(b))
print(adj)
count_colour=[0,0]
dfs(adj,1,0,0,count_colour)
print(count_colour[0]*count_colour[1]-(n-1))
``` | instruction | 0 | 4,745 | 13 | 9,490 |
No | output | 1 | 4,745 | 13 | 9,491 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
def dfs(graph, start, color):
global is_bipartite
for u in graph[start]:
if not color[u]:
color[u] = 3 - color[start]
dfs(graph, u, color)
elif color[u] == color[start]:
is_bipartite = False
n = int(input())
r = [[] for i in range(n + 1)]
f = []
s = []
for i in range(n - 1):
a, b = map(int, input().split())
r[a].append(b)
r[b].append(a)
if a in f:
s.append(b)
elif a in s:
f.append(b)
else:
if b in f:
s.append(a)
elif b in s:
f.append(a)
else:
f.append(b)
s.append(a)
k = 0
for i in f:
for j in s:
if i not in r[j]:
r[j].append(i)
r[i].append(j)
is_bipartite = True
df = [0] * (n + 1)
dfs(r, 1, df)
if is_bipartite :
k += 1
else:
r[j] = r[j][:-1]
r[i] = r[i][:-1]
print(k)
``` | instruction | 0 | 4,746 | 13 | 9,492 |
No | output | 1 | 4,746 | 13 | 9,493 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 4,997 | 13 | 9,994 |
"Correct Solution:
```
from collections import deque
class LowestCommonAncestor():
"""根付き木に対して、二頂点の共通の祖先で最も近いところにある頂点を求める
初期化(ダブリング配列parent[k][v]の構築): O(NlogN)
lcaを求めるクエリ: O(logN)
"""
def __init__(self, tree, root):
self.n = len(tree)
self.depth = [0] * self.n
self.log_size = (self.n).bit_length()
self.parent = [[-1] * self.n for i in range(self.log_size)]
# 親を2^0回たどって到達する頂点、つまり現在の頂点に対する親の頂点を求める
# parent[0][現在の頂点] = 親の頂点
q = deque([(root, -1, 0)]) # (現在の地点, 親の頂点, 現在の頂点と親の頂点間の距離)
while q:
v, par, dist = q.pop()
self.parent[0][v] = par
self.depth[v] = dist
for child_v in tree[v]:
if child_v != par:
self.depth[child_v] = dist + 1
q.append((child_v, v, dist + 1))
# ダブリングで親を2^k回たどって到達する頂点を求める
for k in range(1, self.log_size):
for v in range(self.n):
self.parent[k][v] = self.parent[k-1][self.parent[k-1][v]]
def lca(self, u, v):
# u, vのうち深いところにある方から|depth[u] - depth[v]|だけ親をたどる
if self.depth[u] > self.depth[v]:
u, v = v, u
for k in range(self.log_size):
if (self.depth[v] - self.depth[u] >> k) & 1:
v = self.parent[k][v]
if u == v:
return u
# 二分探索でLCAを求める
for k in reversed(range(self.log_size)):
if self.parent[k][u] != self.parent[k][v]:
u = self.parent[k][u]
v = self.parent[k][v]
return self.parent[0][u]
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
tree = [[] for i in range(n)]
for i in range(n):
for j in info[i][1:]:
tree[i].append(j)
tree[j].append(i)
lca = LowestCommonAncestor(tree, 0)
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
for i in range(q):
u, v = query[i]
print(lca.lca(u, v))
``` | output | 1 | 4,997 | 13 | 9,995 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 4,998 | 13 | 9,996 |
"Correct Solution:
```
from collections import deque
import sys
input = sys.stdin.readline
def bfs():
depth[0] = 0
queue = deque([])
queue.append(0)
while queue:
current_node = queue.popleft()
for next_node in adj_list[current_node]:
if depth[next_node] == -1:
parent[0][next_node] = current_node
depth[next_node] = depth[current_node] + 1
queue.append(next_node)
def init():
bfs() #initialize depth and parent[0]
for k in range(1, log_size):
for v in range(N):
if parent[k-1][v] < 0:
parent[k][v] = -1
else:
parent[k][v] = parent[k-1][parent[k-1][v]]
def lca(u, v): #return lowest common ancestor when 0 is root node
if depth[u] > depth[v]:
u, v = v, u
for k in range(log_size):
if (depth[v]-depth[u])>>k & 1:
v = parent[k][v]
if u == v:
return u
for k in range(log_size-1, -1, -1):
if parent[k][u] != parent[k][v]:
u = parent[k][u]
v = parent[k][v]
return parent[0][u]
N = int(input())
log_size = N.bit_length() #ceil(log)
depth = [-1] * N
parent = [[-1] * N for _ in range(log_size)]
adj_list = [[] for _ in range(N)]
for i in range(N):
kc = list(map(int, input().split()))
for ci in kc[1:]:
adj_list[i].append(ci)
adj_list[ci].append(i)
init()
q = int(input())
for _ in range(q):
ui, vi = map(int, input().split())
print(lca(ui, vi))
``` | output | 1 | 4,998 | 13 | 9,997 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 4,999 | 13 | 9,998 |
"Correct Solution:
```
import sys,queue,math,copy,itertools,bisect,collections,heapq
def main():
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())
n = NI()
m = n.bit_length()+1
root = [[-1] * n for _ in range(m)]
rev = [0] * n
depth = [0] * n
for i in range(n):
x = LI()
for a in x[1:]:
root[0][a] = i
depth[a] = depth[i] + 1
for k in range(1,m):
for i in range(n):
root[k][i] = root[k-1][root[k-1][i]]
q = NI()
for _ in range(q):
u,v = LI()
if depth[u] < depth[v] : u,v = v, u
d = depth[u] - depth[v]
bit = 1
for i in range(d.bit_length()):
if d & bit: u = root[i][u]
bit <<= 1
j = depth[u].bit_length() - 1
while j >= 0:
if root[j][u] != root[j][v]:
u = root[j][u]
v = root[j][v]
j -= 1
if u == v:
print(u)
else:
print(root[0][u])
if __name__ == '__main__':
main()
``` | output | 1 | 4,999 | 13 | 9,999 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 5,000 | 13 | 10,000 |
"Correct Solution:
```
class Edge:
def __init__(self, dst, weight):
self.dst, self.weight = dst, weight
def __lt__(self, e):
return self.weight > e.weight
class Graph:
def __init__(self, V):
self.V = V
self.E = [[] for _ in range(V)]
def add_edge(self, src, dst, weight):
self.E[src].append(Edge(dst, weight))
class HeavyLightDecomposition:
def __init__(self, g, root=0):
self.g = g
self.vid, self.head, self.heavy, self.parent = [0] * g.V, [-1] * g.V, [-1] * g.V, [-1] * g.V
self.dfs(root)
self.bfs(root)
def dfs(self, root):
stack = [(root, -1)]
sub, max_sub = [1] * self.g.V, [(0, -1)] * self.g.V
used = [False] * self.g.V
while stack:
v, par = stack.pop()
if not used[v]:
used[v] = True
self.parent[v] = par
stack.append((v, par))
stack.extend((e.dst, v) for e in self.g.E[v] if e.dst != par)
else:
if par != -1:
sub[par] += sub[v]
max_sub[par] = max(max_sub[par], (sub[v], v))
self.heavy[v] = max_sub[v][1]
def bfs(self, root=0):
from collections import deque
k, que = 0, deque([root])
while que:
r = v = que.popleft()
while v != -1:
self.vid[v], self.head[v] = k, r
for e in self.g.E[v]:
if e.dst != self.parent[v] and e.dst != self.heavy[v]:
que.append(e.dst)
k += 1
v = self.heavy[v]
def lca(self, u, v):
while self.head[u] != self.head[v]:
if self.vid[u] > self.vid[v]:
u, v = v, u
v = self.parent[self.head[v]]
else:
if self.vid[u] > self.vid[v]:
u, v = v, u
return u
N = int(input())
g = Graph(N)
for i in range(N):
for c in map(int, input().split()[1:]):
g.add_edge(i, c, 1)
g.add_edge(c, i, 1)
hld = HeavyLightDecomposition(g)
Q = int(input())
for _ in range(Q):
u, v = map(int, input().split())
print(hld.lca(u, v))
``` | output | 1 | 5,000 | 13 | 10,001 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 5,001 | 13 | 10,002 |
"Correct Solution:
```
import math
def lca(x, y):
if d[x] < d[y]:
x,y = y,x
dy = d[y]
k = d[x]-dy#abs(depth)
#Align depth
while k:
x = p[x][int(math.log(k,2))]
k = d[x]-dy
if x == y:
return x
for i in range(h)[::-1]:
#print(h)
if p[x][i] != p[y][i]:
x = p[x][i]
y = p[y][i]
return p[x][0]
if __name__ == "__main__":
n = int(input())
#depth
d = [0] * n
d[0] = 1
#parent
p = [[] for i in range(n)]
p[0].append(0)
for i in range(n):
vi = map(int, input().split()[1:])
nd = d[i] + 1
for j in vi:
p[j].append(i)
d[j] = nd
#print(p)
#print(d)
h = int(math.log(max(d),2)) + 1
for i in range(h - 1):
for x in range(n):
p[x].append(p[p[x][i]][i])
#print(p)
q = int(input())
for _ in range(q):
x,y = map(int, input().split())
print(lca(x,y))
``` | output | 1 | 5,001 | 13 | 10,003 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 5,002 | 13 | 10,004 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
from functools import lru_cache
import sys
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 2**60
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
class Doubling():
def __init__(self, a0):
"""
a0 is an array-like object which contains ai, 0 <= i < N.
ai is the next value of i.
"""
N = len(a0)
self.N = N
self.nt = [[None] * N for i in range(N.bit_length()+1)]
for i, a in enumerate(a0):
self.nt[0][i] = a
for i in range(1, len(self.nt)):
for j in range(N):
if self.nt[i-1][j] is None:
self.nt[i][j] = None
else:
self.nt[i][j] = self.nt[i-1][self.nt[i-1][j]]
def apply(self, i, n):
"""
Apply n times from i
"""
j = i
for k in range(n.bit_length()):
m = 1 << k
if m & n:
j = self.nt[k][j]
if j is None:
break
return j
class LCA():
def __init__(self, g, root):
s = [root]
self.N = len(g)
self.p = [None] * self.N
self.d = [INF] * self.N
self.p[root] = root
self.d[root] = 0
while s:
u = s.pop()
for v in g[u]:
if self.d[v] is INF:
self.p[v] = u
self.d[v] = self.d[u] + 1
s.append(v)
self.doubling = Doubling(self.p)
def query(self, u, v):
if self.d[u] > self.d[v]:
u, v = v, u
o = self.d[v] - self.d[u]
v = self.doubling.apply(v, o)
if u == v:
return u
for k in range(len(self.doubling.nt)-1, -1, -1):
if self.doubling.nt[k][u] != self.doubling.nt[k][v]:
u = self.doubling.nt[k][u]
v = self.doubling.nt[k][v]
return self.doubling.nt[0][u]
def slv(N, KC, Q, UV):
g = [list() for _ in range(N)]
for u, (k, *c) in enumerate(KC):
for v in c:
g[u].append(v)
g[v].append(u)
lca = LCA(g, 0)
ans = []
for u, v in UV:
i = lca.query(u, v)
ans.append(i)
return ans
def main():
N = read_int()
KC = [read_int_n() for _ in range(N)]
Q = read_int()
UV = [read_int_n() for _ in range(Q)]
print(*slv(N, KC, Q, UV), sep='\n')
if __name__ == '__main__':
main()
``` | output | 1 | 5,002 | 13 | 10,005 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 5,003 | 13 | 10,006 |
"Correct Solution:
```
class Lca:
def __init__(self, E, root):
import sys
sys.setrecursionlimit(500000)
self.root = root
self.E = E # V<V>
self.n = len(E) # 頂点数
self.logn = 1 # n < 1<<logn ぴったりはだめ
while self.n >= (1<<self.logn):
self.logn += 1
# parent[n][v] = ノード v から 1<<n 個親をたどったノード
self.parent = [[-1]*self.n for _ in range(self.logn)]
self.depth = [0] * self.n
self.dfs(root, -1, 0)
for k in range(self.logn-1):
for v in range(self.n):
p_ = self.parent[k][v]
if p_ >= 0:
self.parent[k+1][v] = self.parent[k][p_]
def dfs(self, v, p, dep):
# ノード番号、親のノード番号、深さ
self.parent[0][v] = p
self.depth[v] = dep
for e in self.E[v]:
if e != p:
self.dfs(e, v, dep+1)
def get(self, u, v):
if self.depth[u] > self.depth[v]:
u, v = v, u # self.depth[u] <= self.depth[v]
dep_diff = self.depth[v]-self.depth[u]
for k in range(self.logn):
if dep_diff >> k & 1:
v = self.parent[k][v]
if u==v:
return u
for k in range(self.logn-1, -1, -1):
if self.parent[k][u] != self.parent[k][v]:
u = self.parent[k][u]
v = self.parent[k][v]
return self.parent[0][u]
n = int(input())
E = [[] for _ in range(n)]
for i in range(n):
kc = list(map(int, input().split()))
k = kc[0]
for c in kc[1:]:
E[i].append(c)
E[c].append(i)
lca = Lca(E, 0)
Q = int(input())
for _ in range(Q):
u, v = map(int, input().split())
print(lca.get(u, v))
``` | output | 1 | 5,003 | 13 | 10,007 |
Provide a correct Python 3 solution for this coding contest problem.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0 | instruction | 0 | 5,004 | 13 | 10,008 |
"Correct Solution:
```
from math import log2
class LCA:
N = 0
depth = []
table = []
def init(N, par):
LCA.N = N
LCA.depth = [-1] * (N+1)
max_depth = 0
# set depth
for i in range(1, N+1):
if LCA.depth[i] != -1: continue
q = []
v = i
while True:
q.append(v)
if v == par[v]:
d = 1
break
if LCA.depth[v] != -1:
d = LCA.depth[v]
break
v = par[v]
for v in q[::-1]:
LCA.depth[v] = d
d += 1
max_depth = max(max_depth, d)
t_size = int(log2(max_depth))+1
LCA.table = [[i for i in range(N+1)] for j in range(t_size)]
for i in range(N+1):
LCA.table[0][i] = par[i]
for i in range(1, t_size):
for j in range(1, N+1):
LCA.table[i][j] = LCA.table[i-1][LCA.table[i-1][j]]
def move(v, m):
# v の m代の祖先
i = 0
while m:
if m % 2: v = LCA.table[i][v]
i += 1
m //= 2
return v
def same(v, u):
# v と uのLCA
v_d = LCA.depth[v]
u_d = LCA.depth[u]
if v_d > u_d:
v, u = u, v
v_d, u_d = u_d, v_d
diff = u_d - v_d
u = LCA.move(u, diff)
if v == u: return v
l, r = 1, v_d
while l < r:
mid = (l+r) // 2
v_p = LCA.move(v, mid)
u_p = LCA.move(u, mid)
if v_p == u_p: r = mid
else: l = mid+1
return LCA.move(v, l)
def same2(v, u):
# v の祖先に u がいるか
if v == u: return True
v_d = LCA.depth[v]
u_d = LCA.depth[u]
if v_d <= u_d: return False
if LCA.move(v, v_d-u_d) == u: return True
else: return False
N = int(input())
par = [i for i in range(N+1)]
for i in range(N):
c = list(map(int, input().split()))
for j in c[1:]:
par[j] = i
LCA.init(N, par)
for i in range(int(input())):
a, b = list(map(int, input().split()))
print(LCA.same(a, b))
``` | output | 1 | 5,004 | 13 | 10,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0
Submitted Solution:
```
from math import log2
def build():
global parent
dfs()
pk0 = parent[0]
for pk1 in parent[1:]:
for v in range(n):
pkv = pk0[v]
pk1[v] = -1 if pkv < 0 else pk0[pkv]
pk0 = pk1
def dfs():
global depth, parent, tree
stack = [(0, -1, 0)]
while stack:
v, p, d = stack.pop()
parent[0][v] = p
depth[v] = d
stack.extend((child, v, d + 1) for child in tree[v])
def lca(u: int, v: int) -> int:
global depth, parent
du, dv = depth[u], depth[v]
if du > dv:
u, v = v, u
du, dv = dv, du
for k, pk in enumerate(parent):
if (dv - du) >> k & 1:
v = pk[v]
if u == v:
return u
for pk in parent[logn - 1:None:-1]:
pku, pkv = pk[u], pk[v]
if pku != pkv:
u, v = pku, pkv
return parent[0][u]
if __name__ == "__main__":
n = int(input())
tree = []
for _ in range(n):
_, *children = map(lambda x: int(x), input().split())
tree.append(set(children))
logn = int(log2(n)) + 1
parent = [[0] * n for _ in range(logn)]
depth = [0] * n
build()
q = int(input())
for _ in range(q):
u, v = map(lambda x: int(x), input().split())
print(lca(u, v))
``` | instruction | 0 | 5,005 | 13 | 10,010 |
Yes | output | 1 | 5,005 | 13 | 10,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
0
0
Submitted Solution:
```
import sys,math
sys.setrecursionlimit(1000000)
INF = float("inf")
N = int(sys.stdin.readline())
c = tuple(tuple(map(int,sys.stdin.readline().rstrip().split()))[1:] for _ in range(N)) # multi line with multi param
Q = int(sys.stdin.readline())
uv = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(Q)) # multi line with multi param
G = [list() for _ in range(N)]
for i,children in enumerate(c):
G[i] = children
square = [i**2 for i in range(i,40)]
import bisect
#LN = bisect.bisect_left(square,N)+2
LN = math.ceil(math.log2(N))+1
depth = [0]*N
parents = [[0]*N for _ in range(LN)]
def dfs(v,p,l):
parents[0][v] = p
depth[v] = l
for i in G[v]:
if i != p:
dfs(i,v,l+1)
dfs(0,-1,0)
for k in range(LN-1):#-1?
for v in range(N):
if parents[k][v] < 0:
parents[k+1][v] = -1
else:
parents[k+1][v] = parents[k][parents[k][v]]
def query(u,v):
if depth[u] > depth[v]:
u,v = v,u
while depth[v] != depth[u]:
v = parents[int(math.log2(depth[v]-depth[u]))][v]
# for k in range(LN)[::-1]:
# if ((depth[v]-depth[u])>>k & 1):
# v = parents[k][v]
assert(depth[u]==depth[v])
if u == v:
return u
for k in range(LN)[::-1]:
if parents[k][v] != parents[k][u]:
v = parents[k][v]
u = parents[k][u]
return parents[0][u]
ans = []
for u,v in uv:
print(query(u,v))
``` | instruction | 0 | 5,006 | 13 | 10,012 |
Yes | output | 1 | 5,006 | 13 | 10,013 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.