message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k? Input The first line contains a single integer k (1 ≤ k ≤ 109). Output You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them. Examples Input 2 Output 4 NNYY NNYY YYNN YYNN Input 9 Output 8 NNYYYNNN NNNNNYYY YNNNNYYY YNNNNYYY YNNNNYYY NYYYYNNN NYYYYNNN NYYYYNNN Input 1 Output 2 NY YN Note In first example, there are 2 shortest paths: 1-3-2 and 1-4-2. In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. Submitted Solution: ``` from collections import defaultdict k=int(input()) mask=0 d=defaultdict(lambda:0) while(mask<=30): if k&(1<<mask): d[mask]=1 ma=mask mask+=1 adj=defaultdict(lambda:"N") currl=1 currvu=3 prevu=[1] prevl=[] currvl=4 m=4 while((currl//2)<=ma): if d[currl//2]: adj[currvu,currvl]="Y" adj[currvl, currvu] = "Y" for j in prevu: adj[currvu, j] = "Y" adj[j, currvu] = "Y" for j in prevl: adj[currvl, j] = "Y" adj[j, currvl] = "Y" if ((currl+2)//2)<=ma: prevu=[currvl+1,currvl+2] for j in prevu: adj[currvu, j] = "Y" adj[j, currvu] = "Y" prevl=[currvl+3] for j in prevl: adj[currvl, j] = "Y" adj[j, currvl] = "Y" currvu=currvl+4 currvl=currvu+1 m=max(m,currvl) else: break currl+=2 adj[2,currvl]="Y" adj[currvl,2]="Y" for i in range(1,m+1): for j in range(1,m+1): print(adj[i,j],end="") print() ```
instruction
0
93,015
13
186,030
No
output
1
93,015
13
186,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k? Input The first line contains a single integer k (1 ≤ k ≤ 109). Output You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them. Examples Input 2 Output 4 NNYY NNYY YYNN YYNN Input 9 Output 8 NNYYYNNN NNNNNYYY YNNNNYYY YNNNNYYY YNNNNYYY NYYYYNNN NYYYYNNN NYYYYNNN Input 1 Output 2 NY YN Note In first example, there are 2 shortest paths: 1-3-2 and 1-4-2. In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. Submitted Solution: ``` k = int(input()) edges = [['N' for i in range(1010)] for j in range(1010)] vertices = 2 def add_edge(a, b): global edges edges[a][b] = edges[b][a] = 'Y' for i in range(1, 29 + 1): vertices += 3 add_edge(i * 3, i * 3 - 1) add_edge(i * 3, i * 3 + 2) add_edge(i * 3 + 1, i * 3 - 1) add_edge(i * 3 + 1, i * 3 + 2) for bit in range(30): if (1 << bit) & k: lst = 1 for i in range((29 - bit) * 2): vertices += 1 add_edge(lst, vertices) lst = vertices add_edge(lst, 3 * bit + 2) print(vertices) print('\n'.join(map(lambda x: ''.join(x), edges[1:]))) ```
instruction
0
93,016
13
186,032
No
output
1
93,016
13
186,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k? Input The first line contains a single integer k (1 ≤ k ≤ 109). Output You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them. Examples Input 2 Output 4 NNYY NNYY YYNN YYNN Input 9 Output 8 NNYYYNNN NNNNNYYY YNNNNYYY YNNNNYYY YNNNNYYY NYYYYNNN NYYYYNNN NYYYYNNN Input 1 Output 2 NY YN Note In first example, there are 2 shortest paths: 1-3-2 and 1-4-2. In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. Submitted Solution: ``` k = int(input()) edges = [['N' for i in range(1010)] for j in range(1010)] vertices = 2 def add_edge(a, b): global edges edges[a][b] = edges[b][a] = 'Y' for i in range(1, 29 + 1): vertices += 3 add_edge(i * 3, i * 3 - 1) add_edge(i * 3, i * 3 + 2) add_edge(i * 3 + 1, i * 3 - 1) add_edge(i * 3 + 1, i * 3 + 2) for bit in range(30): if (1 << bit) & k: lst = 1 for i in range((29 - bit) * 2): vertices += 1 add_edge(lst, vertices) lst = vertices add_edge(lst, 3 * bit + 2) print(vertices) if 0: for i in range(1, vertices + 1): print(i, ':', '\n\t', end='') for j in range(1, vertices + 1): if edges[i][j] == 'Y': print(j, end=' ') print('') else: print('\n'.join(map(lambda x: ''.join(x[1:vertices+1]), edges[1:]))) ```
instruction
0
93,017
13
186,034
No
output
1
93,017
13
186,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k? Input The first line contains a single integer k (1 ≤ k ≤ 109). Output You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them. Examples Input 2 Output 4 NNYY NNYY YYNN YYNN Input 9 Output 8 NNYYYNNN NNNNNYYY YNNNNYYY YNNNNYYY YNNNNYYY NYYYYNNN NYYYYNNN NYYYYNNN Input 1 Output 2 NY YN Note In first example, there are 2 shortest paths: 1-3-2 and 1-4-2. In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. Submitted Solution: ``` k = int(input()) edges = [['N' for i in range(1010)] for j in range(1010)] vertices = 2 def add_edge(a, b): global edges edges[a][b] = edges[b][a] = 'Y' for i in range(1, 29 + 1): vertices += 3 add_edge(i * 3, i * 3 - 1) add_edge(i * 3, i * 3 + 2) add_edge(i * 3 + 1, i * 3 - 1) add_edge(i * 3 + 1, i * 3 + 2) for bit in range(30): if (1 << bit) & k: lst = 1 for i in range((29 - bit) * 2): vertices += 1 add_edge(lst, vertices) lst = vertices add_edge(lst, 3 * bit + 2) print(vertices) if False: for i in range(1, vertices + 1): print(i, ':', '\n\t', end='') for j in range(1, vertices + 1): if edges[i][j] == 'Y': print(j, end=' ') print('') print('\n'.join(map(lambda x: ''.join(x[1:]), edges[1:]))) ```
instruction
0
93,018
13
186,036
No
output
1
93,018
13
186,037
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,115
13
186,230
Tags: constructive algorithms, graphs Correct Solution: ``` from collections import defaultdict,deque,Counter,OrderedDict import sys sys.setrecursionlimit(20000) def main(): n,m = map(int,input().split()) adj = [[] for i in range(n+1)] for i in range(m): a,b = map(int,input().split()) a,b = a-1,b-1 adj[a].append(b) adj[b].append(a) ans = ["c"]*(n) visited = [0]*(n) for i in range(n): if len(adj[i]) == n - 1: visited[i] = 1 ans[i] = "b" def dfs(s,c): if visited[s]: return visited[s],ans[s] = 1,c for j in adj[s]: dfs(j,c) if "c" in ans: st = ans.index("c") dfs(st,"a") if "c" in ans: st = ans.index("c") dfs(st,"c") check,cnta,cntc,cntb = True,ans.count("a"),ans.count("c"),ans.count("b") for i in range(n): if ans[i] == "a": check &= (len(adj[i])==cnta+cntb-1) elif ans[i] == "c": check &= (len(adj[i])==cntc+cntb-1) if check: print("Yes\n"+"".join(ans)) else: print("No") if __name__ == "__main__": main() ```
output
1
93,115
13
186,231
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,116
13
186,232
Tags: constructive algorithms, graphs Correct Solution: ``` #!/usr/bin/python3 (n, m) = tuple(map(int, input().split())) cnt = [0]*n edges = [] for i in range(m): (u, v) = tuple(map(int, input().split())) edges.append((u, v)) cnt[u-1] += 1 cnt[v-1] += 1 edges = sorted(edges) edge_set = set(edges) A = set() B = set() C = set() for i in range(n): #print(A) #print(B) #print(C) if cnt[i] == n-1: B.add(i+1) else: in_A = True in_C = True for a in A: if ((a, i+1) not in edge_set and (i+1, a) not in edge_set): in_A = False else: in_C = False for c in C: if ((c, i+1) not in edge_set and (i+1, c) not in edge_set): in_C = False else: in_A = False if in_A == True and in_C == True: #? A.add(i+1) elif in_A == False and in_C == True: C.add(i+1) elif in_A == True and in_C == False: A.add(i+1) else: print("No") break else: print("Yes") ans = "" for i in range(1, n+1): if i in A: ans += 'a' if i in B: ans += 'b' if i in C: ans += 'c' print(ans) ```
output
1
93,116
13
186,233
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,117
13
186,234
Tags: constructive algorithms, graphs Correct Solution: ``` edge=[[0 for _ in range(510)] for _ in range(510)] cnt = [0]*510 s=[0]*510 n,m = map(int,input().split()) for _ in range(m): u,v = map(int,input().split()) u-=1 v-=1 edge[u][v]=1 edge[v][u]=1 cnt[u]+=1 cnt[v]+=1 for i in range(n): if(cnt[i]==n-1):s[i]='b' for i in range(n): if s[i]==0: s[i]='a' #print(i) for j in range(n): if s[j]==0: #print(j) #print(edge[i][j]) if edge[i][j]!=0:s[j]='a' else:s[j]='c' #print(s[j]) for i in range(n): for j in range(n): if i == j : continue if (abs(ord(s[i])-ord(s[j])==2 and edge[i][j]==1))or(abs(ord(s[i])-ord(s[j]))<2 and edge[i][j]==0):print('No');exit() print('Yes') no = '' for i in s: if i == 0:break no+=str(i) print(no) ```
output
1
93,117
13
186,235
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,118
13
186,236
Tags: constructive algorithms, graphs Correct Solution: ``` def dfs(v, graph, used, str_arr, color=0): used[v] = True str_arr[v] = color for u in graph[v]: if used[u] and str_arr[u] == color: return False if not used[u] and not dfs(u, graph, used, str_arr, color ^ 1): return False return True def main(): n, m = list(map(int, input().strip().split())) graph_adj = [[0] * n for i in range(n)] for i in range(m): a, b = list(map(int, input().strip().split())) a -= 1 b -= 1 graph_adj[a][b] = 1 graph_adj[b][a] = 1 arr_adj = [[] for i in range(n)] for i in range(n): for j in range(i + 1, n): if graph_adj[i][j] == 0: arr_adj[i].append(j) arr_adj[j].append(i) used = [False] * n str_arr = [-1] * n #print(arr_adj) for i in range(n): if not used[i] and len(arr_adj[i]) > 0: if not dfs(i, arr_adj, used, str_arr): print("No") return #print(str_arr) for i in range(n): if str_arr[i] == -1: str_arr[i] = 'b' elif str_arr[i] == 0: str_arr[i] = 'a' else: str_arr[i] = 'c' for i in range(n): for j in range(i + 1, n): if graph_adj[i][j] and (str_arr[i] == 'a' and str_arr[j] == 'c' or str_arr[i] == 'c' and str_arr[j] == 'a'): print("No") return print("Yes") print(''.join(str_arr)) main() ```
output
1
93,118
13
186,237
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,119
13
186,238
Tags: constructive algorithms, graphs Correct Solution: ``` color = [-1] * 510 vis = [0] * 510 def dfs(start): vis[start] = 1 for i in g[start]: if vis[i] == 0: color[i] = 1 - color[start] dfs(i) if vis[i] != 0: if (color[i] == color[start]): print("No") quit() g = {} for i in range(510): g[i] = [] h = [] for i in range(510): h.append([0] * 510) cosas = [] a, b = map(int, input().split(' ')) for c in range(b): d, e = map(int, input().split(' ')) h[d][e] = 1 h[e][d] = 1 cosas.append([d, e]) for i in range(1, a+1): for j in range(1, a+1): if h[i][j] != 1 and i != j: g[i].append(j) for i in range(1, a+1): if (len(g[i]) == 0): color[i] = -1 vis[i] = 1 if (vis[i] == 0): color[i] = 0 dfs(i) estrenga = "" for i in range(1, a+1): if color[i] == 0: estrenga += 'a' elif color[i] == 1: estrenga += 'c' else: estrenga += 'b' for i in cosas: arra = [i[0], i[1]] arrb = [estrenga[arra[0]-1], estrenga[arra[1]-1]] arrb.sort() if arrb[0] == 'a' and arrb[1] == 'c': print("No") quit() print("Yes") print(estrenga) ```
output
1
93,119
13
186,239
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,120
13
186,240
Tags: constructive algorithms, graphs Correct Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 missingdays <missingdays@missingdays> # # Distributed under terms of the MIT license. """ """ from string import ascii_lowercase def indx(c): global ascii_lowercase return ascii_lowercase.index(c) def read_list(): return [int(i) for i in input().split()] def new_list(n): return [0 for i in range(n)] def new_matrix(n, m=0): return [[0 for i in range(m)] for i in range(n)] n, m = read_list() n += 1 string = new_list(n) v = new_matrix(n, n) for i in range(m): v1, v2 = read_list() v[v1][v2] = True v[v2][v1] = True for i in range(1, n): l = v[i].count(True) if l == n-2: string[i] = 'b' for i in range(1, n): if string[i]: continue string[i] = 'a' for j in range(1, n): if string[j]: continue if v[i][j] == True: string[i] = 'a' else: string[i] = 'c' for i in range(1, n): for j in range(1, n): if i == j: continue if (abs(indx(string[i])-indx(string[j])) == 2 and v[i][j]) or (abs(indx(string[i])-indx(string[j])) < 2 and not v[i][j]): print("No") exit() print("Yes") for i in range(1, n): print(string[i], end="") print() ```
output
1
93,120
13
186,241
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,121
13
186,242
Tags: constructive algorithms, graphs Correct Solution: ``` def dfs(v): visit[v] = cnt for u in vertex[v]: if not visit[u] and u in challengers: dfs(u) n, m = map(int, input().split()) vertex = [[] for i in range(n + 1)] challengers = set() ans = [''] * (n + 1) middle = set() for i in range(m): a, b = map(int, input().split()) vertex[a].append(b) vertex[b].append(a) for i in range(1, n + 1): s = set(j for j in range(1, n + 1)) s.discard(i) if s == set(vertex[i]): ans[i] = 'b' middle.add(i) else: challengers.add(i) visit = [0] * (n + 1) cnt = 0 for c in challengers: if not visit[c]: cnt += 1 dfs(c) if cnt > 2 or cnt == 1: print('No') elif cnt == 2: first = set() second = set() for i in range(1, n + 1): if visit[i] == 1: first.add(i) elif visit[i] == 2: second.add(i) for c in first: s = first s.discard(c) if set(vertex[c]) - middle != s: print('No') break s.add(c) else: for c in first: ans[c] = 'a' for c in second: s = second s.discard(c) if set(vertex[c]) - middle != s: print('No') break s.add(c) else: for c in second: ans[c] = 'c' if not ans[1:].count(''): print('Yes', ''.join(ans[1:]), sep = '\n') ```
output
1
93,121
13
186,243
Provide tags and a correct Python 3 solution for this coding contest problem. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
instruction
0
93,122
13
186,244
Tags: constructive algorithms, graphs Correct Solution: ``` import collections n, m = map(int, input().split()) ans, A, B, C = [''] * n, [], [], [] d = collections.defaultdict(list) for i in range(m): x, y = map(int, input().split()) d[y - 1].append(x - 1) d[x - 1].append(y - 1) for k, v in d.items(): #set 'b' if len(v) == n - 1: ans[k] = 'b' B.append(k) for i in range(n): #set 'a' if ans[i] == '': ans[i] = 'a' A.append(i) de = collections.deque() de.append(i) while(len(de) != 0): cur = de.popleft() for j in d[cur]: if ans[j] == '': ans[j] = 'a' A.append(j) de.append(j) break for i in range(n): #set 'c' if ans[i] == '': ans[i] = 'c' C.append(i) temp = sorted(A + B) for i in A: #check 'a' d[i].append(i) if sorted(d[i]) != temp: print('No') exit(0) temp = sorted(B + C) for i in C: d[i].append(i) if sorted(d[i]) != temp: print('No') exit(0) print('Yes') print(''.join(ans)) ```
output
1
93,122
13
186,245
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` #!/usr/bin/python3 (n, m) = tuple(map(int, input().split())) cnt = [0]*n edges = [] for i in range(m): (u, v) = tuple(map(int, input().split())) edges.append((u, v)) cnt[u-1] += 1 cnt[v-1] += 1 edge_set = set(edges) A = set() B = set() C = set() for i in range(n): if cnt[i] == n-1: B.add(i+1) else: in_A = True in_C = True for a in A: if ((a, i+1) not in edge_set and (i+1, a) not in edge_set): in_A = False else: in_C = False for c in C: if ((c, i+1) not in edge_set and (i+1, c) not in edge_set): in_C = False else: in_A = False if in_A == True and in_C == True: A.add(i+1) elif in_A == False and in_C == True: C.add(i+1) elif in_A == True and in_C == False: A.add(i+1) else: print("No") break else: print("Yes") ans = "" for i in range(1, n+1): if i in A: ans += 'a' if i in B: ans += 'b' if i in C: ans += 'c' print(ans) ```
instruction
0
93,123
13
186,246
Yes
output
1
93,123
13
186,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` edge=[[0 for _ in range(510)] for _ in range(510)] cnt = [0]*510 s=[0]*510 n,m = map(int,input().split()) for _ in range(m): u,v = map(int,input().split()) u-=1;v-=1 edge[u][v]=1;edge[v][u]=1 cnt[u]+=1;cnt[v]+=1 for i in range(n): if(cnt[i]==n-1):s[i]='b' for i in range(n): if s[i]==0: s[i]='a' for j in range(n): if s[j]==0: if edge[i][j]!=0:s[j]='a' else:s[j]='c' for i in range(n): for j in range(n): if i == j : continue if (abs(ord(s[i])-ord(s[j])==2 and edge[i][j]==1))or(abs(ord(s[i])-ord(s[j]))<2 and edge[i][j]==0):print('No');exit() print('Yes') print(''.join(s[:s.index(0)])) ```
instruction
0
93,124
13
186,248
Yes
output
1
93,124
13
186,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` f = lambda: map(int, input().split()) n, m = f() p = [1 << i for i in range(n)] for i in range(m): x, y = f() x -= 1 y -= 1 p[x] |= 1 << y p[y] |= 1 << x s = set(p) b = (1 << n) - 1 t = {} if b in s: t[b] = 'b' s.remove(b) if len(s) == 2: a, c = s if a | c == b and bool(a & c) == (b in t): t[a], t[c] = 'ac' s.clear() print('No' if s else 'Yes\n' + ''.join(map(t.get, p))) # Made By Mostafa_Khaled ```
instruction
0
93,125
13
186,250
Yes
output
1
93,125
13
186,251
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` #!/usr/bin/python3 class StdIO: def read_int(self): return int(self.read_string()) def read_ints(self, sep=None): return [int(i) for i in self.read_strings(sep)] def read_float(self): return float(self.read_string()) def read_floats(self, sep=None): return [float(i) for i in self.read_strings(sep)] def read_string(self): return input() def read_strings(self, sep=None): return self.read_string().split(sep) io = StdIO() def dfs(adj, visited, v, word, c, component): visited[v] = True word[v] = c component.append(v) for u in adj[v]: if not visited[u]: dfs(adj, visited, u, word, c, component) def main(): n, m = io.read_ints() adj = [list() for i in range(n)] for i in range(m): u, v = io.read_ints() u -= 1 v -= 1 adj[u].append(v) adj[v].append(u) word = [None]*n visited = [False]*n # print(adj) # bs = set() bs = 0 for v in range(n): if len(adj[v]) == n-1: # bs.add(v) visited[v] = True word[v] = 'b' bs += 1 comp = 0 good = True for v in range(n): if not visited[v]: comp += 1 if comp > 2: good = False break component = [] dfs(adj, visited, v, word, ['a', 'c'][comp-1], component) size = len(component) good = True for u in component: if len(adj[u]) != size-1 + bs: good = False break if not good: break if not good: print('No') return print('Yes') print(''.join(word)) if __name__ == '__main__': main() ```
instruction
0
93,126
13
186,252
Yes
output
1
93,126
13
186,253
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` from collections import defaultdict,deque,Counter,OrderedDict def main(): n,m = map(int,input().split()) adj = [[] for i in range(n+1)] for i in range(m): a,b = map(int,input().split()) adj[a].append(b) adj[b].append(a) ans = ["d"]*(n+1) visited = [0] * (n + 1) for i in range(1,n+1): if len(adj[i]) == n-1: visited[i] = 1 ans[i] = "b" def dfs(st,ck): if visited[st]: return visited[st] = 1 ans[st] = ck for i in adj[st]: dfs(i,ck) if "d" in ans[1:]: st = ans.index("d",1) dfs(st,"a") if "d" in ans[1:]: st = ans.index("d",1) dfs(st,"c") ans = ans[1:] if "d" in ans: print("No") else: print("Yes") print("".join(ans)) if __name__ == "__main__": main() ```
instruction
0
93,127
13
186,254
No
output
1
93,127
13
186,255
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` #!/usr/bin/python3 (n, m) = tuple(map(int, input().split())) edges = [] for i in range(m): (u, v) = tuple(map(int, input().split())) edges.append((u, v)) edge_set = set(edges) A = set() B = set() C = set() for i in range(n): nums = set(range(1, n+1)) for j in edges: if j[0] == i+1: nums.remove(j[1]) if j[1] == i+1: nums.remove(j[0]) if len(nums) == 1 : B.add(i+1) else: in_A = True in_C = True for a in A: if ((a, i+1) not in edge_set): in_A = False else: in_C = False for c in C: if ((c, i+1) not in edge_set): in_C = False else: in_A = False if in_A == True and in_C == True: #? A.add(i+1) elif in_A == False and in_C == True: C.add(i+1) elif in_A == True and in_C == False: A.add(i+1) else: print("No") break else: print("Yes") ans = "" for i in range(1, n+1): if i in A: ans += 'a' if i in B: ans += 'b' if i in C: ans += 'c' print(ans) ```
instruction
0
93,128
13
186,256
No
output
1
93,128
13
186,257
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` #!/usr/bin/python3 (n, m) = tuple(map(int, input().split())) edges = [] for i in range(m): (u, v) = tuple(map(int, input().split())) edges.append((u, v)) edge_set = set(edges) A = set() B = set() C = set() for i in range(n): nums = set(range(1, n+1)) for j in edges: if j[0] == i+1: nums.remove(j[1]) if j[1] == i+1: nums.remove(j[0]) if len(nums) == 1 : B.add(i+1) else: if len(A) == 0 and len(C) == 0: A.add(i+1) elif len(A) == 0 and len(C) != 0: for c in C: if ((c, i+1) not in edge_set): A.add(i+1) break else: C.add(i+1) elif len(A) != 0 and len(C) == 0: for a in A: if ((a, i+1) not in edge_set): C.add(i+1) break else: A.add(i+1) else: in_A = True in_C = True for a in A: if ((a, i+1) not in edge_set): in_A = False for c in C: if ((c, i+1) not in edge_set): in_C = False if in_A == False and in_C == True: C.add(i+1) elif in_A == True and in_C == False: A.add(i+1) else: print("No") break else: print("Yes") ans = "" for i in range(1, n+1): if i in A: ans += 'a' if i in B: ans += 'b' if i in C: ans += 'c' print(ans) ```
instruction
0
93,129
13
186,258
No
output
1
93,129
13
186,259
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to n. * For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G. Input The first line of the input contains two integers n and m <image> — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once. Output In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them. Examples Input 2 1 1 2 Output Yes aa Input 4 3 1 2 1 3 1 4 Output No Note In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c. Submitted Solution: ``` from collections import defaultdict,deque,Counter,OrderedDict def main(): n,m = map(int,input().split()) adj = [[] for i in range(n+1)] for i in range(m): a,b = map(int,input().split()) adj[a].append(b) adj[b].append(a) ans = ["d"]*(n+1) visited = [0] * (n + 1) for i in range(1,n+1): if len(adj[i]) == n-1: visited[i] = 1 ans[i] = "b" st = ans.index("d") def dfs(st,ck): if visited[st]: return visited[st] = 1 ans[st] = ck for i in adj[st]: dfs(i,ck) dfs(st,"a") if "d" in ans: st = ans.index("d") dfs(st,"c") if "d" in ans: print("No") else: print("Yes") print("".join(ans[1:])) if __name__ == "__main__": main() ```
instruction
0
93,130
13
186,260
No
output
1
93,130
13
186,261
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n. You have to answer q queries. Each query is described by a segment of vertices [l; r], and you have to count the number of its subsegments [x; y] (l ≤ x ≤ y ≤ r), such that if we delete all vertices except the segment of vertices [x; y] (including x and y) and edges between them, the resulting graph is bipartite. Input The first line contains two integers n and m (1 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105) — the number of vertices and the number of edges in the graph. The next m lines describe edges in the graph. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting an edge between vertices ai and bi. It is guaranteed that this graph does not contain edge-simple cycles of even length. The next line contains a single integer q (1 ≤ q ≤ 3·105) — the number of queries. The next q lines contain queries. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the query parameters. Output Print q numbers, each in new line: the i-th of them should be the number of subsegments [x; y] (li ≤ x ≤ y ≤ ri), such that the graph that only includes vertices from segment [x; y] and edges between them is bipartite. Examples Input 6 6 1 2 2 3 3 1 4 5 5 6 6 4 3 1 3 4 6 1 6 Output 5 5 14 Input 8 9 1 2 2 3 3 1 4 5 5 6 6 7 7 8 8 4 7 2 3 1 8 1 4 3 8 Output 27 8 19 Note The first example is shown on the picture below: <image> For the first query, all subsegments of [1; 3], except this segment itself, are suitable. For the first query, all subsegments of [4; 6], except this segment itself, are suitable. For the third query, all subsegments of [1; 6] are suitable, except [1; 3], [1; 4], [1; 5], [1; 6], [2; 6], [3; 6], [4; 6]. The second example is shown on the picture below: <image>
instruction
0
93,213
13
186,426
Tags: binary search, data structures, dfs and similar, dsu, graphs, two pointers Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log import io,os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline mi = lambda :map(int,input().split()) li = lambda :list(mi()) n,m = mi() edge = [[] for i in range(n)] for _ in range(m): u,v = mi() edge[u-1].append(v-1) edge[v-1].append(u-1) parent = [-1 for i in range(n)] depth = [0 for i in range(n)] cnt = [0 for i in range(n)] res = [n for i in range(n)] for root in range(n): if parent[root]==-1: stack = [root] while stack: v = stack[-1] if len(edge[v])==cnt[v]: stack.pop() else: nv = edge[v][cnt[v]] cnt[v] += 1 if nv==root or parent[nv]!=-1: if depth[nv] < depth[v]-1: m,M = nv,nv pos = v while pos!=nv: m = min(pos,m) M = max(pos,M) pos = parent[pos] res[m] = min(res[m],M) else: depth[nv] = depth[v] + 1 parent[nv] = v stack.append(nv) cnt = [0 for i in range(n)] cnt[n-1] = res[n-1] - (n-1) for i in range(n-2,-1,-1): res[i] = min(res[i],res[i+1]) cnt[i] = res[i] - i for i in range(1,n): cnt[i] += cnt[i-1] query = [[] for i in range(n+1)] q = int(input()) for i in range(q): l,r = mi() query[r].append((i,l-1)) pos = -1 ans = [0 for i in range(q)] for r in range(1,n+1): while pos+1<n and res[pos+1]<=r: pos += 1 for idx,l in query[r]: if r<=pos: tmp = cnt[r-1] if l: tmp -= cnt[l-1] elif l<=pos: tmp = cnt[pos] if l: tmp -= cnt[l-1] tmp += (r-pos-1) * r - ((r+pos)*(r-pos-1)//2) else: tmp = (r-l) * r - ((r-1+l)*(r-l)//2) ans[idx] = tmp print(*ans,sep="\n") ```
output
1
93,213
13
186,427
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n. You have to answer q queries. Each query is described by a segment of vertices [l; r], and you have to count the number of its subsegments [x; y] (l ≤ x ≤ y ≤ r), such that if we delete all vertices except the segment of vertices [x; y] (including x and y) and edges between them, the resulting graph is bipartite. Input The first line contains two integers n and m (1 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105) — the number of vertices and the number of edges in the graph. The next m lines describe edges in the graph. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting an edge between vertices ai and bi. It is guaranteed that this graph does not contain edge-simple cycles of even length. The next line contains a single integer q (1 ≤ q ≤ 3·105) — the number of queries. The next q lines contain queries. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the query parameters. Output Print q numbers, each in new line: the i-th of them should be the number of subsegments [x; y] (li ≤ x ≤ y ≤ ri), such that the graph that only includes vertices from segment [x; y] and edges between them is bipartite. Examples Input 6 6 1 2 2 3 3 1 4 5 5 6 6 4 3 1 3 4 6 1 6 Output 5 5 14 Input 8 9 1 2 2 3 3 1 4 5 5 6 6 7 7 8 8 4 7 2 3 1 8 1 4 3 8 Output 27 8 19 Note The first example is shown on the picture below: <image> For the first query, all subsegments of [1; 3], except this segment itself, are suitable. For the first query, all subsegments of [4; 6], except this segment itself, are suitable. For the third query, all subsegments of [1; 6] are suitable, except [1; 3], [1; 4], [1; 5], [1; 6], [2; 6], [3; 6], [4; 6]. The second example is shown on the picture below: <image> Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log import io,os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline mi = lambda :map(int,input().split()) li = lambda :list(mi()) n,m = mi() edge = [[] for i in range(n)] for _ in range(m): u,v = mi() edge[u-1].append(v-1) edge[v-1].append(u-1) if n<=100: mini = SegmentTree([10**8 for i in range(n)],min,10**8) maxi = SegmentTree([-1 for i in range(n)],max,-1) parent = [-1 for i in range(n)] depth = [0 for i in range(n)] cnt = [0 for i in range(n)] res = [n for i in range(n)] for root in range(n): if parent[root]==-1: stack = [root] mini.update(0,root) maxi.update(0,root) while stack: v = stack[-1] if len(edge[v])==cnt[v]: mini.update(depth[v],10**8) maxi.update(depth[v],-1) stack.pop() else: nv = edge[v][cnt[v]] cnt[v] += 1 if nv==root or parent[nv]!=-1: if depth[nv] < depth[v]-1: L,R = depth[nv],depth[v] m,M = mini.query(L,R+1),maxi.query(L,R+1) res[m] = M else: depth[nv] = depth[v] + 1 parent[nv] = v mini.update(depth[nv],nv) maxi.update(depth[nv],nv) stack.append(nv) cnt = [0 for i in range(n)] cnt[n-1] = res[n-1] - (n-1) for i in range(n-2,-1,-1): res[i] = min(res[i],res[i+1]) cnt[i] = res[i] - i for i in range(1,n): cnt[i] += cnt[i-1] query = [[] for i in range(n+1)] q = int(input()) for i in range(q): l,r = mi() query[r].append((i,l-1)) if n<=100: pos = -1 ans = [0 for i in range(q)] for r in range(1,n+1): while pos+1<n and res[pos+1]<=r: pos += 1 for idx,l in query[r]: if r<=pos: tmp = cnt[r-1] if l: tmp -= cnt[l-1] else: tmp = cnt[pos] if l: tmp -= cnt[l-1] tmp += (r-pos-1) * r - ((r+pos)*(r-pos-1)//2) ans[idx] = tmp print(*ans,sep="\n") ```
instruction
0
93,214
13
186,428
No
output
1
93,214
13
186,429
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n. You have to answer q queries. Each query is described by a segment of vertices [l; r], and you have to count the number of its subsegments [x; y] (l ≤ x ≤ y ≤ r), such that if we delete all vertices except the segment of vertices [x; y] (including x and y) and edges between them, the resulting graph is bipartite. Input The first line contains two integers n and m (1 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105) — the number of vertices and the number of edges in the graph. The next m lines describe edges in the graph. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting an edge between vertices ai and bi. It is guaranteed that this graph does not contain edge-simple cycles of even length. The next line contains a single integer q (1 ≤ q ≤ 3·105) — the number of queries. The next q lines contain queries. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the query parameters. Output Print q numbers, each in new line: the i-th of them should be the number of subsegments [x; y] (li ≤ x ≤ y ≤ ri), such that the graph that only includes vertices from segment [x; y] and edges between them is bipartite. Examples Input 6 6 1 2 2 3 3 1 4 5 5 6 6 4 3 1 3 4 6 1 6 Output 5 5 14 Input 8 9 1 2 2 3 3 1 4 5 5 6 6 7 7 8 8 4 7 2 3 1 8 1 4 3 8 Output 27 8 19 Note The first example is shown on the picture below: <image> For the first query, all subsegments of [1; 3], except this segment itself, are suitable. For the first query, all subsegments of [4; 6], except this segment itself, are suitable. For the third query, all subsegments of [1; 6] are suitable, except [1; 3], [1; 4], [1; 5], [1; 6], [2; 6], [3; 6], [4; 6]. The second example is shown on the picture below: <image> Submitted Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log import io,os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline mi = lambda :map(int,input().split()) li = lambda :list(mi()) n,m = mi() edge = [[] for i in range(n)] for _ in range(m): u,v = mi() edge[u-1].append(v-1) edge[v-1].append(u-1) parent = [-1 for i in range(n)] depth = [0 for i in range(n)] cnt = [0 for i in range(n)] res = [n for i in range(n)] for root in range(n): if parent[root]==-1: stack = [root] while stack: v = stack[-1] if len(edge[v])==cnt[v]: stack.pop() else: nv = edge[v][cnt[v]] cnt[v] += 1 if nv==root or parent[nv]!=-1: if depth[nv] < depth[v]-1: m,M = nv,nv pos = v while pos!=nv: m = min(pos,m) M = max(pos,M) pos = parent[pos] res[m] = min(res[m],M) else: depth[nv] = depth[v] + 1 parent[nv] = v stack.append(nv) cnt = [0 for i in range(n)] cnt[n-1] = res[n-1] - (n-1) for i in range(n-2,-1,-1): res[i] = min(res[i],res[i+1]) cnt[i] = res[i] - i for i in range(1,n): cnt[i] += cnt[i-1] query = [[] for i in range(n+1)] q = int(input()) for i in range(q): l,r = mi() query[r].append((i,l-1)) pos = -1 ans = [0 for i in range(q)] for r in range(1,n+1): while pos+1<n and res[pos+1]<=r: pos += 1 for idx,l in query[r]: if r<=pos: tmp = cnt[r-1] if l: tmp -= cnt[l-1] else: tmp = cnt[pos] if l: tmp -= cnt[l-1] tmp += (r-pos-1) * r - ((r+pos)*(r-pos-1)//2) ans[idx] = tmp print(*ans,sep="\n") ```
instruction
0
93,215
13
186,430
No
output
1
93,215
13
186,431
Provide a correct Python 3 solution for this coding contest problem. Problem statement You and AOR Ika are preparing for a graph problem in competitive programming. Generating input cases is AOR Ika-chan's job. The input case for that problem is a directed graph of the $ N $ vertices. The vertices are numbered from $ 1 $ to $ N $. Edges may contain self-loops, but not multiple edges. However, AOR Ika suddenly lost communication and couldn't get the original graph. All that remains is the following information: * The number of vertices with degree $ i $ is $ a_i $. That is, the number of vertices ending in $ i $ is $ a_i $. * The number of vertices with degree $ i $ is $ b_i $. That is, the number of vertices starting from $ i $ is $ b_i $. Is there a directed graph that is consistent with the information left behind? Judge it, output YES if it exists, and then output one consistent directed graph. If there are more than one, any one may be output. If it does not exist, output NO. Input constraints $ 1 \ leq n \ leq 50 $ $ 0 \ leq a_i \ leq n $ $ 0 \ leq b_i \ leq n $ sample Sample input 1 3 1 2 0 0 1 2 0 0 Sample output 1 YES YES 0 1 0 0 0 1 0 0 0 Sample input 2 1 Ten Ten Sample output 2 YES YES 0 Sample input 3 2 0 2 0 0 2 0 Sample output 3 YES YES 0 1 Ten Sample input 4 Four 1 3 0 0 0 3 0 0 1 0 Sample output 4 YES YES 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 Sample input 5 1 1 1 0 0 Sample output 5 NO input $ n $ $ a_0 \ cdots a_n $ $ b_0 \ cdots b_n $ output If there is a graph that meets the conditions, output it in the following format. $ e_ {ij} $ should be 1 if there is a directed edge from $ i $ to $ j $, or 0 otherwise. Be careful not to print a blank at the end of the line. YES YES $ e_ {11} \ e_ {12} \ cdots e_ {1n} $ $ e_ {21} \ e_ {22} \ cdots e_ {2n} $ $ \ vdots $ $ e_ {n1} \ e_ {n2} \ cdots e_ {nn} $ If not, output as follows. NO Example Input 3 1 2 0 0 1 2 0 0 Output YES 0 1 0 0 0 1 0 0 0
instruction
0
93,502
13
187,004
"Correct Solution: ``` from operator import itemgetter N = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) cnt_a = 0 cnt_b = 0 for i, (a, b) in enumerate(zip(A, B)): cnt_a += i*a cnt_b += i*b if cnt_a!=cnt_b or not sum(A)==sum(B)==N: print("NO") exit() B_ = [] cumi = 0 for i, b in enumerate(B): for j in range(b): B_.append([cumi, i]) cumi += 1 B_.sort(key=itemgetter(1), reverse=True) Ans = [[0]*N for _ in range(N)] cumi = 0 for i, a in enumerate(A[1:], 1): if len(B_) < i: print("NO") exit() for k in range(a): for j in range(i): B_[j][1] -= 1 if B_[j][1] < 0: print("NO") exit() Ans[B_[j][0]][cumi] = 1 cumi += 1 B_.sort(key=itemgetter(1), reverse=True) print("YES") for ans in Ans: print(*ans) ```
output
1
93,502
13
187,005
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,715
13
187,430
Tags: dp, graphs, greedy Correct Solution: ``` import sys input = sys.stdin.buffer.readline ans = [] for _ in range(int(input())): n = int(input()) c = list(map(int,input().split())) a = list(map(int,input().split())) b = list(map(int,input().split())) res = 0 tmp = c[-1] - 1 pos_x,pos_y = 1,c[-1] for i in range(n-1,0,-1): tmp += 2 pos_x,pos_y = min(a[i],b[i]),max(a[i],b[i]) res = max(res,tmp+pos_y-pos_x) if pos_x==pos_y: tmp = c[i-1] - 1 pos_x,pos_y = 1,c[i-1] else: tmp += pos_x - 1 + c[i-1] - pos_y if c[i-1] - 1 >= tmp: tmp = c[i-1] - 1 pos_x,pos_y = 1,c[i-1] ans.append(res) print(*ans,sep="\n") ```
output
1
93,715
13
187,431
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,716
13
187,432
Tags: dp, graphs, greedy Correct Solution: ``` import os,sys from io import BytesIO,IOBase for _ in range(int(input())): n = int(input()) vert = list(map(int,input().split())) a = list(map(int,input().split())) b = list(map(int,input().split())) dp,ans = -10**10,0 for i in range(1,n): if a[i] == b[i]: dp = 0 else: dp = max(dp+min(a[i],b[i])-1+vert[i-1]-max(b[i],a[i])+2,abs(b[i]-a[i])) ans = max(ans,dp+1+vert[i]) print(ans) ```
output
1
93,716
13
187,433
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,717
13
187,434
Tags: dp, graphs, greedy Correct Solution: ``` for _ in range(int(input())): n = int(input()) c = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) ans = abs(a[1] - b[1]) cur = ans for i in range(1, n): if a[i] == b[i]: ans = max(ans, cur) cur = c[i] + 1 else: pres = c[i] + 1 cur = max(cur + pres - abs(a[i] - b[i]), abs(a[i] - b[i]) + pres) ans = max(ans, cur) ans = max(ans, cur) print(ans) ```
output
1
93,717
13
187,435
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,718
13
187,436
Tags: dp, graphs, greedy Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): for _ in range(int(input())): n = int(input()) vert = list(map(int,input().split())) a = list(map(int,input().split())) b = list(map(int,input().split())) dp,ans = -10**10,0 for i in range(1,n): if a[i] == b[i]: dp = 0 else: dp = max(dp+min(a[i],b[i])-1+vert[i-1]-max(b[i],a[i])+2,abs(b[i]-a[i])) ans = max(ans,dp+1+vert[i]) print(ans) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main() ```
output
1
93,718
13
187,437
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,719
13
187,438
Tags: dp, graphs, greedy Correct Solution: ``` t= int(input().strip()) for i in range(t): n=int(input().strip()) c=list(map(int,input().strip().split())) a=list(map(int,input().strip().split())) b=list(map(int,input().strip().split())) c[0]=0 s=0 m=0 z=0 for k in range(1,n): if b[k]<a[k]: a[k],b[k]=b[k],a[k] for k in range(1,n): if a[k]!=b[k]: m=max(m+a[k]+c[k-1]+1-b[k], b[k]-a[k]+1) s= max(c[k]+m,s) else: z=max(z,s) s=1+c[k] m=1 print(max(z,s)) ```
output
1
93,719
13
187,439
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,720
13
187,440
Tags: dp, graphs, greedy Correct Solution: ``` ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path import sys from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right from itertools import permutations from datetime import datetime from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input() def mi():return map(int,input().split()) def li():return list(mi()) abc='abcdefghijklmnopqrstuvwxyz' abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25} mod=1000000007 #mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def bo(i): return ord(i)-ord('a') def solve(): for _ in range(ii()): n = ii() c = li() a = li() b = li() for i in range(n): if a[i] > b[i]: a[i],b[i] = b[i],a[i] ans = 0 s = b[1]-a[1]+1 for i in range(1,n-1): ans = max(ans,s+c[i]) c1 = a[i+1]+c[i]-b[i+1] s = max(b[i+1]-a[i+1],s+c1) if a[i+1] == b[i+1]: s = 0 s += 1 # print(s,ans) ans =max(ans,s+c[-1]) print(ans) if __name__ =="__main__": solve() ```
output
1
93,720
13
187,441
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,721
13
187,442
Tags: dp, graphs, greedy Correct Solution: ``` for t in range(int(input())): n=int(input()) c=[int(x) for x in input().split()] a=[int(x) for x in input().split()] b=[int(x) for x in input().split()] prev=[0 for i in range(n)] #best=[0 for i in range(n)] best2=0 i=1 x=b[i]-a[i] if(x>0): temp=x+1 prev[i]=temp elif(x==0): prev[i]=1 else: temp=-x+1 prev[i]=temp #best[i]=max(prev[i]+c[i],best[i-1]) best2=max(prev[i]+c[i],best2) for i in range(2,n): x=b[i]-a[i] if(x>0): temp=max(x+1,prev[i-1]+c[i-1]-x+1) prev[i]=temp elif(x==0): prev[i]=1 else: temp=max(-x+1,prev[i-1]+c[i-1]+x+1) prev[i]=temp #best[i]=max(prev[i]+c[i],best[i-1]) best2=max(prev[i]+c[i],best2) #print(best) #print(prev) print(best2) ```
output
1
93,721
13
187,443
Provide tags and a correct Python 3 solution for this coding contest problem. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity.
instruction
0
93,722
13
187,444
Tags: dp, graphs, greedy Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) c = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) maxi=0 cnt=c[n-1] for i in range(n-1,0,-1): if a[i]>b[i]: a[i],b[i]=b[i],a[i] if a[i]==b[i]: cnt+=1 maxi=max(maxi,cnt) cnt=c[i-1] else: if i==1: cnt+=b[i]-a[i]+1 maxi=max(maxi,cnt) else: cnt1=cnt cnt1+=b[i]-a[i]+1 cnt+=a[i]+(c[i-1]-b[i]+1) maxi=max(maxi,cnt) maxi=max(maxi,cnt1) if cnt<c[i-1]: cnt=c[i-1] print(maxi) ```
output
1
93,722
13
187,445
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` for t in range(int(input())): n=int(input()) c=list(map(int,input().split())) a=list(map(int,input().split())) b=list(map(int,input().split())) curlen=0 lstcur=0 ans=0 for i in range(1,n): curlen=abs(a[i]-b[i]) +1 + c[i] if a[i]!=b[i]: curlen=max(curlen, c[i] + 1 + lstcur - abs(a[i]-b[i])) lstcur=curlen ans=max(ans,curlen) lstcur=curlen print(ans) ```
instruction
0
93,723
13
187,446
Yes
output
1
93,723
13
187,447
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` # template begins ##################################### from io import BytesIO, IOBase import sys import math import os # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") def mint(): return map(int, input().split()) def mfloat(): return map(float, input().split()) ##################################### # template ends # Use the recursion snippet if heavy recursion is needed (depth>1000) def solve(): n=int(input()) *c,=mint() *a,=mint() *b,=mint() # dp? # Can we get the longest cycle ending on the given graph? if b[1]<a[1]:a[1],b[1]=b[1],a[1] ans=c[1]+2+b[1]-a[1]-1 current_length=ans for i in range(2, n): if b[i]<a[i]:a[i],b[i]=b[i],a[i] if b[i]!=a[i]: current_length=max(current_length+2+c[i]-1 - (b[i]-a[i]), b[i]-a[i]+2+c[i]-1) # print(current_length, i) else: current_length=2+c[i]-1 ans=max(ans, current_length) print(ans) def main(): t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main() ```
instruction
0
93,724
13
187,448
Yes
output
1
93,724
13
187,449
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` for tc in range(int(input())): n = int(input()) c = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) k = [0] for i in range(1, n): if a[i] == b[i]: k.append(2+c[i]-1) else: n1 = abs(a[i]-b[i])+2+c[i]-1 # start afresh n2 = k[i-1]-abs(a[i]-b[i])+2+c[i]-1 k.append(max(n1, n2)) print(max(k)) ```
instruction
0
93,725
13
187,450
Yes
output
1
93,725
13
187,451
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` t= int(input().strip()) for i in range(t): n=int(input().strip()) c=list(map(int,input().strip().split())) a=list(map(int,input().strip().split())) b=list(map(int,input().strip().split())) s=0 m=0 z=0 for k in range(1,n): if b[k]<a[k]: a[k],b[k]=b[k],a[k] for k in range(1,n): if k==1: if a[k]==b[k]: s=1+c[k] m=1 continue else: m=b[k]-a[k]+1 s=c[k]+m continue if a[k]!=b[k]: m=max(m+a[k]+c[k-1]+1-b[k], b[k]-a[k]+1) s= max(c[k]+m,s) else: z=max(z,s) s=1+c[k] m=1 print(max(z,s)) ```
instruction
0
93,726
13
187,452
Yes
output
1
93,726
13
187,453
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log2, ceil from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from bisect import insort from collections import Counter from collections import deque from heapq import heappush,heappop,heapify from itertools import permutations,combinations from itertools import accumulate as ac mod = int(1e9)+7 #mod = 998244353 ip = lambda : int(stdin.readline()) inp = lambda: map(int,stdin.readline().split()) ips = lambda: stdin.readline().rstrip() out = lambda x : stdout.write(str(x)+"\n") t = ip() for _ in range(t): n = ip() c = list(inp()) a = list(inp()) b = list(inp()) dp = [0]*n ele = [] dp[0] = c[0]-1 for i in range(1,n): if a[i] == b[i]: dp[i] = c[i]+2-1 else: minus = abs(a[i]-b[i]) dp[i] = dp[i-1]-minus+ c[i]+2 -1 ele.append(c[i]+minus+1) dp.pop(0) ans = -float('inf') ans = max(ans,max(dp)) if len(ele) != 0: ans = max(ans,max(ele)) print(ans) ```
instruction
0
93,727
13
187,454
No
output
1
93,727
13
187,455
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` from math import ceil def solve(n, c, a, b): t = 0 r = c[-1] for i in range(n-1, 0, -1): if a[i] == b[i]: r+= 1 if r > t: t = r r = c[i-1] else: if r+abs(a[i]-b[i])+1 > t: t = r + abs(a[i]-b[i])+1 if c[i]+ abs(a[i]-b[i])+1 > t: t = c[i]+ abs(a[i]-b[i])+1 r+= c[i-1] - abs(a[i]-b[i]) +1 print(t) for _ in range(int(input())): n = int(input()) c = list(map(int,input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) solve(n, c, a, b) ```
instruction
0
93,728
13
187,456
No
output
1
93,728
13
187,457
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) c = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) initialSpan = 0 maxSpan = 0 for i in range(1, n): if(b[i]!=a[i]): initialSpan+=c[i]+1 initialSpan-=abs(b[i]-a[i]) secSpan = c[i]+abs(b[i]-a[i])+1 if(secSpan>initialSpan): maxSpan = max(maxSpan, initialSpan) maxSpan = max(maxSpan, secSpan) initialSpan = secSpan else: initialSpan = c[i]+1 maxSpan = max(maxSpan, initialSpan) maxSpan = max(maxSpan, initialSpan) print(maxSpan) ```
instruction
0
93,729
13
187,458
No
output
1
93,729
13
187,459
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i. Now you decided to unite chains in one graph in the following way: 1. the first chain is skipped; 2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain; 3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain. <image> Picture of the first test case. Dotted lines are the edges added during uniting process Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the single integer n (2 ≤ n ≤ 10^5) — the number of chains you have. The second line of each test case contains n integers c_1, c_2, ..., c_n (2 ≤ c_i ≤ 10^9) — the number of vertices in the corresponding chains. The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 ≤ a_i ≤ c_{i - 1}). The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 ≤ b_i ≤ c_{i - 1}). Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, print the length of the longest simple cycle. Example Input 3 4 3 4 3 3 -1 1 2 2 -1 2 2 3 2 5 6 -1 5 -1 1 3 3 5 2 -1 1 1 -1 3 5 Output 7 11 8 Note In the first test case, the longest simple cycle is shown below: <image> We can't increase it with the first chain, since in such case it won't be simple — the vertex 2 on the second chain will break simplicity. Submitted Solution: ``` t= int(input().strip()) for i in range(t): n=int(input().strip()) c=list(map(int,input().strip().split())) a=list(map(int,input().strip().split())) b=list(map(int,input().strip().split())) l=[] s=0 m=0 for k in range(1,n): if b[k]<a[k]: a[k],b[k]=b[k],a[k] print(a,b,c) for k in range(1,n): if k==1: if a[k]==b[k]: l.append(s) s=1+c[k] m=1 l.append(s) continue else: m=b[k]-a[k]+1 s=c[k]+m l.append(s) continue if a[k]!=b[k]: m=max(m+a[k]+c[k-1]+1-b[k], b[k]-a[k]+1) s= c[k]+m print("m ",m) l.append(s) else: l.append(s) s=2+c[k] m=1 l.append(s) print(l) print(max(l)) ```
instruction
0
93,730
13
187,460
No
output
1
93,730
13
187,461
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,913
13
187,826
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` def connected_components(n, graph): components, visited = [], [False] * n def dfs(start): component, stack = [], [start] while stack: start = stack[-1] if visited[start]: stack.pop() continue else: visited[start] = True component.append(start) for i in graph[start]: if not visited[i]: stack.append(i) return component for i in range(n): if not visited[i]: components.append(dfs(i)) return components # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase 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") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from collections import deque def bfs(graph, n, alpha, used, color): """Breadth first search on a graph!""" q = deque([alpha]) used[alpha] = True z, o = 0, 0 while q: v = q.popleft() if color[v] == -1: color[v] = 0 z += 1 for u in graph[v]: if not used[u]: used[u] = True q.append(u) if color[u] == color[v]:return False if color[u] == -1: if color[v] == 1:z+=1 else: o += 1 color[u] = (color[v] + 1) % 2 return (used, color, z, o) def shortest_path(graph, alpha, omega): """Returns the shortest path between two vertices!""" used, dist, parents = bfs(graph, alpha) if not used[omega]: return [] path = [omega] v = omega while parents[v] != -1: path += [parents[v]] v = parents[v] return path[::-1] for _ in range(int(input()) if not True else 1): #n = int(input()) n, m = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #e, f = map(int, input().split()) graph = [[] for __ in range(n+1)] ml = 0 for i in range(m): x, y = map(int, input().split()) graph[x] += [y] graph[y] += [x] ml = max(ml, len(graph[x]), len(graph[y])) if ml == 0: print(3, (n*(n-1)*(n-2))//6) continue if ml == 1: x=0 for i in graph: if len(i) == 1: x += 1 print(2, (x//2)*(n-2)) continue # ans will be 1 if no odd cycle else 0 cn = connected_components(n+1, graph) bipartite = True ans = 0 used = [0]*(n+1) color = [-1]*(n+1) for i in range(1, len(cn)): j = cn[i][0] ooff = bfs(graph, n+1, j, used, color) if not ooff: bipartite = False break used, color, z, o = ooff ans += (z*(z-1)) // 2 + (o*(o-1))//2 if not bipartite: print(0, 1) continue # ans = 1 print(1, ans) ```
output
1
93,913
13
187,827
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,914
13
187,828
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` import sys import threading threading.stack_size(67108864) sys.setrecursionlimit(100500) def nc2(k): return k * (k - 1) // 2 def solve(): def dfs(u): comp[u] = n_comp for v in g[u]: if color[v] == 0: color[v] = 3 - color[u] dfs(v) elif color[u] == color[v]: return True return False def check(g, color, n): for v in range(1, n + 1): for u in g[v]: if color[u] == color[v]: return False return True n, m = map(int, input().split()) g = dict() for i in range(1, n + 1): g[i] = set() for i in range(m): a, b = map(int, input().split()) g[a].add(b) g[b].add(a) color = [0] * (n + 1) comp = [0] * (n + 1) n_comp = 0 for u in range(1, n + 1): if color[u] == 0: n_comp += 1 color[u] = 1 if dfs(u): print(0, 1) return if not check(g, color, n): print(0, 1) return counts = [0] * (n_comp + 1) counts_1 = [0] * (n_comp + 1) counts_2 = [0] * (n_comp + 1) for i in range(1, n + 1): counts[comp[i]] += 1 if color[i] == 1: counts_1[comp[i]] += 1 else: counts_2[comp[i]] += 1 c = max(counts) if c == 1: print(3, n * (n - 1) * (n - 2) // 6) elif c == 2: print(2, m * (n - 2)) elif c >= 3: ans = 0 for i in range(1, n_comp + 1): if counts[i] >= 3: ans += nc2(counts_1[i]) + nc2(counts_2[i]) print(1, ans) thread = threading.Thread(target=solve) thread.start() ```
output
1
93,914
13
187,829
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,915
13
187,830
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` # 解説AC # 二部グラフでないグラフの性質や,パスの長さを考察する def main(): N, M = (int(i) for i in input().split()) par = [i for i in range(N)] size = [1 for i in range(N)] def find(x): if par[x] == x: return x else: par[x] = find(par[x]) size[x] = size[par[x]] return par[x] def same(x, y): return find(x) == find(y) def union(x, y): x = find(x) y = find(y) if x == y: return if size[x] < size[y]: x, y = y, x size[x] += size[y] par[y] = x def get_size(x): return size[find(x)] G = [[] for _ in range(N)] for _ in range(M): a, b = (int(i) for i in input().split()) G[a-1].append(b-1) G[b-1].append(a-1) union(a-1, b-1) S = [False]*4 for i in range(N): S[min(3, get_size(i))] = True if S[3]: break t = 0 if S[3]: t = 1 elif S[2]: t = 2 else: t = 3 color = [-1]*N def dfs(s): stack = [s] color[s] = 0 b = 1 w = 0 while stack: v = stack.pop() for u in G[v]: if color[u] != -1: if color[u] == color[v]: return False, b*w continue color[u] = color[v] ^ 1 if color[u] == 0: b += 1 else: w += 1 stack.append(u) return True, b*(b-1)//2 + w*(w-1)//2 is_bipartite, _ = dfs(0) if is_bipartite: w = 0 if t == 3: w = N*(N-1)*(N-2)//3//2 elif t == 2: used = [False]*N for i in range(N): if not used[find(i)] and get_size(i) == 2: w += (N-2) used[find(i)] = True elif t == 1: used = [False]*N color = [-1]*N for i in range(N): if not used[find(i)] and get_size(i) >= 3: _, ways = dfs(i) w += ways used[find(i)] = True print(t, w) else: print(0, 1) if __name__ == '__main__': main() ```
output
1
93,915
13
187,831
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,916
13
187,832
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right import time from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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") from collections import defaultdict as dd, deque as dq, Counter as dc import math, string start_time = time.time() def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] MOD = 998244353 #MOD = 10**9+7 def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc """ Scenarios: 0) no edges, answer is (3,N choose 3) 1) already have an odd cycle: answer is (0,1) 2) no odd cycle, but a connected component of at least size 3: answer is (1,W), where W is the number of paths of length 2 number of paths of length 2 = sum(x*(x-1)//2) where x is the degree of each vertex 3) no odd cycle, no component of size 3 or more, some isolated edges: answer is (2,M*(N-2)) How to count odd cycles """ def solve(): N, M = getInts() #case 0 if not M: print(3,N*(N-1)*(N-2)//6) return graph = dd(set) for m in range(M): A, B = getInts() A -= 1 B -= 1 graph[A].add(B) graph[B].add(A) parent = [-1]*N levels = [-1]*N edges = set() global flag flag = False @bootstrap def dfs(node,level): global flag global odds global evens levels[node] = level if level: odds += 1 else: evens += 1 visited.add(node) nodes.remove(node) for neigh in graph[node]: if neigh in visited and neigh != parent[node] and levels[neigh] == level: flag = True if neigh not in visited: parent[neigh] = node yield dfs(neigh,level^1) yield ans = 0 nodes = set(list(range(N))) while nodes: node = next(iter(nodes)) visited = set() global odds odds = 0 global evens evens = 0 dfs(node,0) ans += odds*(odds-1)//2 + evens*(evens-1)//2 if flag: print(0,1) return if ans: print(1,ans) return if edges: print(1,len(edges)) return print(2,M*(N-2)) return #for _ in range(getInt()): solve() #solve() #print(time.time()-start_time) ```
output
1
93,916
13
187,833
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,917
13
187,834
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` def main(): N, M = (int(i) for i in input().split()) par = [i for i in range(N)] size = [1 for i in range(N)] def find(x): if par[x] == x: return x else: par[x] = find(par[x]) size[x] = size[par[x]] return par[x] def same(x, y): return find(x) == find(y) def union(x, y): x = find(x) y = find(y) if x == y: return if size[x] < size[y]: x, y = y, x size[x] += size[y] par[y] = x def get_size(x): return size[find(x)] G = [[] for _ in range(N)] for _ in range(M): a, b = (int(i) for i in input().split()) G[a-1].append(b-1) G[b-1].append(a-1) union(a-1, b-1) S = [False]*4 for i in range(N): S[min(3, get_size(i))] = True if S[3]: break t = 0 if S[3]: t = 1 elif S[2]: t = 2 else: t = 3 color = [-1]*N def dfs(s): stack = [s] color[s] = 0 b = 1 w = 0 while stack: v = stack.pop() for u in G[v]: if color[u] != -1: if color[u] == color[v]: return False, b*w continue color[u] = color[v] ^ 1 if color[u] == 0: b += 1 else: w += 1 stack.append(u) return True, b*(b-1)//2 + w*(w-1)//2 is_bipartite, _ = dfs(0) if is_bipartite: w = 0 if t == 3: w = N*(N-1)*(N-2)//3//2 elif t == 2: used = [False]*N for i in range(N): if not used[find(i)] and get_size(i) == 2: w += (N-2) used[find(i)] = True elif t == 1: used = [False]*N color = [-1]*N for i in range(N): if not used[find(i)] and get_size(i) >= 3: _, ways = dfs(i) w += ways used[find(i)] = True print(t, w) else: print(0, 1) if __name__ == '__main__': main() ```
output
1
93,917
13
187,835
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,918
13
187,836
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` n, m = [int(x) for x in input().split()] E = {i:[] for i in range(n)} for i in range(m): u, v = [int(x)-1 for x in input().split()] E[v].append(u) E[u].append(v) def dfs(): visited = [False for i in range(n)] colour = [0 for i in range(n)] ans = 0 for v in range(n): if visited[v]: continue stack = [(v, 0)] part = [0, 0] while stack: node, c = stack.pop() if not visited[node]: part[c] += 1 visited[node] = True colour[node] = c stack.extend((u,c^1) for u in E[node]) elif c != colour[node]: return (0, 1) ans += (part[0]*(part[0] - 1) + part[1]*(part[1] - 1)) // 2 return (1, ans) if m == 0: print(3, n*(n-1)*(n-2)//6) elif max(len(E[v]) for v in E) == 1: print(2, m*(n-2)) else: ans = dfs() print(ans[0], ans[1]) ```
output
1
93,918
13
187,837
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,919
13
187,838
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` def read_data(): n, m = map(int, input().split()) Es = [[] for v in range(n)] for e in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 Es[a].append(b) Es[b].append(a) return n, m, Es def solve(n, m, Es): if m == 0: return 3, n * (n - 1) * (n - 2) // 6 if max(map(len, Es)) == 1: return 2, m * (n-2) patterns = 0 color = [0] * n for u in range(n): if color[u]: continue color[u] = 1 stack = [u] n_color = [1, 0] while stack: v = stack.pop() prev_color = color[v] for w in Es[v]: current_color = color[w] if current_color == prev_color: return 0, 1 if current_color == 0: color[w] = - prev_color n_color[(prev_color + 1)//2] += 1 stack.append(w) n_even = n_color[0] n_odd = n_color[1] patterns += n_even * (n_even - 1) // 2 + n_odd * (n_odd - 1) // 2 return 1, patterns if __name__ == '__main__': n, m, Es = read_data() print(*solve(n, m, Es)) ```
output
1
93,919
13
187,839
Provide tags and a correct Python 3 solution for this coding contest problem. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice.
instruction
0
93,920
13
187,840
Tags: combinatorics, dfs and similar, graphs, math Correct Solution: ``` g = [[] for _ in range(100005)] n, m = map(int, input().split(' ')) for i in range(m): a, b = map(int, input().split(' ')) g[a].append(b) g[b].append(a) colour = [0] * 100005 v = [0] * 100005 cycle = False two = True twos = 0 ones = 0 ans = 0 for i in range(1, n+1): cs = 0 c1 = 0 c2 = 0 if (not colour[i]): q = [i] colour[i] = 1 while q: cs += 1 top = q.pop() if colour[top] == 1: c1 += 1 else: c2 += 1 for j in g[top]: if colour[j] == colour[top]: cycle = True elif colour[j] == 0: colour[j] = -colour[top] q = [j] + q if cs > 2: two = False ans += ((c1*(c1-1))//2 + (c2*(c2-1))//2) if cs == 2: twos += 1 if cs == 1: ones += 1 if cycle: print(0, 1) quit() if m == 0: print(3, (n*(n-1)*(n-2)//6)) quit() if two: print(2, twos*ones + 4 * (twos * (twos - 1) // 2)) quit() sumx = 0 for i in range(1, n+1): ll = len(g[i]) sumx += ll * (ll-1) // 2 print(1, ans) ```
output
1
93,920
13
187,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice. Submitted Solution: ``` import sys import threading threading.stack_size(67108864) sys.setrecursionlimit(100500) def nc2(k): return k * (k - 1) // 2 def solve(): def dfs(u): comp[u] = n_comp for v in g[u]: if color[v] == 0: color[v] = 3 - color[u] dfs(v) elif color[u] == color[v]: return True return False n, m = map(int, input().split()) g = dict() for i in range(1, n + 1): g[i] = set() for i in range(m): a, b = map(int, input().split()) g[a].add(b) g[b].add(a) bad_graph = False color = [0] * (n + 1) comp = [0] * (n + 1) n_comp = 0 for u in range(1, n + 1): if color[u] == 0: n_comp += 1 color[u] = 1 if dfs(u): print(0, 1) return counts = [0] * (n_comp + 1) counts_1 = [0] * (n_comp + 1) counts_2 = [0] * (n_comp + 1) for i in range(1, n + 1): counts[comp[i]] += 1 if color[i] == 1: counts_1[comp[i]] += 1 else: counts_2[comp[i]] += 1 c = max(counts) if c == 1: print(3, n * (n - 1) * (n - 2) // 6) elif c == 2: print(2, m * (n - 2)) elif c >= 3: ans = 0 for i in range(1, n_comp + 1): if counts[i] >= 3: ans += nc2(counts_1[i]) + nc2(counts_2[i]) print(1, ans) thread = threading.Thread(target=solve) thread.start() ```
instruction
0
93,921
13
187,842
No
output
1
93,921
13
187,843
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task. Input The first line of the input contains two integers n and m (<image> — the number of vertices in the graph and the number of edges in the graph. Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n) — the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space. It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected. Output Print in the first line of the output two space-separated integers t and w — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this. Examples Input 4 4 1 2 1 3 4 2 4 3 Output 1 2 Input 3 3 1 2 2 3 3 1 Output 0 1 Input 3 0 Output 3 1 Note The simple cycle is a cycle that doesn't contain any vertex twice. Submitted Solution: ``` __author__ = 'Andrey' import sys sys.setrecursionlimit(100500) n, m = map(int, input().split()) g = dict() for i in range(1, n + 1): g[i] = set() for i in range(m): a, b = map(int, input().split()) g[a].add(b) g[b].add(a) bad_graph = False color = [0] * (n + 1) def dfs(u): global bad_graph for v in g[u]: if color[v] == 0: color[v] = 3 - color[u] dfs(v) elif color[u] == color[v]: bad_graph = True for u in range(1, n + 1): if color[u] == 0: color[u] = 1 dfs(u) if bad_graph: print(0, 1) else: nothing = 0 ans = -1 total = 0 set_1 = set() set_2 = set() for i in range(1, n + 1): c = 0 c_1 = 0 if color[i] == 1: for u in g[i]: c += 1 if u in set_1: c_1 += 1 set_1.add(u) if color[i] == 2: for u in g[i]: c += 1 if u in set_2: c_1 += 1 set_2.add(u) if c == 0: nothing += 1 if ans == 1: if c >= 2: total += c * (c - 1) // 2 - c_1 * (c_1 - 1) // 2 if ans == 2: if c >= 2: total = c * (c - 1) // 2 - c_1 * (c_1 - 1) // 2 ans = 1 if c == 1 and len(g[i]) == 1: total += n - 2 if ans == -1: if c >= 2: ans = 1 total = c * (c - 1) // 2 - c_1 * (c_1 - 1) // 2 if c == 1 and len(g[i]) == 1: ans = 2 total = n - 2 if nothing == n: print(n * (n - 1) * (n - 2) // 6) else: print(ans, total) ```
instruction
0
93,922
13
187,844
No
output
1
93,922
13
187,845