message
stringlengths
2
22.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
16
109k
cluster
float64
1
1
__index_level_0__
int64
32
217k
Provide a correct Python 3 solution for this coding contest problem. Problem I Starting a Scenic Railroad Service Jim, working for a railroad company, is responsible for planning a new tourist train service. He is sure that the train route along a scenic valley will arise a big boom, but not quite sure how big the boom will be. A market survey was ordered and Jim has just received an estimated list of passengers' travel sections. Based on the list, he'd like to estimate the minimum number of train seats that meets the demand. Providing as many seats as all of the passengers may cost unreasonably high. Assigning the same seat to more than one passenger without overlapping travel sections may lead to a great cost cutback. Two different policies are considered on seat assignments. As the views from the train windows depend on the seat positions, it would be better if passengers can choose a seat. One possible policy (named `policy-1') is to allow the passengers to choose an arbitrary seat among all the remaining seats when they make their reservations. As the order of reservations is unknown, all the possible orders must be considered on counting the required number of seats. The other policy (named `policy-2') does not allow the passengers to choose their seats; the seat assignments are decided by the railroad operator, not by the passengers, after all the reservations are completed. This policy may reduce the number of the required seats considerably. Your task is to let Jim know how di erent these two policies are by providing him a program that computes the numbers of seats required under the two seat reservation policies. Let us consider a case where there are four stations, S1, S2, S3, and S4, and four expected passengers $p_1$, $p_2$, $p_3$, and $p_4$ with the travel list below. passenger | from | to ---|---|--- $p_1$ | S1 | S2 $p_2$ | S2 | S3 $p_3$ | S1 | S3 $p_4$ | S3 | S4 The travel sections of $p_1$ and $p_2$ do not overlap, that of $p_3$ overlaps those of $p_1$ and $p_2$, and that of $p_4$ does not overlap those of any others. Let's check if two seats would suffice under the policy-1. If $p_1$ books a seat first, either of the two seats can be chosen. If $p_2$ books second, as the travel section does not overlap that of $p_1$, the same seat can be booked, but the other seat may look more attractive to $p_2$. If $p_2$ reserves a seat different from that of $p_1$, there will remain no available seats for $p_3$ between S1 and S3 (Figure I.1). <image> Figure I.1. With two seats With three seats, $p_3$ can find a seat with any seat reservation combinations by $p_1$ and $p_2$. $p_4$ can also book a seat for there are no other passengers between S3 and S4 (Figure I.2). <image> Figure I.2. With three seats For this travel list, only three seats suffice considering all the possible reservation orders and seat preferences under the policy-1. On the other hand, deciding the seat assignments after all the reservations are completed enables a tight assignment with only two seats under the policy-2 (Figure I.3). <image> Figure I.3. Tight assignment to two seats Input The input consists of a single test case of the following format. $n$ $a_1$ $b_1$ ... $a_n$ $b_n$ Here, the first line has an integer $n$, the number of the passengers in the estimated list of passengers' travel sections ($1 \leq n \leq 200 000$). The stations are numbered starting from 1 in their order along the route. Each of the following $n$ lines describes the travel for each passenger by two integers, the boarding and the alighting station numbers, $a_i$ and $b_i$, respectively ($1 \leq a_i < b_i \leq 100 000$). Note that more than one passenger in the list may have the same boarding and alighting stations. Output Two integers $s_1$ and $s_2$ should be output in a line in this order, separated by a space. $s_1$ and $s_2$ are the numbers of seats required under the policy-1 and -2, respectively. Sample Input 1 4 1 3 1 3 3 6 3 6 Sample Output 1 2 2 Sample Input 2 4 1 2 2 3 1 3 3 4 Sample Output 2 3 2 Sample Input 3 10 84 302 275 327 364 538 26 364 29 386 545 955 715 965 404 415 903 942 150 402 Sample Output 3 6 5 Example Input 4 1 3 1 3 3 6 3 6 Output 2 2
instruction
0
49,565
1
99,130
"Correct Solution: ``` from bisect import bisect n = int(input()) P = [list(map(int, input().split())) for i in range(n)] M = 10**5+1 def policy1(P): A = [a for a, b in P] B = [b for a, b in P] A.sort(); B.sort() ans = 1 for a, b in P: left = bisect(B, a) right = n - bisect(A, b-1) ans = max(ans, n - (left + right)) return ans def policy2(P): D = [0]*M for a, b in P: D[a] += 1 D[b] -= 1 for i in range(1, M): D[i] += D[i-1] return max(D) print(policy1(P), policy2(P)) ```
output
1
49,565
1
99,131
Provide a correct Python 3 solution for this coding contest problem. Problem I Starting a Scenic Railroad Service Jim, working for a railroad company, is responsible for planning a new tourist train service. He is sure that the train route along a scenic valley will arise a big boom, but not quite sure how big the boom will be. A market survey was ordered and Jim has just received an estimated list of passengers' travel sections. Based on the list, he'd like to estimate the minimum number of train seats that meets the demand. Providing as many seats as all of the passengers may cost unreasonably high. Assigning the same seat to more than one passenger without overlapping travel sections may lead to a great cost cutback. Two different policies are considered on seat assignments. As the views from the train windows depend on the seat positions, it would be better if passengers can choose a seat. One possible policy (named `policy-1') is to allow the passengers to choose an arbitrary seat among all the remaining seats when they make their reservations. As the order of reservations is unknown, all the possible orders must be considered on counting the required number of seats. The other policy (named `policy-2') does not allow the passengers to choose their seats; the seat assignments are decided by the railroad operator, not by the passengers, after all the reservations are completed. This policy may reduce the number of the required seats considerably. Your task is to let Jim know how di erent these two policies are by providing him a program that computes the numbers of seats required under the two seat reservation policies. Let us consider a case where there are four stations, S1, S2, S3, and S4, and four expected passengers $p_1$, $p_2$, $p_3$, and $p_4$ with the travel list below. passenger | from | to ---|---|--- $p_1$ | S1 | S2 $p_2$ | S2 | S3 $p_3$ | S1 | S3 $p_4$ | S3 | S4 The travel sections of $p_1$ and $p_2$ do not overlap, that of $p_3$ overlaps those of $p_1$ and $p_2$, and that of $p_4$ does not overlap those of any others. Let's check if two seats would suffice under the policy-1. If $p_1$ books a seat first, either of the two seats can be chosen. If $p_2$ books second, as the travel section does not overlap that of $p_1$, the same seat can be booked, but the other seat may look more attractive to $p_2$. If $p_2$ reserves a seat different from that of $p_1$, there will remain no available seats for $p_3$ between S1 and S3 (Figure I.1). <image> Figure I.1. With two seats With three seats, $p_3$ can find a seat with any seat reservation combinations by $p_1$ and $p_2$. $p_4$ can also book a seat for there are no other passengers between S3 and S4 (Figure I.2). <image> Figure I.2. With three seats For this travel list, only three seats suffice considering all the possible reservation orders and seat preferences under the policy-1. On the other hand, deciding the seat assignments after all the reservations are completed enables a tight assignment with only two seats under the policy-2 (Figure I.3). <image> Figure I.3. Tight assignment to two seats Input The input consists of a single test case of the following format. $n$ $a_1$ $b_1$ ... $a_n$ $b_n$ Here, the first line has an integer $n$, the number of the passengers in the estimated list of passengers' travel sections ($1 \leq n \leq 200 000$). The stations are numbered starting from 1 in their order along the route. Each of the following $n$ lines describes the travel for each passenger by two integers, the boarding and the alighting station numbers, $a_i$ and $b_i$, respectively ($1 \leq a_i < b_i \leq 100 000$). Note that more than one passenger in the list may have the same boarding and alighting stations. Output Two integers $s_1$ and $s_2$ should be output in a line in this order, separated by a space. $s_1$ and $s_2$ are the numbers of seats required under the policy-1 and -2, respectively. Sample Input 1 4 1 3 1 3 3 6 3 6 Sample Output 1 2 2 Sample Input 2 4 1 2 2 3 1 3 3 4 Sample Output 2 3 2 Sample Input 3 10 84 302 275 327 364 538 26 364 29 386 545 955 715 965 404 415 903 942 150 402 Sample Output 3 6 5 Example Input 4 1 3 1 3 3 6 3 6 Output 2 2
instruction
0
49,566
1
99,132
"Correct Solution: ``` #!usr/bin/env python3 from collections import defaultdict from collections import deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS():return list(map(list, sys.stdin.readline().split())) def S(): return list(sys.stdin.readline())[:-1] def IR(n): l = [None for i in range(n)] for i in range(n):l[i] = I() return l def LIR(n): l = [None for i in range(n)] for i in range(n):l[i] = LI() return l def SR(n): l = [None for i in range(n)] for i in range(n):l[i] = S() return l def LSR(n): l = [None for i in range(n)] for i in range(n):l[i] = LS() return l sys.setrecursionlimit(1000000) mod = 1000000007 #A def A(): n,k = LI() ans = 0 for l in range(1,n+1): for i in range(1000): if i*k > l:break j = l-i*k+i if j%2: j //= 2 j += 1 s = 1 for a in range(i): s *= j-a s //= a+1 ans += s print(ans) return #B def B(): return #C def C(): while 1: n = I() if n == 0: break v = [input().split() for i in range(n)] d = defaultdict(int) f = [[1 for j in range(n)] for i in range(n)] i = 0 s = 0 while i < n: v[i][1] = int(v[i][1]) v[i][2] = int(v[i][2]) if v[i][2] == 0: s += v[i][1] v.pop(i) n -= 1 else: d[v[i][0]] = i i += 1 for i in range(n): for j in v[i][3:]: f[i][d[j]] = 0 e = [[] for i in range(n)] for i in range(n): for j in range(n): if i == j:continue if f[i][j]: e[i].append(j) for i in e: print(i) print(ans) return #D def D(): n = I() s = [0 for i in range(100001)] l = LIR(n) l.sort(key = lambda x:x[1]) r = [l[i][0] for i in range(n)] r.sort() f = [0 for i in range(100001)] for a,b in l: s[a] += 1 s[b] -= 1 f[b] += 1 for i in range(100000): s[i+1] += s[i] f[i+1] += f[i] ans = 0 for a,b in l: ri = bisect.bisect_left(r,b) ri = n-ri le = f[a] ans = max(ans,n-(ri+le)) print(ans,max(s)) return #E def E(): n = I() c = LI() f = [[i,c[i]] for i in range(n)] f.sort(key = lambda x:x[1]) v = [[] for i in range(n)] m = I() for i in range(m): a,b = LI() a -= 1 b -= 1 v[a].append(b) v[b].append(a) q = deque() bfs_map = [1 for i in range(n)] ans = [0 for i in range(n)] for i,j in f: if not bfs_map[i]:continue q.append(i,-1) bfs_map[i] = 0 ans[i] = 1 while q: x,pre = q.popleft() for y in v[x]: if bfs_map[y]: if x == 0: bfs_map[y] = 0 q.append(y) print(sum(ans)) return #F def F(): return #G def G(): return #H def H(): return #I def I_(): return #J def J(): return #Solve if __name__ == "__main__": D() ```
output
1
49,566
1
99,133
Provide a correct Python 3 solution for this coding contest problem. Divide and rule Taro, Hanako, and Jiro rule the JAG Kingdom together. There are N cities in the JAG Kingdom, some of which are connected by two-way roads. You can always reach all the other cities from any city via one or more roads. One day, Taro and Hanako finally made a mistake and decided to share the city and govern it. However, I don't even like the fact that the city governed by Taro and the city governed by Hanako are directly connected by a single road because they have become so bad. Therefore, we decided to share the governing towns so as to satisfy the following conditions. * Any pair of towns governed by Taro and Hanako are not directly connected by roads. This is because the relationship between Taro and Hanako is insanely bad. * Towns governed by the same person are not directly connected by roads. This is to encourage diplomacy by obliging the passage under the control of others. * The total number of towns governed by Taro and the total number of towns governed by Hanako must be the same. This is because if the total number is not equal, the relationship between Taro and Hanako will be even worse. Here, Mr. Jiro is very open-minded, so the total number of cities governed by Mr. Jiro can be any number. If the division meets the above conditions, the three people can be convinced to rule, and even if there are no cities governed by someone, there is no complaint. At this time, create a program that enumerates all possible numbers as the total number of cities governed by Mr. Taro (= the total number of cities governed by Mr. Hanako). Input The input consists of multiple datasets. The maximum number of datasets is 50. Each data set is represented in the following format. > N M u1 v1 ... uM vM The first line consists of two integers N (2 ≤ N ≤ 103) and M (1 ≤ M ≤ 103), which represent the number of cities and the number of roads, respectively. The i-th line of the following M lines consists of two integers ui and vi (1 ≤ ui <vi ≤ N), indicating that the i-th road connects the city ui and the city vi in ​​both directions. Here, it is guaranteed that one city can always reach all other cities via one or more roads. Also, no multiple roads connecting pairs of the same city will be given. That is, (ui, vi) ≠ (uj, vj) is satisfied for all 1 ≤ i <j ≤ M. The end of the input is represented by a line of two zeros. Output For each dataset, if there are K possible total numbers of cities governed by Taro, first output K on the first line, then output the possible total number on each line in ascending order. Sample Input 6 7 1 2 14 twenty three twenty five 3 4 4 5 4 6 twenty one 1 2 3 3 1 2 13 twenty three 4 3 1 2 twenty three 3 4 5 4 1 2 twenty three 3 4 4 5 0 0 Output for the Sample Input 2 1 2 0 0 1 1 1 1 Example Input 6 7 1 2 1 4 2 3 2 5 3 4 4 5 4 6 2 1 1 2 3 3 1 2 1 3 2 3 4 3 1 2 2 3 3 4 5 4 1 2 2 3 3 4 4 5 0 0 Output 2 1 2 0 0 1 1 1 1
instruction
0
49,583
1
99,166
"Correct Solution: ``` #!usr/bin/env python3 from collections import defaultdict from collections import deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS():return list(map(list, sys.stdin.readline().split())) def S(): return list(sys.stdin.readline())[:-1] def IR(n): l = [None for i in range(n)] for i in range(n):l[i] = I() return l def LIR(n): l = [None for i in range(n)] for i in range(n):l[i] = LI() return l def SR(n): l = [None for i in range(n)] for i in range(n):l[i] = S() return l def LSR(n): l = [None for i in range(n)] for i in range(n):l[i] = LS() return l sys.setrecursionlimit(1000000) mod = 1000000007 #A def A(): while 1: n,m = LI() if n == 0 and m == 0: break v = [[] for i in range(n)] for i in range(m): a,b = LI() a -= 1 b -= 1 v[a].append(b) v[b].append(a) bfs_map = [1 for i in range(n)] bfs_map[0] = 0 f = [0 for i in range(n)] q = deque() q.append(0) fl = 1 while q: if not fl:break x = q.popleft() for y in v[x]: if bfs_map[y]: bfs_map[y] = 0 f[y] = (1-f[x]) q.append(y) else: if f[y] == f[x]: print(0) fl = 0 break if fl: ans = [] k = sum(f) if k%2 == 0: ans.append(k//2) k = len(f)-sum(f) if k%2 == 0: ans.append(k//2) ans = list(set(ans)) ans.sort() print(len(ans)) for i in ans: print(i) return #B def B(): return #C def C(): return #D def D(): return #E def E(): return #F def F(): return #G def G(): return #H def H(): return #I def I_(): return #J def J(): return #Solve if __name__ == "__main__": A() ```
output
1
49,583
1
99,167
Provide a correct Python 3 solution for this coding contest problem. Divide and rule Taro, Hanako, and Jiro rule the JAG Kingdom together. There are N cities in the JAG Kingdom, some of which are connected by two-way roads. You can always reach all the other cities from any city via one or more roads. One day, Taro and Hanako finally made a mistake and decided to share the city and govern it. However, I don't even like the fact that the city governed by Taro and the city governed by Hanako are directly connected by a single road because they have become so bad. Therefore, we decided to share the governing towns so as to satisfy the following conditions. * Any pair of towns governed by Taro and Hanako are not directly connected by roads. This is because the relationship between Taro and Hanako is insanely bad. * Towns governed by the same person are not directly connected by roads. This is to encourage diplomacy by obliging the passage under the control of others. * The total number of towns governed by Taro and the total number of towns governed by Hanako must be the same. This is because if the total number is not equal, the relationship between Taro and Hanako will be even worse. Here, Mr. Jiro is very open-minded, so the total number of cities governed by Mr. Jiro can be any number. If the division meets the above conditions, the three people can be convinced to rule, and even if there are no cities governed by someone, there is no complaint. At this time, create a program that enumerates all possible numbers as the total number of cities governed by Mr. Taro (= the total number of cities governed by Mr. Hanako). Input The input consists of multiple datasets. The maximum number of datasets is 50. Each data set is represented in the following format. > N M u1 v1 ... uM vM The first line consists of two integers N (2 ≤ N ≤ 103) and M (1 ≤ M ≤ 103), which represent the number of cities and the number of roads, respectively. The i-th line of the following M lines consists of two integers ui and vi (1 ≤ ui <vi ≤ N), indicating that the i-th road connects the city ui and the city vi in ​​both directions. Here, it is guaranteed that one city can always reach all other cities via one or more roads. Also, no multiple roads connecting pairs of the same city will be given. That is, (ui, vi) ≠ (uj, vj) is satisfied for all 1 ≤ i <j ≤ M. The end of the input is represented by a line of two zeros. Output For each dataset, if there are K possible total numbers of cities governed by Taro, first output K on the first line, then output the possible total number on each line in ascending order. Sample Input 6 7 1 2 14 twenty three twenty five 3 4 4 5 4 6 twenty one 1 2 3 3 1 2 13 twenty three 4 3 1 2 twenty three 3 4 5 4 1 2 twenty three 3 4 4 5 0 0 Output for the Sample Input 2 1 2 0 0 1 1 1 1 Example Input 6 7 1 2 1 4 2 3 2 5 3 4 4 5 4 6 2 1 1 2 3 3 1 2 1 3 2 3 4 3 1 2 2 3 3 4 5 4 1 2 2 3 3 4 4 5 0 0 Output 2 1 2 0 0 1 1 1 1
instruction
0
49,584
1
99,168
"Correct Solution: ``` import sys input = sys.stdin.readline def main(): while True: N, M = map(int, input().split()) if N == 0: break path = [[False] * N for i in range(N)] for i in range(M): u, v = map(int, input().split()) u -= 1; v -= 1; path[u][v] = True path[v][u] = True d = [-1] * N d[0] = 0 q = [0] while len(q) > 0: now = q.pop(0) for i in range(N): if path[now][i] and d[i] == -1: q.append(i) d[i] = d[now] + 1 ok = True for i in range(1, N): for j in range(i+1, N): if path[i][j] and d[i] == d[j]: ok = False break if not ok: break if not ok: print(0) else: num = 0 for i in range(N): if d[i]&1: num += 1 if N&1: print(1) if num&1: print((N-num)//2) else: print(num//2) else: if num&1: print(0) else: if N//2 == num: print(1) print(num//2) else: print(2) tmp = min(num, N-num) print(tmp//2) print((N-tmp)//2) if __name__ == "__main__": main() ```
output
1
49,584
1
99,169
Provide a correct Python 3 solution for this coding contest problem. Divide and rule Taro, Hanako, and Jiro rule the JAG Kingdom together. There are N cities in the JAG Kingdom, some of which are connected by two-way roads. You can always reach all the other cities from any city via one or more roads. One day, Taro and Hanako finally made a mistake and decided to share the city and govern it. However, I don't even like the fact that the city governed by Taro and the city governed by Hanako are directly connected by a single road because they have become so bad. Therefore, we decided to share the governing towns so as to satisfy the following conditions. * Any pair of towns governed by Taro and Hanako are not directly connected by roads. This is because the relationship between Taro and Hanako is insanely bad. * Towns governed by the same person are not directly connected by roads. This is to encourage diplomacy by obliging the passage under the control of others. * The total number of towns governed by Taro and the total number of towns governed by Hanako must be the same. This is because if the total number is not equal, the relationship between Taro and Hanako will be even worse. Here, Mr. Jiro is very open-minded, so the total number of cities governed by Mr. Jiro can be any number. If the division meets the above conditions, the three people can be convinced to rule, and even if there are no cities governed by someone, there is no complaint. At this time, create a program that enumerates all possible numbers as the total number of cities governed by Mr. Taro (= the total number of cities governed by Mr. Hanako). Input The input consists of multiple datasets. The maximum number of datasets is 50. Each data set is represented in the following format. > N M u1 v1 ... uM vM The first line consists of two integers N (2 ≤ N ≤ 103) and M (1 ≤ M ≤ 103), which represent the number of cities and the number of roads, respectively. The i-th line of the following M lines consists of two integers ui and vi (1 ≤ ui <vi ≤ N), indicating that the i-th road connects the city ui and the city vi in ​​both directions. Here, it is guaranteed that one city can always reach all other cities via one or more roads. Also, no multiple roads connecting pairs of the same city will be given. That is, (ui, vi) ≠ (uj, vj) is satisfied for all 1 ≤ i <j ≤ M. The end of the input is represented by a line of two zeros. Output For each dataset, if there are K possible total numbers of cities governed by Taro, first output K on the first line, then output the possible total number on each line in ascending order. Sample Input 6 7 1 2 14 twenty three twenty five 3 4 4 5 4 6 twenty one 1 2 3 3 1 2 13 twenty three 4 3 1 2 twenty three 3 4 5 4 1 2 twenty three 3 4 4 5 0 0 Output for the Sample Input 2 1 2 0 0 1 1 1 1 Example Input 6 7 1 2 1 4 2 3 2 5 3 4 4 5 4 6 2 1 1 2 3 3 1 2 1 3 2 3 4 3 1 2 2 3 3 4 5 4 1 2 2 3 3 4 4 5 0 0 Output 2 1 2 0 0 1 1 1 1
instruction
0
49,585
1
99,170
"Correct Solution: ``` import sys sys.setrecursionlimit(5000) def dfs(x): global ng, parity for v in adj[x]: if parity[v] == parity[x]: ng = True return elif parity[v] < 0: parity[v] = 1^parity[x] dfs(v) return while True: n, m = map(int, input().split()) if n == 0 and m == 0: break adj = [[] for _ in range(n)] parity = [-1 for _ in range(n)] for _ in range(m): a, b = map(int, input().split()) adj[a-1].append(b-1) adj[b-1].append(a-1) ng = False parity[0] = 0 dfs(0) if ng: print(0) continue ans = [] zero = parity.count(0) if zero%2 == 0: ans.append(zero//2) if (n-zero)%2 == 0 and zero*2 != n: ans.append((n-zero)//2) ans.sort() print(len(ans)) if ans: print(*ans, sep="\n") ```
output
1
49,585
1
99,171
Provide a correct Python 3 solution for this coding contest problem. Divide and rule Taro, Hanako, and Jiro rule the JAG Kingdom together. There are N cities in the JAG Kingdom, some of which are connected by two-way roads. You can always reach all the other cities from any city via one or more roads. One day, Taro and Hanako finally made a mistake and decided to share the city and govern it. However, I don't even like the fact that the city governed by Taro and the city governed by Hanako are directly connected by a single road because they have become so bad. Therefore, we decided to share the governing towns so as to satisfy the following conditions. * Any pair of towns governed by Taro and Hanako are not directly connected by roads. This is because the relationship between Taro and Hanako is insanely bad. * Towns governed by the same person are not directly connected by roads. This is to encourage diplomacy by obliging the passage under the control of others. * The total number of towns governed by Taro and the total number of towns governed by Hanako must be the same. This is because if the total number is not equal, the relationship between Taro and Hanako will be even worse. Here, Mr. Jiro is very open-minded, so the total number of cities governed by Mr. Jiro can be any number. If the division meets the above conditions, the three people can be convinced to rule, and even if there are no cities governed by someone, there is no complaint. At this time, create a program that enumerates all possible numbers as the total number of cities governed by Mr. Taro (= the total number of cities governed by Mr. Hanako). Input The input consists of multiple datasets. The maximum number of datasets is 50. Each data set is represented in the following format. > N M u1 v1 ... uM vM The first line consists of two integers N (2 ≤ N ≤ 103) and M (1 ≤ M ≤ 103), which represent the number of cities and the number of roads, respectively. The i-th line of the following M lines consists of two integers ui and vi (1 ≤ ui <vi ≤ N), indicating that the i-th road connects the city ui and the city vi in ​​both directions. Here, it is guaranteed that one city can always reach all other cities via one or more roads. Also, no multiple roads connecting pairs of the same city will be given. That is, (ui, vi) ≠ (uj, vj) is satisfied for all 1 ≤ i <j ≤ M. The end of the input is represented by a line of two zeros. Output For each dataset, if there are K possible total numbers of cities governed by Taro, first output K on the first line, then output the possible total number on each line in ascending order. Sample Input 6 7 1 2 14 twenty three twenty five 3 4 4 5 4 6 twenty one 1 2 3 3 1 2 13 twenty three 4 3 1 2 twenty three 3 4 5 4 1 2 twenty three 3 4 4 5 0 0 Output for the Sample Input 2 1 2 0 0 1 1 1 1 Example Input 6 7 1 2 1 4 2 3 2 5 3 4 4 5 4 6 2 1 1 2 3 3 1 2 1 3 2 3 4 3 1 2 2 3 3 4 5 4 1 2 2 3 3 4 4 5 0 0 Output 2 1 2 0 0 1 1 1 1
instruction
0
49,586
1
99,172
"Correct Solution: ``` from collections import defaultdict import sys sys.setrecursionlimit(1000000) def dfs(graph, visited, x, c): visited[x] = c for nx in graph[x]: if visited[nx] == c: return False if visited[nx] == 0 and not dfs(graph, visited, nx, -c): return False return True while True: n, m = list(map(int, input().split())) if n==0: break graph = defaultdict(list) visited = [0 for i in range(n+1)] for i in range(m): u, v = list(map(int, input().split())) graph[u].append(v) graph[v].append(u) f = dfs(graph, visited, 1, 1) if f == False: print(0) else: ans1, ans2 = 0, 0 for i in range(1, n+1): if visited[i]>0: ans1 += 1 elif visited[i]<0: ans2 += 1 ans = set() if ans1%2==0: ans.add(ans1//2) if ans2%2==0: ans.add(ans2//2) print(len(ans)) for e in sorted(ans): print(e) ```
output
1
49,586
1
99,173
Provide tags and a correct Python 3 solution for this coding contest problem. There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it. Input The first line contains three integers n, k and p (1 ≤ n ≤ 1 000, n ≤ k ≤ 2 000, 1 ≤ p ≤ 109) — the number of people, the number of keys and the office location. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — positions in which people are located initially. The positions are given in arbitrary order. The third line contains k distinct integers b1, b2, ..., bk (1 ≤ bj ≤ 109) — positions of the keys. The positions are given in arbitrary order. Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point. Output Print the minimum time (in seconds) needed for all n to reach the office with keys. Examples Input 2 4 50 20 100 60 10 40 80 Output 50 Input 1 2 10 11 15 7 Output 7 Note In the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.
instruction
0
50,177
1
100,354
Tags: binary search, brute force, dp, greedy, sortings Correct Solution: ``` def list_input(): return list(map(int,input().split())) def map_input(): return map(int,input().split()) def map_string(): return input().split() n,k,p = map_input() a = list_input() b = list_input() a.sort() b.sort() ans = 1000000000000000000 for i in range(k-n+1): cur = 0 c1 = 0 c2 = i while c1 < n: cur = max(abs(a[c1]-b[c2])+abs(b[c2]-p),cur) c1 += 1 c2 += 1 ans = min(ans,cur) print(ans) ```
output
1
50,177
1
100,355
Provide tags and a correct Python 3 solution for this coding contest problem. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
instruction
0
50,184
1
100,368
Tags: dp Correct Solution: ``` n=int(input()) a=[0]*n for i in range(n-1): for j in input().split(): a[int(j)-1]+=1 l=a.count(1) print((l*2**(n-l+1)+(n-l)*2**(n-l))%1000000007) ```
output
1
50,184
1
100,369
Provide tags and a correct Python 3 solution for this coding contest problem. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
instruction
0
50,185
1
100,370
Tags: dp Correct Solution: ``` n=int(input()) a = [0]*(n+1) for i in range(n-1): for i in input().split(): a[int(i)]+=1 l = a.count(1) print ((l*2**(n-l+1)+(n-l)*(2**(n-l)))%(10**9+7)) ```
output
1
50,185
1
100,371
Provide tags and a correct Python 3 solution for this coding contest problem. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
instruction
0
50,186
1
100,372
Tags: dp Correct Solution: ``` n = int(input()) cnt = [[] for _ in range(n)] for i in range (n - 1): fr, to = map(int, input().split()) cnt[fr - 1].append(to - 1); cnt[to - 1].append(fr - 1); l = 0 for i in range(n): if (len(cnt[i]) == 1): l += 1 ans = (n - l) * pow(2, n - l, 10 ** 9 + 7) ans += l * pow(2, n - l + 1, 10 ** 9 + 7) print (ans % (10 ** 9 + 7)) ```
output
1
50,186
1
100,373
Provide tags and a correct Python 3 solution for this coding contest problem. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
instruction
0
50,187
1
100,374
Tags: dp Correct Solution: ``` def quick_mod(b, p) : s = 1 while (p != 0) : if (p & 1) : s = s * b % mod p = p // 2 b = b * b % mod return s s = input().split() n = int(s[0]) N = 100000 mod = 1000000007 enter = [] for i in range(1, N + 5) : enter.append(0) for i in range(1, n) : s1 = input().split() enter[int(s1[0])] += 1 enter[int(s1[1])] += 1 tot = 0 for i in range(1, n + 1) : if (enter[i] == 1) : tot += 1 print((n + tot) * quick_mod(2, n - tot) % mod) ```
output
1
50,187
1
100,375
Provide tags and a correct Python 3 solution for this coding contest problem. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
instruction
0
50,188
1
100,376
Tags: dp Correct Solution: ``` n = int(input()) degree = n*[0] for i in range(0, n-1): u, v = input().split() u = int(u) v = int(v) u -= 1 v -= 1 degree[u] += 1 degree[v] += 1 numL = 0 for i in range(0, n): if degree[i] == 1: numL += 1 mod = 1000000007 ans = (n-numL)*2**(n-numL) + numL*2**(n+1-numL) print(ans%mod) ```
output
1
50,188
1
100,377
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options. Submitted Solution: ``` n=int(input()) a = [0]*(n+1) for i in range(n-1): for i in input().split(): a[int(i)]+=1 l = a.count(1) print ((l*2**(n-l+1)+(n-l)*(2**(n-l)))%(1e9+7)) ```
instruction
0
50,189
1
100,378
No
output
1
50,189
1
100,379
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options. Submitted Solution: ``` def exp(p): if not p: return 1 if p == 1: return 2 if p % 2: return (exp((p - 1) // 2) * exp((p - 1) // 2) * 2) % 1000000007 return (exp(p // 2) * exp(p // 2)) % 1000000007 n = int(input()) a = [0] * 100000 for i in range(n - 1): b, c = map(int, input().split()) b -= 1 c -= 1 a[b] += 1 a[c] += 1 cnt = 0 for i in range(n): if a[i] == 1: cnt += 1 cur = exp(n - cnt) ans = ((n - cnt) * cur) % (10 ** 9 + 7) cur <<= 1 cur %= (10 ** 9 + 7) ans += (cnt * cur) % (10 ** 9 + 7) print(ans) ```
instruction
0
50,190
1
100,380
No
output
1
50,190
1
100,381
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options. Submitted Solution: ``` print(4+0+0) ```
instruction
0
50,191
1
100,382
No
output
1
50,191
1
100,383
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7. Input In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities. In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road. Output Output one number, the answer to the problem modulo 109 + 7. Examples Input 2 1 2 Output 4 Input 3 1 2 2 3 Output 10 Note Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options. Submitted Solution: ``` n=int(input()) a=[0]*n for i in range(n-1): for j in input().split(): a[int(j)-1]+=1 l=a.count(1) print(l*2**(n-l+1)+(n-l)*2**(n-l)) ```
instruction
0
50,192
1
100,384
No
output
1
50,192
1
100,385
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi's office has N rooms. Each room has an ID from 1 to N. There are also N-1 corridors, and the i-th corridor connects Room a_i and Room b_i. It is known that we can travel between any two rooms using only these corridors. Takahashi has got lost in one of the rooms. Let this room be r. He decides to get back to his room, Room 1, by repeatedly traveling in the following manner: * Travel to the room with the smallest ID among the rooms that are adjacent to the rooms already visited, but not visited yet. Let c_r be the number of travels required to get back to Room 1. Find all of c_2,c_3,...,c_N. Note that, no matter how many corridors he passes through in a travel, it still counts as one travel. Constraints * 2 \leq N \leq 2\times 10^5 * 1 \leq a_i,b_i \leq N * a_i \neq b_i * The graph given as input is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Examples Input 6 1 5 5 6 6 2 6 3 6 4 Output 5 5 5 1 5 Input 6 1 2 2 3 3 4 4 5 5 6 Output 1 2 3 4 5 Input 10 1 5 5 6 6 10 6 4 10 3 10 8 8 2 4 7 4 9 Output 7 5 3 1 3 4 7 4 5 Submitted Solution: ``` """ Writer: SPD_9X2 https://atcoder.jp/contests/agc029/tasks/agc029_e 1に近いところから決めていくのが良いか? または部屋1を根とした木を考える? 部屋1スタートなら答えは0 部屋1に隣接している部屋なら答えは0 1を原点としてそこから定めていくとする 移動回数確定点に隣接する点を1つ取ってくる(Xとする) Xに隣接する確定点をAとする。ここで、(X > Aは確定) Xから探索する。また、Aにたどり着きさえすれば、後はAから原点までの移動回数で移動可能? →これは正しい。(途中でXより大きい点を通ることは無いため) Xから隣接点を探索していき、Aがでるまで小さい点を訪問し続ける? それまで訪問した点は、すべて同じ時間になる? →正しそう (部分木で、A超をまたがないといけない点以外は何処から始めても全て訪問する羽目になる) (また、最終的にはAにたどり着くから) そんなかんたんでいいのか?? """ from collections import deque N = int(input()) lis = [ [] for i in range(N) ] for i in range(N-1): a,b = map(int,input().split()) a -= 1 b -= 1 lis[a].append(b) lis[b].append(a) dis = [float("inf")] * N unvisit = [True] * N unvisit[0] = False dis[0] = 0 stq = deque([]) for nex in lis[0]: stq.append([nex,0]) while len(stq) > 0: st,A = stq.popleft() nv = [st] q = deque([st]) while len(q) > 0: now = q.popleft() for nex in lis[now]: if unvisit[nex]: if nex > A: stq.append([nex,now]) elif nex < A: nv.append(nex) q.append(nex) unvisit[nex] = False for i in nv: dis[i] = len(nv) + dis[A] print (*dis[1:]) ```
instruction
0
50,329
1
100,658
No
output
1
50,329
1
100,659
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi's office has N rooms. Each room has an ID from 1 to N. There are also N-1 corridors, and the i-th corridor connects Room a_i and Room b_i. It is known that we can travel between any two rooms using only these corridors. Takahashi has got lost in one of the rooms. Let this room be r. He decides to get back to his room, Room 1, by repeatedly traveling in the following manner: * Travel to the room with the smallest ID among the rooms that are adjacent to the rooms already visited, but not visited yet. Let c_r be the number of travels required to get back to Room 1. Find all of c_2,c_3,...,c_N. Note that, no matter how many corridors he passes through in a travel, it still counts as one travel. Constraints * 2 \leq N \leq 2\times 10^5 * 1 \leq a_i,b_i \leq N * a_i \neq b_i * The graph given as input is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Examples Input 6 1 5 5 6 6 2 6 3 6 4 Output 5 5 5 1 5 Input 6 1 2 2 3 3 4 4 5 5 6 Output 1 2 3 4 5 Input 10 1 5 5 6 6 10 6 4 10 3 10 8 8 2 4 7 4 9 Output 7 5 3 1 3 4 7 4 5 Submitted Solution: ``` N = int(input()) X = [[] for i in range(N)] P = [-1] * N for i in range(N-1): x, y = map(int, input().split()) X[x-1].append(y-1) X[y-1].append(x-1) def set_parent(i): # print(i) for a in X[i]: if a != P[i]: P[a] = i # print(a) X[a].remove(i) set_parent(a) set_parent(0) B = [-1] * N def set_block(i): for a in X[i]: B[a] = max(i, B[i]) set_block(a) B_id = [-1] * N B_id_cnt = [0] * N def BID(i): for a in X[i]: if a > B[i]: B_id[a] = a else: B_id[a] = B_id[i] # print(a, B_id) B_id_cnt[B_id[a]] += 1 BID(a) Ans = [0] * N def flow(i): for a in X[i]: if B_id[a] == B_id[i]: Ans[a] = Ans[i] else: Ans[a] = Ans[i] + B_id_cnt[a] flow(a) set_block(0) BID(0) flow(0) # print("X=", X) # 子リスト # print("P=", P) # 親 # print("B=", B) # Block # print(B_id) # BlockのID # print(B_id_cnt) # BlockのID # print(Ans) print(" ".join(map(str, Ans[1:]))) ```
instruction
0
50,330
1
100,660
No
output
1
50,330
1
100,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi's office has N rooms. Each room has an ID from 1 to N. There are also N-1 corridors, and the i-th corridor connects Room a_i and Room b_i. It is known that we can travel between any two rooms using only these corridors. Takahashi has got lost in one of the rooms. Let this room be r. He decides to get back to his room, Room 1, by repeatedly traveling in the following manner: * Travel to the room with the smallest ID among the rooms that are adjacent to the rooms already visited, but not visited yet. Let c_r be the number of travels required to get back to Room 1. Find all of c_2,c_3,...,c_N. Note that, no matter how many corridors he passes through in a travel, it still counts as one travel. Constraints * 2 \leq N \leq 2\times 10^5 * 1 \leq a_i,b_i \leq N * a_i \neq b_i * The graph given as input is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Examples Input 6 1 5 5 6 6 2 6 3 6 4 Output 5 5 5 1 5 Input 6 1 2 2 3 3 4 4 5 5 6 Output 1 2 3 4 5 Input 10 1 5 5 6 6 10 6 4 10 3 10 8 8 2 4 7 4 9 Output 7 5 3 1 3 4 7 4 5 Submitted Solution: ``` import sys def dfs1(v, p): ret = 1 links[v].discard(p) m = min(v, p) for c in links[v]: res = dfs1(c, v) if c < m: ret += res subtree_costs[v] = ret return ret def dfs2(v, p, pc): sc = pc + subtree_costs[v] costs[v] = sc m = min(v, p) for c in links[v]: if c < m: dfs2(c, v, sc - subtree_costs[c]) else: dfs2(c, v, sc) n = int(input()) links = [set() for _ in range(n)] for line in sys.stdin.readlines(): a, b = map(int, line.split()) a -= 1 b -= 1 links[a].add(b) links[b].add(a) link = [sorted(l) for l in links] subtree_costs = [0] * n dfs1(0, -1) subtree_costs[0] = 0 costs = [0] * n dfs2(0, -1, 0) print(*costs[1:]) ```
instruction
0
50,331
1
100,662
No
output
1
50,331
1
100,663
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi's office has N rooms. Each room has an ID from 1 to N. There are also N-1 corridors, and the i-th corridor connects Room a_i and Room b_i. It is known that we can travel between any two rooms using only these corridors. Takahashi has got lost in one of the rooms. Let this room be r. He decides to get back to his room, Room 1, by repeatedly traveling in the following manner: * Travel to the room with the smallest ID among the rooms that are adjacent to the rooms already visited, but not visited yet. Let c_r be the number of travels required to get back to Room 1. Find all of c_2,c_3,...,c_N. Note that, no matter how many corridors he passes through in a travel, it still counts as one travel. Constraints * 2 \leq N \leq 2\times 10^5 * 1 \leq a_i,b_i \leq N * a_i \neq b_i * The graph given as input is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Output Print c_r for each r, in the following format: c_2 c_3 ... c_N Examples Input 6 1 5 5 6 6 2 6 3 6 4 Output 5 5 5 1 5 Input 6 1 2 2 3 3 4 4 5 5 6 Output 1 2 3 4 5 Input 10 1 5 5 6 6 10 6 4 10 3 10 8 8 2 4 7 4 9 Output 7 5 3 1 3 4 7 4 5 Submitted Solution: ``` # -*- coding: utf-8 -*- from collections import defaultdict, deque from heapq import heappush, heappop, heapreplace def solve(): N = int(input()) V = list(range(1, N+1)) E = defaultdict(set) for _ in range(N-1): a, b = map(int,input().split()) E[a].add(b) E[b].add(a) Q = [1] while Q: r = heappop(Q) for s in E[r]: E[s].discard(r) heappush(Q, s) #print(E) Q = [1] while Q: r = heappop(Q) R = E[r].copy() while R: s = R.pop() P = E[s].copy() s_ = {s} if isinstance(s,int) else set(s) while P: t = P.pop() if t < (r if isinstance(r,int) else max(r)): s_.add(t) for u in E[t]: P.add(u) s__ = tuple(s_) E[s__] = set(u for t in s_ for u in E.pop(t,{}))-s_ E[r].discard(s) E[r].add(s__) heappush(Q, s__) #print(E) E = dict(E) C = defaultdict(int) Q = [1] while Q: r = heappop(Q) for s in E.get(r): C[s] = C[r] + (1 if isinstance(r,int) else len(s)) heappush(Q, s) #print(C) D = [0 for _ in range(N-1)] for key in C: if isinstance(key, tuple): for i in key: D[i-2] = C[key] #print(D) res = ' '.join([str(d) for d in D]) return str(res) if __name__ == '__main__': print(solve()) ```
instruction
0
50,332
1
100,664
No
output
1
50,332
1
100,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in the kingdom X, numbered from 1 through n. People travel between cities by some one-way roads. As a passenger, JATC finds it weird that from any city u, he can't start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an acyclic graph. Being annoyed by the traveling system, JATC decides to meet the king and ask him to do something. In response, the king says that he will upgrade some cities to make it easier to travel. Because of the budget, the king will only upgrade those cities that are important or semi-important. A city u is called important if for every city v ≠ u, there is either a path from u to v or a path from v to u. A city u is called semi-important if it is not important and we can destroy exactly one city v ≠ u so that u becomes important. The king will start to act as soon as he finds out all those cities. Please help him to speed up the process. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 300 000, 1 ≤ m ≤ 300 000) — the number of cities and the number of one-way roads. Next m lines describe the road system of the kingdom. Each of them contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting one-way road from u_i to v_i. It is guaranteed, that the kingdoms' roads make an acyclic graph, which doesn't contain multiple edges and self-loops. Output Print a single integer — the number of cities that the king has to upgrade. Examples Input 7 7 1 2 2 3 3 4 4 7 2 5 5 4 6 4 Output 4 Input 6 7 1 2 2 3 3 4 1 5 5 3 2 6 6 4 Output 4 Note In the first example: <image> * Starting at the city 1 we can reach all the other cities, except for the city 6. Also, from the city 6 we cannot reach the city 1. Therefore, if we destroy the city 6 then the city 1 will become important. So 1 is a semi-important city. * For city 2, the set of cities that cannot reach 2 and cannot be reached by 2 is \{6\}. Therefore, destroying city 6 will make the city 2 important. So city 2 is also semi-important. * For city 3, the set is \{5, 6\}. As you can see, destroying either city 5 or 6 will not make the city 3 important. Therefore, it is neither important nor semi-important. * For city 4, the set is empty. So 4 is an important city. * The set for city 5 is \{3, 6\} and the set for city 6 is \{3, 5\}. Similarly to city 3, both of them are not important nor semi-important. * The city 7 is important since we can reach it from all other cities. So we have two important cities (4 and 7) and two semi-important cities (1 and 2). In the second example, the important cities are 1 and 4. The semi-important cities are 2 and 3. Submitted Solution: ``` from collections import deque def topoSort(v,stack,visit): visit[v]=True for i in adj[v]: if not visit[i]: topoSort(i,stack,visit) stack.append(v) def findLongestPaht(): stack=[] visit=[False]*(n+1) dis=[-1]*(n+1) path=[0]*(n+1) for i in range (1,n): if not visit[i]: topoSort(i,stack,visit) for i in range(1,n): if inDeg[i]==0: dis[i]=1 while stack.__len__()>0: x=stack.pop() if dis[x] != -1: for y in adj[x]: if dis[y]<dis[x]+1: dis[y]=dis[x]+1 path[y]=x size=max(dis) return path,size,dis.index(size) def findCandidates(): cand=[False]*(n+1) for i in range(size): for j in adj[longestPath[i]]: if L[j]==-1: L[j]=size-i longestPath.reverse() for i in range(size): for j in adjIn[longestPath[i]]: if R[j]==-1: R[j]=i+1 for i in range (1,n): if R[i]-L[i]==2: cand[i]=True if R[i]==2 or L[i]==size-1: cand[i]=True for i in range(size): cand[longestPath[i]]=False return cand def solve(): visit=[False]*(n+1) Ls=[[]for i in range (size+1)] Rs=[[]for i in range (size+1)] for i in range (1,n): if candidates[i]: if L[i]!=-1: Ls[L[i]].append(i) if R[i]!=-1: Rs[R[i]].append(i) for i in range(size-1,-1,-1): current=longestPath[i] DFS(current,visit,True,adj,OUT) if(i+1<size): OUT[current]+=OUT[longestPath[i+1]]+1 for r in Rs[i+1]: DFS(r,visit,False,adj,OUT) OUT[r]+=OUT[current]+1 visit=[False]*(n+1) for i in range(size): current=longestPath[i] DFS(current,visit,True,adjIn,IN) if(i>0): IN[current]+=IN[longestPath[i-1]]+1 for l in Ls[i+1]: DFS(l,visit,False,adjIn,IN) IN[l]+=IN[current]+1 def DFS(v,visit,check,adj,in_out): visit[v]=check for i in adj[v]: if not visit[i]: in_out[v]+=1 DFS(i,visit,check,adj,in_out) n,m=map(int,input().split()) adj=[[] for i in range (n+1)] adjIn=[[] for i in range (n+1)] IN=[0]*(n+1) OUT=[0]*(n+1) outDeg=[0] *(n+1) inDeg=[0] *(n+1) L=[-1]*(n+1) R=[-1]*(n+1) for i in range(m): x,y=map(int,input().split()) adj[x].append(y) adjIn[y].append(x) inDeg[y]+=1 outDeg[x]+=1 longestPath=[] distances,size,start=findLongestPaht() for i in range(size): longestPath.append(start) start=distances[start] candidates=findCandidates() solve() ans=0 for i in range (1,n+1): if(IN[i]+OUT[i]>=n-2): ans+=1 print(ans) ```
instruction
0
50,506
1
101,012
No
output
1
50,506
1
101,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in the kingdom X, numbered from 1 through n. People travel between cities by some one-way roads. As a passenger, JATC finds it weird that from any city u, he can't start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an acyclic graph. Being annoyed by the traveling system, JATC decides to meet the king and ask him to do something. In response, the king says that he will upgrade some cities to make it easier to travel. Because of the budget, the king will only upgrade those cities that are important or semi-important. A city u is called important if for every city v ≠ u, there is either a path from u to v or a path from v to u. A city u is called semi-important if it is not important and we can destroy exactly one city v ≠ u so that u becomes important. The king will start to act as soon as he finds out all those cities. Please help him to speed up the process. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 300 000, 1 ≤ m ≤ 300 000) — the number of cities and the number of one-way roads. Next m lines describe the road system of the kingdom. Each of them contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting one-way road from u_i to v_i. It is guaranteed, that the kingdoms' roads make an acyclic graph, which doesn't contain multiple edges and self-loops. Output Print a single integer — the number of cities that the king has to upgrade. Examples Input 7 7 1 2 2 3 3 4 4 7 2 5 5 4 6 4 Output 4 Input 6 7 1 2 2 3 3 4 1 5 5 3 2 6 6 4 Output 4 Note In the first example: <image> * Starting at the city 1 we can reach all the other cities, except for the city 6. Also, from the city 6 we cannot reach the city 1. Therefore, if we destroy the city 6 then the city 1 will become important. So 1 is a semi-important city. * For city 2, the set of cities that cannot reach 2 and cannot be reached by 2 is \{6\}. Therefore, destroying city 6 will make the city 2 important. So city 2 is also semi-important. * For city 3, the set is \{5, 6\}. As you can see, destroying either city 5 or 6 will not make the city 3 important. Therefore, it is neither important nor semi-important. * For city 4, the set is empty. So 4 is an important city. * The set for city 5 is \{3, 6\} and the set for city 6 is \{3, 5\}. Similarly to city 3, both of them are not important nor semi-important. * The city 7 is important since we can reach it from all other cities. So we have two important cities (4 and 7) and two semi-important cities (1 and 2). In the second example, the important cities are 1 and 4. The semi-important cities are 2 and 3. Submitted Solution: ``` from collections import deque def topoSort(v,stack,visit): visit[v]=True for i in adj[v]: if not visit[i]: topoSort(i,stack,visit) stack.append(v) def findLongestPaht(): stack=[] visit=[False]*(n+1) dis=[-1]*(n+1) path=[0]*(n+1) for i in range (1,n): if not visit[i]: topoSort(i,stack,visit) for i in range(1,n): if inDeg[i]==0: dis[i]=1 while stack.__len__()>0: x=stack.pop() if dis[x] != -1: for y in adj[x]: if dis[y]<dis[x]+1: dis[y]=dis[x]+1 path[y]=x size=max(dis) return path,size,dis.index(size) def findCandidates(): cand=[False]*(n+1) for i in range(size): for j in adj[longestPath[i]]: if L[j]==-1: L[j]=size-i longestPath.reverse() for i in range(size): for j in adjIn[longestPath[i]]: if R[j]==-1: R[j]=i+1 for i in range (1,n): if R[i]-L[i]==2: cand[i]=True for i in range(size): cand[longestPath[i]]=False return cand def solve(): visit=[False]*(n+1) Ls=[[]for i in range (size+1)] Rs=[[]for i in range (size+1)] for i in range (1,n): if candidates[i]: Ls[L[i]].append(i) Rs[R[i]].append(i) for i in range(size-1,-1,-1): current=longestPath[i] DFS(current,visit,True,adj,OUT) if(i+1<size): OUT[current]+=OUT[longestPath[i+1]]+1 for r in Rs[i+1]: DFS(r,visit,False,adj,OUT) OUT[r]+=OUT[current]+1 visit=[False]*(n+1) for i in range(size): current=longestPath[i] DFS(current,visit,True,adjIn,IN) if(i>0): IN[current]+=IN[longestPath[i-1]]+1 for l in Ls[i+1]: DFS(l,visit,False,adjIn,IN) IN[l]+=IN[current]+1 def DFS(v,visit,check,adj,in_out): visit[v]=check for i in adj[v]: if not visit[i]: in_out[v]+=1 DFS(i,visit,check,adj,in_out) n,m=map(int,input().split()) adj=[[] for i in range (n+1)] adjIn=[[] for i in range (n+1)] IN=[0]*(n+1) OUT=[0]*(n+1) outDeg=[0] *(n+1) inDeg=[0] *(n+1) L=[-1]*(n+1) R=[-1]*(n+1) for i in range(m): x,y=map(int,input().split()) adj[x].append(y) adjIn[y].append(x) inDeg[y]+=1 outDeg[x]+=1 longestPath=[] distances,size,start=findLongestPaht() for i in range(size): longestPath.append(start) start=distances[start] candidates=findCandidates() solve() ans=0 for i in range (1,n+1): if(IN[i]+OUT[i]>=n-2): ans+=1 print(ans) ```
instruction
0
50,507
1
101,014
No
output
1
50,507
1
101,015
Provide tags and a correct Python 3 solution for this coding contest problem. They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths. A simple path is the path which goes through every Berland city not more than once. The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it. Note how the fools' paths are given in the input. Input The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path. Output Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input. Examples Input 5 1 2 1 3 2 4 2 5 2 1 4 3 5 Output 2 1 1 1 Input 5 3 4 4 5 1 4 2 4 3 2 3 1 3 3 5 Output 3 1 1 1 Note In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones. In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1.
instruction
0
50,760
1
101,520
Tags: data structures, dfs and similar, trees Correct Solution: ``` # solved using sparse table from math import log2 def construct(root): stack = [root] while stack: u = stack.pop() for v in edges[u]: if v != parents[u]: parents[v] = u levels[v] = levels[u] + 1 stack.append(v) table.append(parents) k = 1 while (1 << k) < n: new_row = [0] * n for i in range(n): new_row[i] = table[k-1][table[k-1][i]] table.append(new_row) k += 1 def getlca(a, b): # range MINIMUM query depth_gap = levels[b] - levels[a] if depth_gap < 0: # make sure node b is at a deeper level than node a a, b = b, a depth_gap = -depth_gap if depth_gap != 0: ## traverse upward from a so that both a and b are at the same level k = int(log2(depth_gap)) while depth_gap: if (depth_gap) >= (2**k): b = table[k][b] depth_gap = levels[b] - levels[a] k -= 1 if b == a: return a for k in range(logn, -1, -1): if table[k][a] != table[k][b]: a, b = table[k][a], table[k][b] return table[0][a] def travel(a, b): lca = getlca(a, b) tally[a] += 1 tally[b] += 1 tally[lca] -= 2 def sum_subtree(root): stack = [] for v in edges[root]: stack.append([v, 0]) while stack: u, i = stack[-1] if i == len(edges[u]): tally[parents[u]] += tally[u] stack.pop() else: v = edges[u][i] stack[-1][1] += 1 if v != parents[u]: stack.append([v, 0]) def count_fools(u, v): if levels[u] > levels[v]: return tally[u] else: return tally[v] n = int(input()) logn = int(log2(n)) edges = [[] for _ in range(n)] edges_list = [] for i in range(n-1): u, v = map(int, input().split()) u, v = u-1, v-1 # adjusting index convention for convenience edges[u].append(v) edges[v].append(u) edges_list.append((u, v)) parents = [0] * n levels = [0] * n table = [] root = 0 construct(root//2) tally = [0] * n k = int(input()) for _ in range(k): a, b = map(int, input().split()) travel(a-1, b-1) sum_subtree(root) for u, v in edges_list: print(count_fools(u, v), end=' ') print() ```
output
1
50,760
1
101,521
Provide tags and a correct Python 3 solution for this coding contest problem. They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths. A simple path is the path which goes through every Berland city not more than once. The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it. Note how the fools' paths are given in the input. Input The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path. Output Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input. Examples Input 5 1 2 1 3 2 4 2 5 2 1 4 3 5 Output 2 1 1 1 Input 5 3 4 4 5 1 4 2 4 3 2 3 1 3 3 5 Output 3 1 1 1 Note In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones. In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1.
instruction
0
50,761
1
101,522
Tags: data structures, dfs and similar, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(2*10**5) 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 MA=10**5+1 level=20 tree=[[] for i in range(MA)] depth=[0 for i in range(MA)] parent=[[0 for i in range(level)] for j in range(MA)] @bootstrap def dfs(cur,prev): depth[cur] = depth[prev] + 1 parent[cur][0] = prev res.append(cur) for i in range(len(tree[cur])): if (tree[cur][i] != prev): yield dfs(tree[cur][i], cur) res.append(-cur) yield def precomputeSparseMatrix(n): for i in range(1,level): for node in range(1,n+1): if (parent[node][i-1] != -1): parent[node][i] =parent[parent[node][i-1]][i-1] def lca(u,v): if (depth[v] < depth[u]): u,v=v,u diff = depth[v] - depth[u] for i in range(level): if ((diff >> i) & 1): v = parent[v][i] if (u == v): return u i=level-1 while(i>=0): if (parent[u][i] != parent[v][i]): u = parent[u][i] v = parent[v][i] i+=-1 return parent[u][0] def add(a,b): tree[a].append(b) tree[b].append(a) def res(s,t,f): p=lca(t,f) q=lca(s,f) if p==q: r=depth[lca(s,t)]-depth[p] return min(depth[p] + depth[f] - 2 * depth[p] + 1+r, depth[q] + depth[f] - 2 * depth[q] + 1+r) return min(depth[p]+depth[f]-2*depth[p]+1,depth[q]+depth[f]-2*depth[q]+1) ord=[] n=int(input()) for j in range(n-1): u,v=map(int,input().split()) ord.append([u, v]) tree[u].append(v) tree[v].append(u) res=[] dfs(1,0) precomputeSparseMatrix(n) d=dict() l=len(res) req=[0]*(l) for j in range(l): d[res[j]]=j k=int(input()) c=[0]*(n+1) for j in range(k): u,v=map(int,input().split()) lc=lca(u,v) c[lc]+=1 if u==lc: indu=d[u] indv=d[v] req[indu]+=1 req[indv+1]+=-1 elif v==lc: indu = d[u] indv = d[v] req[indv] += 1 req[indu + 1] += -1 else: indl=d[lc] indu = d[u] indv = d[v] req[indl]+=1 req[indu+1]+=-1 req[indl+1]+=1 req[indv+1]+=-1 for j in range(1,l): req[j]+=req[j-1] ans=[0]*(n+1) for j in range(1,n+1): ans[j]=req[d[j]]-req[d[-j]] for j in ord: l=lca(j[0],j[1]) if l==j[0]: print(ans[j[1]]-c[j[1]],end=" ") else: print(ans[j[0]] - c[j[0]], end=" ") ```
output
1
50,761
1
101,523
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths. A simple path is the path which goes through every Berland city not more than once. The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it. Note how the fools' paths are given in the input. Input The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path. Output Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input. Examples Input 5 1 2 1 3 2 4 2 5 2 1 4 3 5 Output 2 1 1 1 Input 5 3 4 4 5 1 4 2 4 3 2 3 1 3 3 5 Output 3 1 1 1 Note In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones. In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1. Submitted Solution: ``` INF = 1000000001 def travel(a, b): if dist[a] > dist[b]: a, b = b, a traveled = [False] * n while a > 0: id = edges[a][pred[a]] count[id] += 1 traveled[a] = True a = pred[a] traveled[0] = True while not traveled[b]: id = edges[b][pred[b]] count[id] += 1 b = pred[b] while b > 0: id = edges[b][pred[b]] count[id] -= 1 b = pred[b] n = int(input()) edges = [{} for _ in range(n)] count = [0] * (n-1) for id in range(n-1): u, v = map(int, input().split()) u, v = u-1, v-1 # adjusting index convention for convenience edges[u][v] = id edges[v][u] = id #calculate distance from node 0 dist = [0] * n l = [0] left = 0 visited = [False] * n visited[0] = True pred = [-1] * n while left < len(l): u = l[left] left += 1 for v in edges[u]: if not visited[v]: l.append(v) dist[v] = dist[u] + 1 visited[v] = True pred[v] = u k = int(input()) for _ in range(k): a, b = map(int, input().split()) a, b = a-1, b-1 travel(a, b) print(count) ```
instruction
0
50,762
1
101,524
No
output
1
50,762
1
101,525
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths. A simple path is the path which goes through every Berland city not more than once. The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it. Note how the fools' paths are given in the input. Input The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path. Output Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input. Examples Input 5 1 2 1 3 2 4 2 5 2 1 4 3 5 Output 2 1 1 1 Input 5 3 4 4 5 1 4 2 4 3 2 3 1 3 3 5 Output 3 1 1 1 Note In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones. In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1. Submitted Solution: ``` #!/usr/bin/env python3 import sys from math import sqrt def level_to_sid(l): return int(sqrt(l)) + 1 class Node: def __init__(self, nid): self.id = nid self._conns = {} self.level = -1 def add_conn(self, nid, eid): self._conns[nid] = eid def get_conns(self): return self._conns.keys() def get_edge_id(self, nid): return self._conns[nid] class Graph: def __init__(self, num_nodes): self.nodes = [None for _ in range(num_nodes)] self.parents = [None for _ in range(num_nodes)] self.segments = [None for _ in range(num_nodes)] def add_node(self, nid): if not self.nodes[nid]: self.nodes[nid] = Node(nid) def add_edge(self, nid_a, nid_b, edge_id): self.nodes[nid_a].add_conn(nid_b, edge_id) self.nodes[nid_b].add_conn(nid_a, edge_id) def find_lca(self, s_node, e_node): assert s_node.level <= e_node.level s_sid = level_to_sid(s_node.level) e_sid = level_to_sid(e_node.level) while e_sid != s_sid: e_node = self.segments[e_node.id] e_sid = level_to_sid(e_node.level) s_n = s_node e_n = e_node while self.segments[s_n.id] != self.segments[e_n.id]: s_n = self.segments[s_n.id] e_n = self.segments[e_n.id] ceil_n = self.parents[s_n.id] visited = [False] * len(self.nodes) if ceil_n: visited[ceil_n.id] = True while e_n != ceil_n: visited[e_n.id] = True e_n = self.parents[e_n.id] lca_node = s_n while lca_node and (not visited[lca_node.id]): lca_node = self.parents[lca_node.id] assert lca_node != None return lca_node def prepare(self): visited = [False] * len(self.nodes) def dfs(n, parent, level, cur_sid, last_seg_parent): if visited[n.id]: return n.level = level sid = level_to_sid(level) if sid != cur_sid: cur_sid = sid last_seg_parent = parent self.parents[n.id] = parent self.segments[n.id] = last_seg_parent visited[n.id] = True for nid in n.get_conns(): dfs(self.nodes[nid], n, level + 1, cur_sid, last_seg_parent) dfs(self.nodes[0], None, 0, 1, None) def count_damage(g, journeys): damage = [0 for _ in g.nodes] def inc_damage_through(start, end): n = start while n.id != end.id: p = g.parents[n.id] assert p != None damage[n.get_edge_id(p.id)] += 1 n = p for (s_nid, e_nid) in journeys: s_node = g.nodes[s_nid] e_node = g.nodes[e_nid] if s_node.level > e_node.level: (s_node, e_node) = (e_node, s_node) lca_node = g.find_lca(s_node, e_node) inc_damage_through(e_node, lca_node) inc_damage_through(s_node, lca_node) return damage def main(): def read_pair(): return list(map(lambda x: int(x) - 1, sys.stdin.readline().strip().split(' '))) n_roads = int(sys.stdin.readline()) g = Graph(n_roads) for edge_id in range(n_roads - 1): (nid_a, nid_b) = read_pair() g.add_node(nid_a) g.add_node(nid_b) g.add_edge(nid_a, nid_b, edge_id) g.prepare() n_fools = int(sys.stdin.readline()) journeys = [] for _ in range(n_fools): (nid_s, nid_e) = read_pair() journeys.append((nid_s, nid_e)) damage = count_damage(g, journeys) for d in damage: sys.stdout.write("{} ".format(d)) print() if __name__ == '__main__': main() ```
instruction
0
50,763
1
101,526
No
output
1
50,763
1
101,527
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths. A simple path is the path which goes through every Berland city not more than once. The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it. Note how the fools' paths are given in the input. Input The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path. Output Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input. Examples Input 5 1 2 1 3 2 4 2 5 2 1 4 3 5 Output 2 1 1 1 Input 5 3 4 4 5 1 4 2 4 3 2 3 1 3 3 5 Output 3 1 1 1 Note In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones. In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(3*10**5) 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 MA=10**5+1 level=20 tree=[[] for i in range(MA)] depth=[0 for i in range(MA)] parent=[[0 for i in range(level)] for j in range(MA)] @bootstrap def dfs(cur,prev): depth[cur] = depth[prev] + 1 parent[cur][0] = prev res.append(cur) for i in range(len(tree[cur])): if (tree[cur][i] != prev): yield dfs(tree[cur][i], cur) res.append(-cur) yield def precomputeSparseMatrix(n): for i in range(1,level): for node in range(1,n+1): if (parent[node][i-1] != -1): parent[node][i] =parent[parent[node][i-1]][i-1] def lca(u,v): if (depth[v] < depth[u]): u,v=v,u diff = depth[v] - depth[u] for i in range(level): if ((diff >> i) & 1): v = parent[v][i] if (u == v): return u i=level-1 while(i>=0): if (parent[u][i] != parent[v][i]): u = parent[u][i] v = parent[v][i] i+=-1 return parent[u][0] def add(a,b): tree[a].append(b) tree[b].append(a) def res(s,t,f): p=lca(t,f) q=lca(s,f) if p==q: r=depth[lca(s,t)]-depth[p] return min(depth[p] + depth[f] - 2 * depth[p] + 1+r, depth[q] + depth[f] - 2 * depth[q] + 1+r) return min(depth[p]+depth[f]-2*depth[p]+1,depth[q]+depth[f]-2*depth[q]+1) ord=[] n=int(input()) for j in range(n-1): u,v=map(int,input().split()) ord.append([u, v]) tree[u].append(v) tree[v].append(u) res=[] dfs(1,0) precomputeSparseMatrix(n) d=dict() l=len(res) req=[0]*(l) for j in range(l): d[res[j]]=j k=int(input()) for j in range(k): u,v=map(int,input().split()) lc=lca(u,v) if u==lc: indu=d[u] indv=d[v] req[indu]+=1 req[indv+1]+=-1 elif v==lc: indu = d[u] indv = d[v] req[indv] += 1 req[indu + 1] += -1 else: indl=d[lc] indu = d[u] indv = d[v] req[indl]+=1 req[indu+1]+=-1 req[indl+1]+=1 req[indv+1]+=-1 for j in range(1,l): req[j]+=req[j-1] ans=[0]*(n+1) for j in range(1,n+1): ans[j]=req[d[j]]-req[d[-j]] for j in ord: print(min(ans[j[0]],ans[j[1]]),end=" ") ```
instruction
0
50,764
1
101,528
No
output
1
50,764
1
101,529
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths. A simple path is the path which goes through every Berland city not more than once. The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it. Note how the fools' paths are given in the input. Input The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path. Output Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input. Examples Input 5 1 2 1 3 2 4 2 5 2 1 4 3 5 Output 2 1 1 1 Input 5 3 4 4 5 1 4 2 4 3 2 3 1 3 3 5 Output 3 1 1 1 Note In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones. In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1. Submitted Solution: ``` from math import ceil, log2 def euler_tour(u, parent, level): tour = [(level, u)] for v in edges[u]: if v != parent: tour += euler_tour(v, u, level+1) tour.append((level, u)) # tour.append((level, u)) return tour def construct(l, r, sti): global segment_tree if l == r: segment_tree[sti] = tour[l] else: mid = (l + r) // 2 segment_tree[sti] = min(construct(l, mid, sti*2), construct(mid+1, r, sti*2+1)) return segment_tree[sti] def rmqutil(sti, x, y, l, r): if x > r or y < l: return (100000, 0) if x >= l and y <= r: return segment_tree[sti] mid = (x + y) // 2 return min(rmqutil(sti*2, x, mid, l, r), rmqutil(sti*2+1, mid+1, y, l, r)) def rmq(l, r): # range MINIMUM query return rmqutil(1, 0, tour_len-1, l, r)[1] def travel(a, b): l, r = tour_lookup[a], tour_lookup[b] if l > r: l, r = r, l lca = rmq(l, r) tally[a] += 1 tally[b] += 1 tally[lca] -= 2 def dfs(u, parent): subtree_sum[u] = tally[u] for v in edges[u]: if v != parent: subtree_sum[u] += dfs(v, u) return subtree_sum[u] def count_fools(u, v): step = max(tour[tour_lookup[u]], tour[tour_lookup[v]]) return subtree_sum[step[1]] n = int(input()) edges = [set() for _ in range(n)] edges_list = [] for i in range(n-1): u, v = map(int, input().split()) u, v = u-1, v-1 # adjusting index convention for convenience edges[u].add(v) edges[v].add(u) edges_list.append((u, v)) root = 0 # choose optimal root? tour = euler_tour(root, root, 1) tour_lookup = [0] * n for i in range(len(tour)): tour_lookup[tour[i][1]] = i tour_len = len(tour) segment_tree = [0] * 2**int(ceil(log2(tour_len))+1) construct(0, tour_len-1, 1) tally = [0] * n k = int(input()) for _ in range(k): a, b = map(int, input().split()) travel(a-1, b-1) subtree_sum = [0] * n dfs(root, root) print(subtree_sum) for u, v in edges_list: print(count_fools(u, v), end=' ') print() ```
instruction
0
50,765
1
101,530
No
output
1
50,765
1
101,531
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: * all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); * to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); * no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit). Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of intersections and roads, respectively. The following m lines contain two integers — the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads. Output If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO. Examples Input 4 4 1 2 2 3 3 4 4 1 Output NO Input 5 6 1 2 1 3 1 4 2 5 3 5 4 5 Output YES 3 5 4 1 3 5 3 1 3 5 2 1
instruction
0
50,882
1
101,764
Tags: dfs and similar, graphs Correct Solution: ``` from typing import List import sys n, m = [int(a) for a in input().split(' ')] adj: List[List[int]] = [[]] + [[] for _ in range(n)] visited: List[bool] = [False] * (n + 1) parent: List[int] = [0] * (n + 1) depth: List[int] = [0] * (n + 1) low: List[int] = [0] * (n + 1) cx: List[int] = [0] * (n + 1) cy: List[int] = [0] * (n + 1) qi: List[int] = [0] * (n + 1) for i in range(m): u, v = [int(a) for a in input().split(' ')] adj[u].append(v) adj[v].append(u) def solve(): for i in range(1, n + 1): if not visited[i]: # dfs(i) dfs2(i) print('NO') def lca(a, b): while depth[a] > depth[b]: a = parent[a] while depth[b] > depth[a]: b = parent[b] while a != b: a = parent[a] b = parent[b] return a def parent_path(a, b): p = [] while a != b: p.append(str(a)) a = parent[a] p.append(str(b)) return p def gett(a, b, u, v, e): if depth[b] > depth[v]: a, b, u, v = u, v, a, b # e = lca(a, u) print('YES') c1 = parent_path(e, v) print(' '.join([str(len(c1))] + c1)) c2 = list(reversed(parent_path(a, e))) + list(reversed(parent_path(v, b))) print(' '.join([str(len(c2))] + c2)) c3 = list(reversed(parent_path(u, e))) + [str(v)] print(' '.join([str(len(c3))] + c3)) exit(0) def dfs(i): visited[i] = True depth[i] = depth[parent[i]] + 1 for ni in adj[i]: if parent[i] != ni: if not visited[ni]: parent[ni] = i dfs(ni) elif depth[ni] < depth[i]: x = i while x != ni: if cx[x] and cy[x]: gett(cx[x], cy[x], i, ni) else: cx[x] = i cy[x] = ni x = parent[x] def dfs2(i): visited[i] = True q = list() q.append(i) while len(q) > 0: u = q[-1] if qi[u] >= len(adj[u]): q.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: parent[v] = u depth[v] = depth[u] + 1 visited[v] = True q.append(v) elif depth[v] < depth[u]: x = u while x != v: if cx[x] and cy[x]: gett(cx[x], cy[x], u, v, x) else: cx[x] = u cy[x] = v x = parent[x] solve() ```
output
1
50,882
1
101,765
Provide tags and a correct Python 3 solution for this coding contest problem. You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: * all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); * to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); * no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit). Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of intersections and roads, respectively. The following m lines contain two integers — the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads. Output If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO. Examples Input 4 4 1 2 2 3 3 4 4 1 Output NO Input 5 6 1 2 1 3 1 4 2 5 3 5 4 5 Output YES 3 5 4 1 3 5 3 1 3 5 2 1
instruction
0
50,883
1
101,766
Tags: dfs and similar, graphs Correct Solution: ``` from typing import List import sys n, m = [int(a) for a in input().split(' ')] adj: List[List[int]] = [[]] + [[] for _ in range(n)] visited: List[bool] = [False] * (n + 1) parent: List[int] = [0] * (n + 1) depth: List[int] = [0] * (n + 1) low: List[int] = [0] * (n + 1) cx: List[int] = [0] * (n + 1) cy: List[int] = [0] * (n + 1) qi: List[int] = [0] * (n + 1) for i in range(m): u, v = [int(a) for a in input().split(' ')] adj[u].append(v) adj[v].append(u) def solve(): for i in range(1, n + 1): if not visited[i]: # dfs(i) dfs2(i) print('NO') def lca(a, b): while depth[a] > depth[b]: a = parent[a] while depth[b] > depth[a]: b = parent[b] while a != b: a = parent[a] b = parent[b] return a def parent_path(a, b): p = [] while a != b: p.append(str(a)) a = parent[a] p.append(str(b)) return p def gett(a, b, u, v): if depth[b] > depth[v]: a, b, u, v = u, v, a, b e = lca(a, u) print('YES') c1 = parent_path(e, v) print(' '.join([str(len(c1))] + c1)) c2 = list(reversed(parent_path(a, e))) + list(reversed(parent_path(v, b))) print(' '.join([str(len(c2))] + c2)) c3 = list(reversed(parent_path(u, e))) + [str(v)] print(' '.join([str(len(c3))] + c3)) exit(0) def dfs(i): visited[i] = True depth[i] = depth[parent[i]] + 1 for ni in adj[i]: if parent[i] != ni: if not visited[ni]: parent[ni] = i dfs(ni) elif depth[ni] < depth[i]: x = i while x != ni: if cx[x] and cy[x]: gett(cx[x], cy[x], i, ni) else: cx[x] = i cy[x] = ni x = parent[x] def dfs2(i): visited[i] = True q: List[int] = [] q.append(i) while len(q) > 0: u = q[-1] if qi[u] >= len(adj[u]): q.pop() continue v = adj[u][qi[u]] qi[u] += 1 if parent[u] != v: if not visited[v]: parent[v] = u depth[v] = depth[u] + 1 visited[v] = True q.append(v) elif depth[v] < depth[u]: x = u while x != v: if cx[x] and cy[x]: gett(cx[x], cy[x], u, v) else: cx[x] = u cy[x] = v x = parent[x] solve() ```
output
1
50,883
1
101,767
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: * all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); * to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); * no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit). Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of intersections and roads, respectively. The following m lines contain two integers — the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads. Output If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO. Examples Input 4 4 1 2 2 3 3 4 4 1 Output NO Input 5 6 1 2 1 3 1 4 2 5 3 5 4 5 Output YES 3 5 4 1 3 5 3 1 3 5 2 1 Submitted Solution: ``` from typing import List, Dict import sys # sys.setrecursionlimit(1000000) n, m = [int(a) for a in input().split(' ')] n += 1 adj: List[List[int]] = [[] for _ in range(n)] for mi in range(m): mu, mv = [int(a) for a in input().split(' ')] adj[mu].append(mv) adj[mv].append(mu) visited: List[bool] = [False] * n parent: List[int] = [0] * n disc: List[int] = [0] * n low: List[int] = [0] * n articulation: List[bool] = [False] * n color = 0 bc: Dict[int, Dict[int, List[int]]] = {} in_cycle: List[bool] = [False] * n cycle = [] ext_path = [] p_out = False p_in = False def ena_dis_cycle(): for i in cycle: in_cycle[i] = not in_cycle[i] def get_articulation_points(u, d): visited[u] = True disc[u] = d low[u] = d childCount = 0 isArticulation = False for v in adj[u]: if not visited[v]: parent[v] = u get_articulation_points(v, d + 1) childCount += 1 if low[v] >= disc[u]: isArticulation = True low[u] = min(low[u], low[v]) elif parent[u] != v: low[u] = min(low[u], disc[v]) if (parent[u] != 0 and isArticulation) or (parent[u] == 0 and childCount > 1): articulation[u] = True def color_graph(u, root, acol): global color visited[u] = True if u == root: for v in adj[u]: if not visited[v]: # parent_color[v] = u bc[color] = {} bc[color][u] = [v] bc[color][v] = [u] color_graph(v, root, color) color += 1 elif articulation[u]: for v in adj[u]: if parent[u] != v: if not visited[v]: if low[v] > disc[u]: color += 1 # parent_color[v] = u bc[color] = {} bc[color][v] = [] color_graph(v, root, color) elif low[v] == disc[u]: color += 1 # parent_color[v] = u bc[color] = {} bc[color][u] = [v] bc[color][v] = [u] color_graph(v, root, color) else: bc[color][u] = [v] bc[color][v] = [u] color_graph(v, root, acol) elif disc[v] > disc[u]: bc[color][u].append(v) bc[color][v].append(u) else: for v in adj[u]: if parent[u] != v: if not visited[v]: # parent_color[v] = u bc[color][v] = [u] bc[color][u].append(v) color_graph(v, root, acol) elif disc[u] > disc[v]: bc[color][u].append(v) bc[color][v].append(u) def find_cycle_in_biconnected_component(c): if dfs3(c, list(c.keys())[0]): ena_dis_cycle() for i in range(n): visited[i] = False parent[i] = 0 find_path(c) print_output() exit(0) def dfs3(c, u): visited[u] = True for v in c[u]: if parent[u] != v: if not visited[v]: parent[v] = u if dfs3(c, v): return True elif disc[v] < disc[u]: x = u n = 1 while x != v: n += 1 cycle.append(x) x = parent[x] cycle.append(x) edges = 0 for nod in c.values(): edges += len(nod) if edges//2 == n: return False return True visited[u] = False return False def find_path(c): for u in cycle: for v in c[u]: if in_cycle[v] and abs(u - v) > 1: ext_path = [u, v] elif not in_cycle[v]: visited[u] = True parent[v] = u dfs2(c, v) return def dfs2(c, u): visited[u] = True for v in c[u]: if parent[u] != v: if not visited[v]: parent[v] = u if in_cycle[v]: x = u ext_path.append(v) while parent[x] != 0: ext_path.append(x) x = parent[x] ext_path.append(x) return True else: if dfs2(c, v): return True return False def print_output(): # print(cycle) # print(ext_path) start = ext_path[0] end = ext_path[-1] if cycle.index(start) > cycle.index(end): cycle.reverse() c1 = list(map(str, ext_path)) c2 = list(map(str, cycle[cycle.index(start):cycle.index(end)+1])) c3 = list(map(str, list(reversed(cycle[:cycle.index(start) + 1])) + list(reversed(cycle[cycle.index(end):])))) print('YES') print(' '.join([str(len(c1))] + c1)) print(' '.join([str(len(c2))] + c2)) print(' '.join([str(len(c3))] + c3)) def solve(): for i in range(1, n): if not visited[i]: get_articulation_points(i, 0) for i in range(n): visited[i] = False for i in range(1, n): if not visited[i]: color_graph(i, i, color) for i in range(n): visited[i] = False parent[i] = 0 for c in bc.values(): find_cycle_in_biconnected_component(c) print('NO') try: solve() except Exception as e: print(e) print(e.__traceback__) ```
instruction
0
50,884
1
101,768
No
output
1
50,884
1
101,769
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: * all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); * to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); * no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit). Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of intersections and roads, respectively. The following m lines contain two integers — the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads. Output If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO. Examples Input 4 4 1 2 2 3 3 4 4 1 Output NO Input 5 6 1 2 1 3 1 4 2 5 3 5 4 5 Output YES 3 5 4 1 3 5 3 1 3 5 2 1 Submitted Solution: ``` from typing import List n, m = [int(a) for a in input().split(' ')] adj: List[List[int]] = [[]] + [[] for _ in range(n)] visited: List[bool] = [False] * (n + 1) parent: List[int] = [0] * (n + 1) depth: List[int] = [0] * (n + 1) low: List[int] = [0] * (n + 1) cx: List[int] = [0] * (n + 1) cy: List[int] = [0] * (n + 1) qi: List[int] = [0] * (n + 1) in_cycle: List[bool] = [False] * (n + 1) cycle = [] ext_path = [] def ena_dis_cycle(): for i in cycle[1:]: in_cycle[i] = not in_cycle[i] for i in range(m): u, v = [int(a) for a in input().split(' ')] adj[u].append(v) adj[v].append(u) def one_cycle_dfs(u): visited[u] = True for i in range(len(adj[u])): v = adj[u][i] if not visited[v]: parent[v] = u b, x = one_cycle_dfs(v) parent[v] = 0 if b: if parent[u] != 0: adj[u][i], adj[u][-1] = adj[u][-1], adj[u][i] adj[u].pop() for k in range(len(adj[u])): if parent[u] != 0 and adj[u][k] == parent[u]: adj[u][k], adj[u][-1] = adj[u][-1], adj[u][k] adj[u].pop() break if parent[u] == 0 and adj[u][k] == v: adj[u][k], adj[u][-1] = adj[u][-1], adj[u][k] adj[u].pop() break visited[u] = False cycle.append(u) if x == u: return False, x return True, x elif parent[u] != v: adj[u][i], adj[u][-1] = adj[u][-1], adj[u][i] adj[u].pop() for k in range(len(adj[u])): if adj[u][k] == parent[u]: adj[u][k], adj[u][-1] = adj[u][-1], adj[u][k] adj[u].pop() break for k in range(len(adj[v])): if u == adj[v][k]: adj[v][k], adj[v][-1] = adj[v][-1], adj[v][k] adj[v].pop() break cycle.append(v) cycle.append(u) visited[u] = False return True, v visited[u] = False parent[u] = 0 return False, -1 def path_dfs(u): visited[u] = True for v in adj[u]: if parent[u] != v: if not visited[v]: if in_cycle[v]: ext_path.append(v) ext_path.append(u) return True parent[v] = u b = path_dfs(v) parent[v] = 0 if b: ext_path.append(u) visited[u] = False return True visited[u] = False def build_paths(): print("YES") b = ext_path[0] f = ext_path[-1] b_i = cycle.index(b) f_i = cycle.index(f) if b_i > f_i: b_i, f_i = f_i, b_i ext_path.reverse() c1 = cycle[b_i:f_i+1] c2 = cycle[f_i:-1] + cycle[:b_i+1] c2.reverse() c3 = ext_path print(' '.join([str(len(c1))] + [str(a) for a in c1])) print(' '.join([str(len(c2))] + [str(a) for a in c2])) print(' '.join([str(len(c3))] + [str(a) for a in c3])) exit(0) def solve(): for i in range(1, n + 1): b, x = one_cycle_dfs(i) if x == -1: continue ena_dis_cycle() for j in cycle: if path_dfs(i): build_paths() ena_dis_cycle() cycle.clear() print('NO') solve() ```
instruction
0
50,885
1
101,770
No
output
1
50,885
1
101,771
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: * all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); * to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); * no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit). Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of intersections and roads, respectively. The following m lines contain two integers — the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads. Output If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO. Examples Input 4 4 1 2 2 3 3 4 4 1 Output NO Input 5 6 1 2 1 3 1 4 2 5 3 5 4 5 Output YES 3 5 4 1 3 5 3 1 3 5 2 1 Submitted Solution: ``` from typing import List import sys try: sys.setrecursionlimit(1000000) n, m = [int(a) for a in input().split(' ')] adj: List[List[int]] = [[]] + [[] for _ in range(n)] visited: List[bool] = [False] * (n + 1) parent: List[int] = [0] * (n + 1) depth: List[int] = [0] * (n + 1) low: List[int] = [0] * (n + 1) cx: List[int] = [0] * (n + 1) cy: List[int] = [0] * (n + 1) for i in range(m): u, v = [int(a) for a in input().split(' ')] adj[u].append(v) adj[v].append(u) def solve(): for i in range(1, n + 1): if not visited[i]: dfs(i) print('NO') def lca(a, b): while depth[a] > depth[b]: a = parent[a] while depth[b] > depth[a]: b = parent[b] while a != b: a = parent[a] b = parent[b] return a def parent_path(a, b): p = [] while a != b: p.append(str(a)) a = parent[a] p.append(str(b)) return p def gett(a, b, u, v): if depth[b] > depth[v]: a, b, u, v = u, v, a, b e = lca(a, u) print('YES') c1 = parent_path(e, v) print(' '.join([str(len(c1))] + c1)) c2 = list(reversed(parent_path(a, e))) + list(reversed(parent_path(v, b))) print(' '.join([str(len(c2))] + c2)) c3 = list(reversed(parent_path(u, e))) + [str(v)] print(' '.join([str(len(c3))] + c3)) exit(0) def dfs(i): visited[i] = True depth[i] = depth[parent[i]] + 1 for ni in adj[i]: if parent[i] != ni: if not visited[ni]: parent[ni] = i dfs(ni) elif depth[ni] < depth[i]: x = i while x != ni: if cx[x] and cy[x]: gett(cx[x], cy[x], i, ni) else: cx[x] = i cy[x] = ni x = parent[x] def dfs(i): visited[i] = True visited[i] = True depth[i] = depth[parent[i]] + 1 for ni in adj[i]: if parent[i] != ni: if not visited[ni]: parent[ni] = i dfs(ni) elif depth[ni] < depth[i]: x = i while x != ni: if cx[x] and cy[x]: gett(cx[x], cy[x], i, ni) else: cx[x] = i cy[x] = ni x = parent[x] solve() except Exception as e: print(str(e)) ```
instruction
0
50,886
1
101,772
No
output
1
50,886
1
101,773
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: * all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); * to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); * no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit). Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met. Input The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of intersections and roads, respectively. The following m lines contain two integers — the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads. Output If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO. Examples Input 4 4 1 2 2 3 3 4 4 1 Output NO Input 5 6 1 2 1 3 1 4 2 5 3 5 4 5 Output YES 3 5 4 1 3 5 3 1 3 5 2 1 Submitted Solution: ``` from typing import List n, m = [int(a) for a in input().split(' ')] adj: List[List[int]] = [[]] + [[] for _ in range(n)] visited: List[bool] = [False] * (n + 1) parent: List[int] = [0] * (n + 1) depth: List[int] = [0] * (n + 1) low: List[int] = [0] * (n + 1) cx: List[int] = [0] * (n + 1) cy: List[int] = [0] * (n + 1) for i in range(m): u, v = [int(a) for a in input().split(' ')] adj[u].append(v) adj[v].append(u) def solve(): for i in range(1, n + 1): if not visited[i]: dfs(i) print('NO') def lca(a, b): while depth[a] > depth[b]: a = parent[a] while depth[b] > depth[a]: b = parent[b] while a != b: a = parent[a] b = parent[b] return a def parent_path(a, b): p = [] while a != b: p.append(str(a)) a = parent[a] p.append(str(b)) return p def gett(a, b, u, v): if depth[b] > depth[v]: a, b, u, v = u, v, a, b e = lca(a, u) print('YES') c1 = parent_path(e, v) print(' '.join([str(len(c1))] + c1)) c2 = list(reversed(parent_path(a, e))) + list(reversed(parent_path(v, b))) print(' '.join([str(len(c2))] + c2)) c3 = list(reversed(parent_path(u, e))) + [str(b)] print(' '.join([str(len(c3))] + c3)) exit(0) def dfs(i): visited[i] = True depth[i] = depth[parent[i]] + 1 visited[i] = True for ni in adj[i]: if parent[i] != ni: if not visited[ni]: parent[ni] = i dfs(ni) elif depth[ni] < depth[i]: x = i while x != ni: if cx[x] and cy[x]: gett(cx[x], cy[x], i, ni) else: cx[x] = i cy[x] = ni x = parent[x] solve() ```
instruction
0
50,887
1
101,774
No
output
1
50,887
1
101,775
Provide tags and a correct Python 3 solution for this coding contest problem. A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are <image> roads in total. It takes exactly y seconds to traverse any single road. A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads. Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y. You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once. Input The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree. Output Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once. Examples Input 5 2 3 1 2 1 3 3 4 5 3 Output 9 Input 5 3 2 1 2 1 3 3 4 5 3 Output 8 Note In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is <image>. In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is <image>.
instruction
0
50,931
1
101,862
Tags: dfs and similar, dp, graph matchings, greedy, trees Correct Solution: ``` from collections import defaultdict from collections import deque from functools import reduce n, x, y = [int(x) for x in input().split()] E = defaultdict(set) for i in range(n-1): u, v = [int(x) for x in input().split()] E[u].add(v) E[v].add(u) if x > y: for v in E: if len(E[v]) == n-1: print((n-2)*y + x) break elif len(E[v]) > 1: print((n-1)*y) break else: visited = {v : False for v in E} stack = [1] topsorted = deque() while stack: v = stack.pop() if visited[v]: continue visited[v] = True topsorted.appendleft(v) stack.extend(E[v]) chopped = set() ans = 0 for v in topsorted: ans += max(0, len(E[v])-2) if len(E[v]) > 2: S = E[v].intersection(chopped) S1 = {S.pop(), S.pop()} for u in E[v]: if not u in S1: E[u].remove(v) E[v].clear() E[v].update(S1) chopped.add(v) print(ans*y + (n-1-ans)*x) ```
output
1
50,931
1
101,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are <image> roads in total. It takes exactly y seconds to traverse any single road. A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads. Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y. You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once. Input The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree. Output Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once. Examples Input 5 2 3 1 2 1 3 3 4 5 3 Output 9 Input 5 3 2 1 2 1 3 3 4 5 3 Output 8 Note In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is <image>. In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is <image>. Submitted Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 missingdays <missingdays@missingdays> # # Distributed under terms of the MIT license. """ """ n, x, y = [int(i) for i in input().split()] if x > y: print((n-1) * y) else: print((n-2)*x + y) ```
instruction
0
50,932
1
101,864
No
output
1
50,932
1
101,865
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are <image> roads in total. It takes exactly y seconds to traverse any single road. A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads. Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y. You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once. Input The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree. Output Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once. Examples Input 5 2 3 1 2 1 3 3 4 5 3 Output 9 Input 5 3 2 1 2 1 3 3 4 5 3 Output 8 Note In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is <image>. In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is <image>. Submitted Solution: ``` #!/usr/bin/python3 (n, x, y) = tuple(map(int, input().split())) degree = [0]*n vertices = [] for i in range(n-1): (v1, v2) = tuple(map(int, input().split())) degree[v1-1] += 1 degree[v2-1] += 1 vertices.append((v1, v2)) if x < y: d = 0 used = set() full = set() for i in vertices: if i[0] not in full and i[1] not in full: d += 1 if i[0] in used: used.remove(i[0]) full.add(i[0]) else: used.add(i[0]) if i[1] in used: used.remove(i[1]) full.add(i[1]) else: used.add(i[1]) print(str(d*x+(n-1-d)*y)) elif x > y: d = 0 for i in degree: if i == n-1: d = 1 print(str(d*x+(n-1-d)*y)) else: print(str((n-1)*x)) ```
instruction
0
50,933
1
101,866
No
output
1
50,933
1
101,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are <image> roads in total. It takes exactly y seconds to traverse any single road. A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads. Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y. You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once. Input The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree. Output Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once. Examples Input 5 2 3 1 2 1 3 3 4 5 3 Output 9 Input 5 3 2 1 2 1 3 3 4 5 3 Output 8 Note In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is <image>. In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is <image>. Submitted Solution: ``` import sys sys.setrecursionlimit(10000000) def dfs(v): global answer, color, s a = 0 for u in (s[v]): if color[u] == 0: a += 1 color[u] = 1 dfs(u) answer += max(0, a - 1) n, x, y = map(int, input().split()) if x >= y: print((n - 1) * y) else: s = [[] for i in range(n)] for i in range(n - 1): a, b = map(int, input().split()) s[a - 1].append(b - 1) s[b - 1].append(a - 1) answer = 0 for i in range(n): if len(s[i]) == 1: color = [0] * n color[i] = 1 dfs(i) break print(answer * y + (n - 1 - answer) * x) ```
instruction
0
50,934
1
101,868
No
output
1
50,934
1
101,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are <image> roads in total. It takes exactly y seconds to traverse any single road. A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads. Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y. You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once. Input The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree. Output Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once. Examples Input 5 2 3 1 2 1 3 3 4 5 3 Output 9 Input 5 3 2 1 2 1 3 3 4 5 3 Output 8 Note In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is <image>. In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is <image>. Submitted Solution: ``` n, x, y = map(int, input().split()) if y <= x: print(y * (n - 1)) else: cnt = [0 for i in range(n)] for i in range(n - 1): a, b = map(int, input().split()) cnt[a - 1] += 1 cnt[b - 1] += 1 jumps = 0 for i in cnt: jumps += (i - 1) // 2 print((n - 1 - jumps) * x + jumps * y) ```
instruction
0
50,935
1
101,870
No
output
1
50,935
1
101,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible. He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash. They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well. Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route. Please also note that only friends that are waiting for a gift count as unhappy, even if they die. Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. Input The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, <image>, 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. Output Print a single integer, the answer to the problem. Examples Input 4 4 3 1 2 1 2 3 1 2 4 1 3 1 1 Output 2 Input 7 11 2 1 2 5 1 3 5 2 4 2 2 5 2 3 6 3 3 7 3 4 6 2 3 4 2 6 7 3 4 5 7 4 7 7 Output 4 Note In the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. Submitted Solution: ``` # -*- coding: utf-8 -*- import heapq _BLANCO, _GRIS, _NEGRO = 0, 1, 2 _NIL = -1 _OO = 18446744073709551615 #***************************** DFS ***************************** def dfs(adj): pi, color, tiempo = dfs_initialization(adj) d, f = [-1] * len(adj), [-1] * len(adj) for u in range(len(adj)): if color[u] == _BLANCO: tiempo = dfs_visit(u, adj, pi, color, tiempo, d, f) return pi, d, f def dfs_initialization(adj): n = len(adj) return [_NIL] * n, [_BLANCO] * n, 0 def dfs_visit(u, adj, pi, color, tiempo, d, f): color[u] = _GRIS d[u] = tiempo = tiempo + 1 for v in adj[u]: if color[v] == _BLANCO: pi[v] = u tiempo = dfs_visit(v, adj, pi, color, tiempo, d, f) color[u] = _NEGRO f[u] = tiempo = tiempo + 1 return tiempo def dfs_visit_once(adj, s): n = len(adj) pi, color, tiempo = dfs_initialization(adj) d, f = [-1] * n, [-1] * n dfs_visit(s, adj, pi, color, tiempo, d, f) # llamado al dfs_visit return pi, d, f #****************************** DIJKSTRA ****************************** def dijkstra(adj, s): pi, d = initialize_single_source(adj, s) estaEnS = [False] * len(adj) Q = [] for u in range(len(adj)): Q.append((d[u], u)) heapq.heapify(Q) while len(Q) != 0: u = heapq.heappop(Q)[1] if estaEnS[u]: continue estaEnS[u] = True for v, w_u_v in adj[u]: relax(u, v, w_u_v, d, pi, Q) return pi, d def initialize_single_source(adj, s): n = len(adj) d = [_OO] * n d[s] = 0 pi = [] for i in range(n): pi.append([_NIL]) return pi, d def relax(u, v, w_u_v, d, pi, Q): if d[v] > d[u] + w_u_v: d[v] = d[u] + w_u_v pi[v].append(u) heapq.heappush(Q, (d[v], v)) elif d[v] > d[u] + w_u_v: pi[v].append(u) def construir_arbol_dominador(adj, s): n = len(adj) pi, d, f = dfs_visit_once(adj, s) rd = [-1] * (2 * n) # rd[tiempo] = v ssi d[v] = tiempo tadj = transponer_grafo(adj) secAsc = [i for i in range(n)] # secuencia ascendente [0, 1, 2, ..., n] dsu = secAsc[:] # disjoint set union idom, sdom = secAsc[:], secAsc[:] minRsdom = secAsc[:] # v tal que sdom[v] es minimo en el camino hacia la raiz en el arbol del dsu rsdom = matriz_vacia(n) # rsdom[u] = {w1, w2, ..., wk} ssi sdom[wi] = u para i = 1, 2, ..., k arbolDom = matriz_vacia(n) for i in range(n): rd[d[i]] = i for dw in [t for t in range(2 * n - 1, 0, -1) if rd[t] >= 0]:# tiempos de descubrimiento validos en orden decreciente w = rd[dw] for v in tadj[w]: u = find(v, dsu, d, sdom, minRsdom) if d[sdom[u]] < d[sdom[w]]: sdom[w] = sdom[u] if dw > 1: rsdom[sdom[w]].append(w) for w1 in rsdom[w]: v1 = find(w1, dsu, d, sdom, minRsdom) if sdom[v1] == sdom[w1]: idom[w1] = sdom[w1] else: idom[w1] = v1 if dw > 1: join(pi[w], w, dsu) for dw in [t for t in range(2, 2 * n) if rd[t] >= 0]:# tiempos de descubrimiento validos en orden creciente desde 2 w = rd[dw] if idom[w] != sdom[w]: idom[w] = idom[idom[w]] arbolDom[idom[w]].append(w) return arbolDom def transponer_grafo(adj): n = len(adj) tadj = matriz_vacia(n) for u in range(n): for v in adj[u]: tadj[v].append(u) return tadj def find(u, dsu, d, sdom, minRsdom, f = False): if dsu[u] == u: return -1 if f else u v = find(dsu[u], dsu, d, sdom, minRsdom, f or True) if v < 0: return u if d[sdom[minRsdom[dsu[u]]]] < d[sdom[minRsdom[u]]]: minRsdom[u] = minRsdom[dsu[u]] dsu[u] = v return v if f else minRsdom[u] def join(u, v, dsu): dsu[v] = u def matriz_vacia(n): mat = [] for i in range(n): mat.append([]) return mat def leer_enteros(n): return [int(cad) for cad in input().split()] def solve(adj, s): n = len(adj) piDijk, dDijk = dijkstra(adj, s) arbolDijkstra = matriz_vacia(n) for u in range(n): if u != s: for pu in piDijk[u]: arbolDijkstra[pu].append(u) arbolDom = construir_arbol_dominador(arbolDijkstra, s) piDom, dDom, fDom = dfs_visit_once(arbolDom, s) respuesta = 0 for u in range(n): if u != s: respuesta = max(respuesta, (fDom[u] - dDom[u]) // 2 + 1) return respuesta def caso1(): return [[[1, 1], [2, 1]], [[2, 1], [3, 1], [0, 1]], [[0, 1], [1, 1]], [[1, 1]]], 3 if __name__ == '__main__': n, m, s = leer_enteros(3) adj = matriz_vacia(n) for i in range(m): u, v, w = leer_enteros(3) adj[u - 1].append((v - 1, w)) adj[v - 1].append((u - 1, w)) # adj, s = caso1() print(solve(adj, s - 1)) # pi, d = dijkstra([[[1, 10], [3, 5]], # [[2, 1], [3, 2]], # [[4, 4]], # [[1, 3], [2, 9], [4, 2]], # [[0, 7], [2, 6]]], 0) # print(pi, d, sep='\n') # arbol = construir_arbol_dominador([[3],# A = 0 # [0, 3, 4], #B = 1 # [5, 6], #C = 2 # [11], #D = 3 # [7], #E = 4 # [8], #F = 5 # [8, 9], #G = 6 # [4, 10], #H = 7 # [10], #I = 8 # [8], #J = 9 # [8, 12], #K = 10 # [7], #L = 11 # [0, 1, 2]] #R = 12 # , 12) # print(arbol) ```
instruction
0
50,979
1
101,958
No
output
1
50,979
1
101,959
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible. He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash. They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well. Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route. Please also note that only friends that are waiting for a gift count as unhappy, even if they die. Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. Input The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, <image>, 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. Output Print a single integer, the answer to the problem. Examples Input 4 4 3 1 2 1 2 3 1 2 4 1 3 1 1 Output 2 Input 7 11 2 1 2 5 1 3 5 2 4 2 2 5 2 3 6 3 3 7 3 4 6 2 3 4 2 6 7 3 4 5 7 4 7 7 Output 4 Note In the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. Submitted Solution: ``` # -*- coding: utf-8 -*- import heapq _BLANCO, _GRIS, _NEGRO = 0, 1, 2 _NIL = -1 _OO = 18446744073709551615 #***************************** DFS ***************************** def dfs(adj): pi, color, tiempo = dfs_initialization(adj) d, f = [-1] * len(adj), [-1] * len(adj) for u in range(len(adj)): if color[u] == _BLANCO: tiempo = dfs_visit(u, adj, pi, color, tiempo, d, f) return pi, d, f def dfs_initialization(adj): n = len(adj) return [_NIL] * n, [_BLANCO] * n, 0 def dfs_visit(u, adj, pi, color, tiempo, d, f): color[u] = _GRIS d[u] = tiempo = tiempo + 1 for v in adj[u]: if color[v] == _BLANCO: pi[v] = u tiempo = dfs_visit(v, adj, pi, color, tiempo, d, f) color[u] = _NEGRO f[u] = tiempo = tiempo + 1 return tiempo def dfs_visit_once(adj, s): n = len(adj) pi, color, tiempo = dfs_initialization(adj) d, f = [-1] * n, [-1] * n dfs_visit(s, adj, pi, color, tiempo, d, f) # llamado al dfs_visit return pi, d, f #****************************** DIJKSTRA ****************************** def dijkstra(adj, s): pi, d = initialize_single_source(adj, s) estaEnS = [False] * len(adj) Q = [] for u in range(len(adj)): Q.append((d[u], u)) heapq.heapify(Q) while len(Q) != 0: u = heapq.heappop(Q)[1] if estaEnS[u]: continue estaEnS[u] = True for v, w_u_v in adj[u]: relax(u, v, w_u_v, d, pi, Q) return pi, d def initialize_single_source(adj, s): n = len(adj) d = [_OO] * n d[s] = 0 return [_NIL] * n, d def relax(u, v, w_u_v, d, pi, Q): if d[v] > d[u] + w_u_v: d[v] = d[u] + w_u_v pi[v] = u heapq.heappush(Q, (d[v], v)) def construir_arbol_dominador(adj, s): n = len(adj) pi, d, f = dfs_visit_once(adj, s) rd = [-1] * (2 * n) # rd[tiempo] = v ssi d[v] = tiempo tadj = transponer_grafo(adj) secAsc = [i for i in range(n)] # secuencia ascendente [0, 1, 2, ..., n] dsu = secAsc[:] # disjoint set union idom, sdom = secAsc[:], secAsc[:] minRsdom = secAsc[:] # v tal que sdom[v] es minimo en el camino hacia la raiz en el arbol del dsu rsdom = matriz_vacia(n) # rsdom[u] = {w1, w2, ..., wk} ssi sdom[wi] = u para i = 1, 2, ..., k arbolDom = matriz_vacia(n) for i in range(n): rd[d[i]] = i for dw in [t for t in range(2 * n - 1, 0, -1) if rd[t] >= 0]:# tiempos de descubrimiento validos en orden decreciente w = rd[dw] for v in tadj[w]: u = find(v, dsu, d, sdom, minRsdom) if d[sdom[u]] < d[sdom[w]]: sdom[w] = sdom[u] if dw > 1: rsdom[sdom[w]].append(w) for w1 in rsdom[w]: v1 = find(w1, dsu, d, sdom, minRsdom) if sdom[v1] == sdom[w1]: idom[w1] = sdom[w1] else: idom[w1] = v1 if dw > 1: join(pi[w], w, dsu) for dw in [t for t in range(2, 2 * n) if rd[t] >= 0]:# tiempos de descubrimiento validos en orden creciente desde 2 w = rd[dw] if idom[w] != sdom[w]: idom[w] = idom[idom[w]] arbolDom[idom[w]].append(w) return arbolDom def transponer_grafo(adj): n = len(adj) tadj = matriz_vacia(n) for u in range(n): for v in adj[u]: tadj[v].append(u) return tadj def find(u, dsu, d, sdom, minRsdom, f = False): if dsu[u] == u: return -1 if f else u v = find(dsu[u], dsu, d, sdom, minRsdom, f or True) if v < 0: return u if d[sdom[minRsdom[dsu[u]]]] < d[sdom[minRsdom[u]]]: minRsdom[u] = minRsdom[dsu[u]] dsu[u] = v return v if f else minRsdom[u] def join(u, v, dsu): dsu[v] = u def matriz_vacia(n): mat = [] for i in range(n): mat.append([]) return mat def leer_enteros(n): return [int(cad) for cad in input().split()] def solve(adj, s): n = len(adj) piDijk, dDijk = dijkstra(adj, s) arbolDijkstra = matriz_vacia(n) for u in range(n): if u != s: arbolDijkstra[piDijk[u]].append(u) arbolDom = construir_arbol_dominador(arbolDijkstra, s) piDom, dDom, fDom = dfs_visit_once(arbolDom, s) respuesta = 0 for u in range(n): if u != s: respuesta = max(respuesta, (fDom[u] - dDom[u]) // 2 + 1) return respuesta def caso1(): return [[[1, 1], [2, 1]], [[2, 1], [3, 1], [0, 1]], [[0, 1], [1, 1]], [[1, 1]]], 2 if __name__ == '__main__': n, m, s = leer_enteros(3) adj = matriz_vacia(n) for i in range(m): u, v, w = leer_enteros(3) adj[u - 1].append((v - 1, w)) adj[v - 1].append((u - 1, w)) # adj, s = caso1() print(solve(adj, s - 1)) # pi, d = dijkstra([[[1, 10], [3, 5]], # [[2, 1], [3, 2]], # [[4, 4]], # [[1, 3], [2, 9], [4, 2]], # [[0, 7], [2, 6]]], 0) # print(pi, d, sep='\n') # arbol = construir_arbol_dominador([[3],# A = 0 # [0, 3, 4], #B = 1 # [5, 6], #C = 2 # [11], #D = 3 # [7], #E = 4 # [8], #F = 5 # [8, 9], #G = 6 # [4, 10], #H = 7 # [10], #I = 8 # [8], #J = 9 # [8, 12], #K = 10 # [7], #L = 11 # [0, 1, 2]] #R = 12 # , 12) # print(arbol) ```
instruction
0
50,980
1
101,960
No
output
1
50,980
1
101,961
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the turn of the year, so Bash wants to send presents to his friends. There are n cities in the Himalayan region and they are connected by m bidirectional roads. Bash is living in city s. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city. He also wants to send it to them as soon as possible. He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of 1 meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash. They do this by destroying exactly one of the other n - 1 cities. This implies that the friend residing in that city dies, so he is unhappy as well. Note that if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route. Please also note that only friends that are waiting for a gift count as unhappy, even if they die. Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city. Input The first line contains three space separated integers n, m and s (2 ≤ n ≤ 2·105, <image>, 1 ≤ s ≤ n) — the number of cities and the number of roads in the Himalayan region and the city Bash lives in. Each of the next m lines contain three space-separated integers u, v and w (1 ≤ u, v ≤ n, u ≠ v, 1 ≤ w ≤ 109) denoting that there exists a road between city u and city v of length w meters. It is guaranteed that no road connects a city to itself and there are no two roads that connect the same pair of cities. Output Print a single integer, the answer to the problem. Examples Input 4 4 3 1 2 1 2 3 1 2 4 1 3 1 1 Output 2 Input 7 11 2 1 2 5 1 3 5 2 4 2 2 5 2 3 6 3 3 7 3 4 6 2 3 4 2 6 7 3 4 5 7 4 7 7 Output 4 Note In the first sample, on destroying the city 2, the length of shortest distance between pairs of cities (3, 2) and (3, 4) will change. Hence the answer is 2. Submitted Solution: ``` # -*- coding: utf-8 -*- import heapq _BLANCO, _GRIS, _NEGRO = 0, 1, 2 _NIL = -1 _OO = 18446744073709551615 #***************************** DFS ***************************** def dfs(adj): pi, color, tiempo = dfs_initialization(adj) d, f = [-1] * len(adj), [-1] * len(adj) for u in range(len(adj)): if color[u] == _BLANCO: tiempo = dfs_visit(u, adj, pi, color, tiempo, d, f) return pi, d, f def dfs_initialization(adj): n = len(adj) return [_NIL] * n, [_BLANCO] * n, 0 def dfs_visit(u, adj, pi, color, tiempo, d, f): color[u] = _GRIS d[u] = tiempo = tiempo + 1 for v in adj[u]: if color[v] == _BLANCO: pi[v] = u tiempo = dfs_visit(v, adj, pi, color, tiempo, d, f) color[u] = _NEGRO f[u] = tiempo = tiempo + 1 return tiempo def dfs_visit_once(adj, s): n = len(adj) pi, color, tiempo = dfs_initialization(adj) d, f = [-1] * n, [-1] * n dfs_visit(s, adj, pi, color, tiempo, d, f) # llamado al dfs_visit return pi, d, f #****************************** DIJKSTRA ****************************** def dijkstra(adj, s): pi, d = initialize_single_source(adj, s) estaEnS = [False] * len(adj) Q = [] for u in range(len(adj)): Q.append((d[u], u)) heapq.heapify(Q) while len(Q) != 0: u = heapq.heappop(Q)[1] if estaEnS[u]: continue estaEnS[u] = True for v, w_u_v in adj[u]: relax(u, v, w_u_v, d, pi, Q) return pi, d def initialize_single_source(adj, s): n = len(adj) d = [_OO] * n d[s] = 0 pi = [] for i in range(n): pi.append([_NIL]) return pi, d def relax(u, v, w_u_v, d, pi, Q): if d[v] > d[u] + w_u_v: d[v] = d[u] + w_u_v pi[v].append(u) heapq.heappush(Q, (d[v], v)) elif d[v] == d[u] + w_u_v: pi[v].append(u) def construir_arbol_dominador(adj, s): n = len(adj) pi, d, f = dfs_visit_once(adj, s) rd = [-1] * (2 * n) # rd[tiempo] = v ssi d[v] = tiempo tadj = transponer_grafo(adj) secAsc = [i for i in range(n)] # secuencia ascendente [0, 1, 2, ..., n] dsu = secAsc[:] # disjoint set union idom, sdom = secAsc[:], secAsc[:] minRsdom = secAsc[:] # v tal que sdom[v] es minimo en el camino hacia la raiz en el arbol del dsu rsdom = matriz_vacia(n) # rsdom[u] = {w1, w2, ..., wk} ssi sdom[wi] = u para i = 1, 2, ..., k arbolDom = matriz_vacia(n) for i in range(n): rd[d[i]] = i for dw in [t for t in range(2 * n - 1, 0, -1) if rd[t] >= 0]:# tiempos de descubrimiento validos en orden decreciente w = rd[dw] for v in tadj[w]: u = find(v, dsu, d, sdom, minRsdom) if d[sdom[u]] < d[sdom[w]]: sdom[w] = sdom[u] if dw > 1: rsdom[sdom[w]].append(w) for w1 in rsdom[w]: v1 = find(w1, dsu, d, sdom, minRsdom) if sdom[v1] == sdom[w1]: idom[w1] = sdom[w1] else: idom[w1] = v1 if dw > 1: join(pi[w], w, dsu) for dw in [t for t in range(2, 2 * n) if rd[t] >= 0]:# tiempos de descubrimiento validos en orden creciente desde 2 w = rd[dw] if idom[w] != sdom[w]: idom[w] = idom[idom[w]] arbolDom[idom[w]].append(w) return arbolDom def transponer_grafo(adj): n = len(adj) tadj = matriz_vacia(n) for u in range(n): for v in adj[u]: tadj[v].append(u) return tadj def find(u, dsu, d, sdom, minRsdom, f = False): if dsu[u] == u: return -1 if f else u v = find(dsu[u], dsu, d, sdom, minRsdom, f or True) if v < 0: return u if d[sdom[minRsdom[dsu[u]]]] < d[sdom[minRsdom[u]]]: minRsdom[u] = minRsdom[dsu[u]] dsu[u] = v return v if f else minRsdom[u] def join(u, v, dsu): dsu[v] = u def matriz_vacia(n): mat = [] for i in range(n): mat.append([]) return mat def leer_enteros(n): return [int(cad) for cad in input().split()] def solve(adj, s): n = len(adj) piDijk, dDijk = dijkstra(adj, s) arbolDijkstra = matriz_vacia(n) for u in range(n): if u != s: for pu in piDijk[u]: arbolDijkstra[pu].append(u) arbolDom = construir_arbol_dominador(arbolDijkstra, s) piDom, dDom, fDom = dfs_visit_once(arbolDom, s) respuesta = 0 for u in range(n): if u != s: respuesta = max(respuesta, (fDom[u] - dDom[u]) // 2 + 1) return respuesta def caso1(): return [[[1, 1], [2, 1]], [[2, 1], [3, 1], [0, 1]], [[0, 1], [1, 1]], [[1, 1]]], 3 if __name__ == '__main__': n, m, s = leer_enteros(3) adj = matriz_vacia(n) for i in range(m): u, v, w = leer_enteros(3) adj[u - 1].append((v - 1, w)) adj[v - 1].append((u - 1, w)) # adj, s = caso1() print(solve(adj, s - 1)) # pi, d = dijkstra([[[1, 10], [3, 5]], # [[2, 1], [3, 2]], # [[4, 4]], # [[1, 3], [2, 9], [4, 2]], # [[0, 7], [2, 6]]], 0) # print(pi, d, sep='\n') # arbol = construir_arbol_dominador([[3],# A = 0 # [0, 3, 4], #B = 1 # [5, 6], #C = 2 # [11], #D = 3 # [7], #E = 4 # [8], #F = 5 # [8, 9], #G = 6 # [4, 10], #H = 7 # [10], #I = 8 # [8], #J = 9 # [8, 12], #K = 10 # [7], #L = 11 # [0, 1, 2]] #R = 12 # , 12) # print(arbol) ```
instruction
0
50,981
1
101,962
No
output
1
50,981
1
101,963
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,107
1
102,214
"Correct Solution: ``` import sys input=sys.stdin.readline import heapq n,q=map(int,input().split()) l=[list(map(int,input().split())) for i in range(n)] L1=[] for i in range(n): L1.append((l[i][0]-l[i][2],1,l[i][2])) L1.append((l[i][1]-l[i][2],-1,l[i][2])) for i in range(q): L1.append((int(input()),2,0)) L1.sort() L2=[] heapq.heapify(L2) L3=[] L3=set(L3) for i in range(len(L1)): if L1[i][1]==1: heapq.heappush(L2,L1[i][2]) L3.add(L1[i][2]) elif L1[i][1]==-1: L3.remove(L1[i][2]) else: while L2 and L2[0] not in L3: heapq.heappop(L2) if L2: print(L2[0]) else: print(-1) ```
output
1
51,107
1
102,215
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,108
1
102,216
"Correct Solution: ``` from bisect import bisect_left N,Q = (int(x) for x in input().split()) stop_arr = [tuple(map(int, input().split())) for _ in range(N)] Q_arr = [int(input()) for _ in range(Q)] stop_arr.sort(key=lambda x:x[2]) ans_arr = [-1]*Q skip_arr = [-1]*(Q+1) for s,t,x in stop_arr: q_start = bisect_left(Q_arr, s-x) q_stop = bisect_left(Q_arr, t-x) l = q_start while l < q_stop: if skip_arr[l] == -1: skip_arr[l] = q_stop ans_arr[l] = x l += 1 else: l = skip_arr[l] print(*ans_arr, sep="\n") ```
output
1
51,108
1
102,217
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,109
1
102,218
"Correct Solution: ``` #!/usr/bin/env python3 import sys, math, itertools, collections, bisect, heapq input = lambda: sys.stdin.buffer.readline() inf = float('inf') ;mod = 10**9+7 mans = inf ;ans = 0 ;count = 0 ;pro = 1 n,q=map(int,input().split()) STX=[tuple(map(int,input().split())) for i in range(n)] D=[int(input()) for i in range(q)] event=[] for si,ti,xi in STX: event.append((si-xi,0,xi)) event.append((ti-xi,-1,xi)) for di in D: event.append((di,1,di)) event.sort() hq=[]; S=set() ans = [] for time, query, number in event: if query == 0: heapq.heappush(hq,number) S.add(number) elif query == -1: S.remove(number) else: while hq and hq[0] not in S: heapq.heappop(hq) if not hq: ans.append(-1) else: ans.append(hq[0]) print(*ans,sep="\n") ```
output
1
51,109
1
102,219
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,110
1
102,220
"Correct Solution: ``` from bisect import bisect_left,bisect_right n,q=map(int,input().split()) w=[list(map(int,input().split()))[::-1]for _ in range(n)] p=[int(input())for _ in range(q)] w.sort() ans=[-1]*q to=[-1]*q for x,t,s in w: l,r=bisect_left(p,s-x),bisect_left(p,t-x) while l<r: if to[l]==-1: ans[l]=x to[l]=r l+=1 else: l=to[l] print(*ans) ```
output
1
51,110
1
102,221
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,111
1
102,222
"Correct Solution: ``` from heapq import heappop,heappush N,Q=map(int,input().split()) event=[] q=[] for _ in range(N): S,T,X=map(int,input().split()) event.append([S-X,1,X]) event.append([T-X,-1,X]) for i in range(Q): event.append([int(input()),2,i]) stop_set=set() event.sort() q=[] for pos,m,x in event: if m==-1: stop_set.remove(x) elif m==1: #heappushする時点でqはソートされている heappush(q,x) stop_set.add(x) else: #この時点でのstop_setは、i番目の人が遭遇する通行止めの座標 #この時点でのqは今までstopになった座標 while q: #qはソート済なので、q[0]は最小値 それがstop_setから外れている場合、heappopでそれを排除する if q[0] not in stop_set: heappop(q) #q[0]がstop_setから外れてない場合、それ以降のqも外れていないのでbreak else: break if q: print(q[0]) else: print(-1) ```
output
1
51,111
1
102,223
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,112
1
102,224
"Correct Solution: ``` from heapq import heappush, heappop import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) N, Q = map(int, input().split()) STX = [[int(x) for x in input().split()] for _ in range(N)] EVENT = [] for s, t, x in STX: EVENT.append((s-x, 1, x)) EVENT.append((t-x, 0, x)) for i in range(Q): d = int(input()) EVENT.append((d, 2, i)) ans = [-1] * Q EVENT.sort() STOP = set() h = [] for t, op, x in EVENT: if op == 2 and STOP: while h and h[0] not in STOP: heappop(h) ans[x] = h[0] elif op == 1: STOP.add(x) heappush(h, x) elif op == 0: STOP.remove(x) print("\n".join(map(str, ans))) ```
output
1
51,112
1
102,225
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,113
1
102,226
"Correct Solution: ``` import sys from heapq import heappop,heappush input = sys.stdin.readline n,Q = map(int,input().split()) stx = [list(map(int,input().split())) for i in range(n)] dls = [int(input()) for i in range(Q)] event = [] for i in range(n): s,t,x = stx[i] event.append((s-x,1,x)) event.append((t-x,-1,x)) for i in range(Q): d = dls[i] event.append((d,2,i)) event.sort() ans = [-1]*Q s = set() hq = [] for t,q,x in event: if q == 1: s.add(x) heappush(hq,x) elif q == -1: s.remove(x) elif q == 2: while hq and hq[0] not in s: heappop(hq) if hq: ans[x] = hq[0] else: ans[x] = -1 print(*ans,sep="\n") ```
output
1
51,113
1
102,227
Provide a correct Python 3 solution for this coding contest problem. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1
instruction
0
51,114
1
102,228
"Correct Solution: ``` from bisect import bisect_left from operator import itemgetter n, q = map(int, input().split()) stx = [tuple(int(x) for x in input().split()) for _ in range(n)] d = [int(input()) for _ in range(q)] ans = [-1] * q skip = [-1] * q stx.sort(key=itemgetter(2)) for s, t, x in stx: L = bisect_left(d, s-x) R = bisect_left(d, t-x) while L < R: if skip[L] == -1: ans[L] = x skip[L] = R L += 1 else: L = skip[L] for x in ans: print(x) ```
output
1
51,114
1
102,229