message
stringlengths
2
43.5k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
853
107k
cluster
float64
24
24
__index_level_0__
int64
1.71k
214k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program. Input The first line contains integers n and m (1 ≀ n ≀ 2Β·106, 1 ≀ m ≀ 2Β·105) β€” the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≀ ai ≀ n, 1 ≀ li ≀ n - ai + 1). Output Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them. Examples Input 10 4 3 3 3 1 4 1 9 2 Output 2 2 3 Input 1 1 1 1 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(m)] res = [] def inside(s, a): for k in range(a[0], a[0] + a[1]): if s[k-1] == 0: return False return True for i in range(m): cov = [0 for i in range(n)] for j in range(m): if i != j and j not in res: for k in range(a[j][0], a[j][0] + a[j][1]): cov[k - 1] = 1 if inside(cov, a[i]): res.append(i) print(len(res)) for i in res: print(i + 1, end=' ') ```
instruction
0
89,599
24
179,198
No
output
1
89,599
24
179,199
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program. Input The first line contains integers n and m (1 ≀ n ≀ 2Β·106, 1 ≀ m ≀ 2Β·105) β€” the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≀ ai ≀ n, 1 ≀ li ≀ n - ai + 1). Output Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them. Examples Input 10 4 3 3 3 1 4 1 9 2 Output 2 2 3 Input 1 1 1 1 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 def is_inside(a, b): if a[0] > b[0] and a[0]+a[1] < b[0]+b[1]: return True return False n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(m)] res = [] for i in range(m): for j in range(m): if i != j and i not in res and is_inside(a[i], a[j]): res.append(i) print(len(res)) for i in res: print(i + 1, end=' ') ```
instruction
0
89,600
24
179,200
No
output
1
89,600
24
179,201
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program. Input The first line contains integers n and m (1 ≀ n ≀ 2Β·106, 1 ≀ m ≀ 2Β·105) β€” the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≀ ai ≀ n, 1 ≀ li ≀ n - ai + 1). Output Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them. Examples Input 10 4 3 3 3 1 4 1 9 2 Output 2 2 3 Input 1 1 1 1 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 def is_inside(a, b): if a[0] >= b[0] and a[0]+a[1] <= b[0]+b[1]: return True return False n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(m)] res = [] for i in range(m): for j in range(m): if i != j and j not in res and is_inside(a[i], a[j]): res.append(i) print(len(res)) for i in res: print(i + 1, end=' ') ```
instruction
0
89,601
24
179,202
No
output
1
89,601
24
179,203
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program. Input The first line contains integers n and m (1 ≀ n ≀ 2Β·106, 1 ≀ m ≀ 2Β·105) β€” the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≀ ai ≀ n, 1 ≀ li ≀ n - ai + 1). Output Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them. Examples Input 10 4 3 3 3 1 4 1 9 2 Output 2 2 3 Input 1 1 1 1 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 def is_inside(a, b): if a[0] >= b[0] and a[0]+a[1] <= b[0]+b[1]: return True return False n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(m)] res = [] for i in range(m): for j in range(m): if i != j and j not in res and is_inside(a[i], a[j]): res.append(i) break print(len(res)) for i in res: print(i + 1, end=' ') ```
instruction
0
89,602
24
179,204
No
output
1
89,602
24
179,205
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10βŒ‹ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≀ n ≀ 5000, 0 ≀ b ≀ 105) β€” number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≀ ai ≀ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): if item < 10: return item//2 else: bod = (item - item%10)//2 if bod%10 == 0: return bod + item%10 - 10 else: return bod + item%10//2 def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ```
instruction
0
89,755
24
179,510
No
output
1
89,755
24
179,511
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10βŒ‹ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≀ n ≀ 5000, 0 ≀ b ≀ 105) β€” number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≀ ai ≀ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): bod = (item - item%10)//2 if bod%10 == 0: return bod + item%10 - 10 else: return bod + item%10//2 def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ```
instruction
0
89,756
24
179,512
No
output
1
89,756
24
179,513
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10βŒ‹ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≀ n ≀ 5000, 0 ≀ b ≀ 105) β€” number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≀ ai ≀ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): if item < 10: return item//2 else: LD1 = item%10 item1 = item//2 LD2 = item1%10 if LD1 == LD2: return item1 elif LD1 > LD2: return item1-(10-(LD1-LD2)) else: return item1 - (LD2-LD1) def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if item == days[len(days)-1]: used = com(b,item//2) elif b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ```
instruction
0
89,757
24
179,514
No
output
1
89,757
24
179,515
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10βŒ‹ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≀ n ≀ 5000, 0 ≀ b ≀ 105) β€” number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≀ ai ≀ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): if item < 10: return item else: bod = (item - item%10)//2 if bod%10 == 0: return bod + item%10 - 10 else: return bod + item%10//2 def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ```
instruction
0
89,758
24
179,516
No
output
1
89,758
24
179,517
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,166
24
180,332
Tags: brute force, greedy, math, strings Correct Solution: ``` from collections import deque, Counter, OrderedDict from heapq import nsmallest, nlargest, heapify, heappop ,heappush, heapreplace from math import ceil,floor,log,log2,sqrt,gcd,factorial,pow,pi from bisect import bisect_left,bisect_right def binNumber(n,size=4): return bin(n)[2:].zfill(size) def iar(): return list(map(int,input().split())) def ini(): return int(input()) def isp(): return map(int,input().split()) def sti(): return str(input()) def par(a): print(' '.join(list(map(str,a)))) def tdl(outerListSize,innerListSize,defaultValue = 0): return [[defaultValue]*innerListSize for i in range(outerListSize)] def sts(s): s = list(s) s.sort() return ''.join(s) def bis(a, x): i = bisect_left(a, x) if i != len(a) and a[i] == x: return [i,True] else: return [-1,False] class pair: def __init__(self,f,s): self.fi = f self.se = s def __lt__(self,other): return (self.fi,self.se) < (other.fi,other.se) # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code if __name__ == "__main__": n = ini() s1 = sti() s2 = sti() c = [0]*4 p = [[],[],[],[]] for i in range(n): if s1[i] == '0' and s2[i] == '0': c[0] += 1 p[0].append(i+1) if s1[i] == '0' and s2[i] == '1': c[1] += 1 p[1].append(i+1) if s1[i] == '1' and s2[i] == '0': c[2] += 1 p[2].append(i+1) if s1[i] == '1' and s2[i] == '1': c[3] += 1 p[3].append(i+1) for a in range(c[0]+1): for b in range(c[1]+1): d = c[3]+c[1] - n//2 + a e = n//2 - a - b - d #print(e,d) if e > c[2] or d > c[3]: continue if d >= 0 and e >= 0: for i in range(a): print(p[0][i],end=" ") for i in range(b): print(p[1][i],end=" ") for i in range(e): print(p[2][i],end=" ") for i in range(d): print(p[3][i],end=" ") quit() print(-1) ```
output
1
90,166
24
180,333
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,167
24
180,334
Tags: brute force, greedy, math, strings Correct Solution: ``` # map(int, input().split()) # list(map(int, input().split())) # for _ in range(int(input())): n = int(input()) c = list(map(int, list(input()))) a = list(map(int, list(input()))) p = [0,0,0,0] # 00,10,01,11 ind = [[],[],[],[]] for i in range(n): if c[i] and a[i]: p[3] += 1 ind[3].append(i) elif c[i]: p[1] += 1 ind[1].append(i) elif a[i]: p[2] += 1 ind[2].append(i) else: p[0] += 1 ind[0].append(i) first = [0,p[1],0,0] second = [0,0,p[2],0] def trans(i, n): first[i] += n second[i] -= n if p[2] > p[1]: d = p[2] - p[1] first[2] += d second[2] -= d else: d = p[1] - p[2] first[1] -= d second[1] += d d = p[3] while d>0: if first[1]+first[3] > second[2]+second[3]: second[3] += 1 d -= 1 else: first[3] += 1 d -= 1 dif = first[1]+first[3] - (second[2]+second[3]) if dif > 0: if first[2] > 0: trans(2,-1) elif first[1] > 0: trans(1,-1) elif first[3] > 0 and second[1] > 0: trans(3,-1) trans(1,1) else: print(-1) quit() elif dif < 0: if second[1] > 0: trans(1,1) elif second[2] > 0: trans(2,2) elif second[3] > 0 and first[2] > 0: trans(3,1) trans(2,-1) else: print(-1) quit() d = p[0] while d>0: if sum(first) > sum(second): second[0] += 1 d -= 1 else: first[0] += 1 d -= 1 while sum(first) > sum(second): if first[1]>0 and first[2]>0 and second[3]>0: trans(1,-1) trans(2,-1) trans(3,1) elif first[2]>1 and second[3] > 0: trans(2,-1) trans(2,-1) trans(3,1) else: print(-1) quit() while sum(first) < sum(second): if second[1]>0 and second[2]>0 and first[3]>0: trans(1,1) trans(2,1) trans(3,-1) elif second[1]>1 and first[3] > 0: trans(1,1) trans(1,1) trans(3,-1) else: print(-1) quit() ans = [] for i in range(4): for j in range(first[i]): ans.append(ind[i][j]) print(' '.join([str(x+1) for x in ans])) ```
output
1
90,167
24
180,335
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,168
24
180,336
Tags: brute force, greedy, math, strings Correct Solution: ``` n = int(input()) n2 = n // 2 c = input() a = input() cl = [] ac = [] uni = [] par = [] res = [] for i in range(0, n): if c[i] == "1": if a[i]=="0": cl.append(i+1) else: uni.append(i+1) else: if a[i]=="0": par.append(i+1) else: ac.append(i+1) lcl = len(cl) lac = len(ac) lpar = len(par) luni = len(uni) if lcl > n2 or lac > n2 or (lcl == 0 and lac == 0 and luni % 2 == 1): print(-1) else: if luni + lpar - abs(lac - lcl) < 0: print(-1) else: #Π’Ρ‹Ρ€Π°Π²Π½ΠΈΠ²Π°Π΅ΠΌ массивы if luni - abs(lac - lcl) < 0: nmin = lpar if nmin > abs(lac-lcl): nmin = abs(lac-lcl) if lcl < lac: cl = cl + ac[lcl:lcl+nmin:1] lcl = lcl + nmin lpar = lpar-nmin else: if lcl > lac: cl = cl[0:lcl-nmin:1] + par[0:nmin:1] lac = lac + nmin par = par[nmin:] lpar = lpar-nmin x = 0 if lcl < lac: for i in range(0, lac-lcl): cl.append(uni[i]) x = lac-lcl if (luni - abs(lac - lcl)) % 2 == 1: if lac > 0: cl.append(ac[0]) else: cl = cl[1:] cl.append(uni[luni-1]) cl.append(par[lpar-1]) luni = luni-1 lpar = lpar-1 n4 = (luni - abs(lac - lcl)) // 2 for i in range(x, x+n4): cl.append(uni[i]) n5 = lpar // 2 for i in range(0, n5): cl.append(par[i]) print(*cl) ```
output
1
90,168
24
180,337
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,169
24
180,338
Tags: brute force, greedy, math, strings Correct Solution: ``` from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per from heapq import heapify,heappush,heappop,heappushpop input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\r\n') L=lambda:list(R()) P=lambda x:stdout.write(str(x)+'\n') lcm=lambda x,y:(x*y)//gcd(x,y) nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N inv=lambda x:pow(x,N-2,N) sm=lambda x:(x**2+x)//2 N=10**9+7 n=I() g={(0,0):[],(1,0):[],(1,1):[],(0,1):[]} for i,x,y in zip(range(n),S(),S()): g[int(x),int(y)]+=i+1, w=len(g[(0,0)]) x=len(g[(0,1)]) y=len(g[(1,1)]) z=len(g[(1,0)]) for b in range(len(g[(0,1)])+1): for d in range(len(g[(1,1)])+1): c=x+y-(b+2*d) a=n//2-(b+d+c) if w>=a>=0 and z>=c>=0: print(*g[(0,0)][:a]+g[(1,1)][:d]+g[(1,0)][:c]+g[(0,1)][:b]) exit() print(-1) ```
output
1
90,169
24
180,339
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,170
24
180,340
Tags: brute force, greedy, math, strings Correct Solution: ``` import sys import random N = int(input()) C = list(map(int, input())) A = list(map(int, input())) # N = random.randint(20, 40) * 2 # C = [random.randint(0, 1) for i in range(N)] # A = [random.randint(0, 1) for i in range(N)] def build_solution(i, j, x, y): I = (0, 0) J = (0, 1) X = (1, 0) Y = (1, 1) ans = [] for q in range(N): p = (C[q], A[q]) if i and p == I: i -= 1 ans.append(q+1) elif j and p == J: j -= 1 ans.append(q+1) elif x and p == X: x -= 1 ans.append(q+1) elif y and p == Y: y -= 1 ans.append(q+1) return map(str, ans) a = b = c = d = 0 for i in range(N): if C[i] == 0: if A[i] == 0: a += 1 else: b += 1 else: if A[i] == 0: c += 1 else: d += 1 # print(C) # print(A) # print(a, b, c, d, "N/2=", N//2) for i in range(0, a+1): y = - N//2 + i + b + d if y < 0: continue min_j = max(0, N//2 - i - c - y) max_j = min(b + 1, N //2 + 1) # print(i, y, '[', min_j, max_j, ']') for j in range(min_j, max_j): x = N//2 - i - j - y if x < 0: break # print("Check ", i, j, 'x, y:', x, y) if not ((0 <= x <= c) and (0 <= y <= d)): continue # print('SOL', i, j, x, y) sol = build_solution(i, j, x, y) print(' '.join(sol)) exit(0) print(-1) # 1) loop over N # 2) pick best actor on every iteration # 3) try to minimize diff between teams # if len(first) == len(second) and first.score == second.score: # print(' '.join(map(lambda x: str(x+1), first))) # else: # print(-1) # a, b, c, d = 13 5 2 1, N = 20 # i, j, x, y, SUM = 10 # i = 0 # j = 0 ```
output
1
90,170
24
180,341
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,171
24
180,342
Tags: brute force, greedy, math, strings Correct Solution: ``` def find_sol1(result,num_dict): ans_list = [] #print("result",result) for i in range(num_dict['a']+1): for j in range(num_dict['d']+1): if i - j == result: ans_list.append((i,j)) return ans_list def find_sol2(N,num_dict,ans_list): for a,d in ans_list: for i in range(num_dict['b'] + 1): for j in range(num_dict['c'] + 1): if i + j + a + d == N//2: b = i;c = j return a,b,c,d return -1,-1,-1,-1 if __name__ == '__main__': N = int(input().strip()) clown = [int(i) for i in input().strip()] acro = [int(i) for i in input().strip()] num_dict = {'a':0,'b':0,'c':0,'d':0} for i in range(N): if clown[i] == 0 and acro[i] == 0: num_dict['a']+=1 elif clown[i] == 1 and acro[i] == 0: num_dict['b']+=1 elif clown[i] == 0 and acro[i] == 1: num_dict['c']+=1 else: num_dict['d']+=1 a,b,c,d= 0,0,0,0 result = N//2 - num_dict['c'] - num_dict['d'] ans_list = find_sol1(result,num_dict) #print(a,b,c,d) if ans_list == []: print(-1) else: a,b,c,d = find_sol2(N,num_dict,ans_list) if a == -1: print(-1) else: ans = [] for i in range(N): if clown[i] == 0 and acro[i] == 0: if a > 0: ans.append(i + 1) a -= 1 elif clown[i] == 1 and acro[i] == 0: if b > 0: ans.append(i + 1) b -= 1 elif clown[i] == 0 and acro[i] == 1: if c > 0: ans.append(i + 1) c -= 1 else: if d > 0: ans.append(i + 1) d -= 1 print(' '.join(str(i) for i in ans)) ```
output
1
90,171
24
180,343
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,172
24
180,344
Tags: brute force, greedy, math, strings Correct Solution: ``` n = int(input()) s1 = input() s2 = input() w,x,y,z = 0,0,0,0 W,X,Y,Z = [],[],[],[] for i in range(n): s = s1[i] + s2[i] if s == '00': w += 1 W.append(i) elif s == '11': x += 1 X.append(i) elif s =='10': y += 1 Y.append(i) else: z += 1 Z.append(i) can = False res_count = [] for i in range(x+1): for j in range(n//2+1): req1,left1 = j - i, y - j + i if req1 < 0: continue if y < req1 : continue req2 = j - (x - i) left2 = z - req2 if req2 < 0 or z < req2 : continue if req2 + left1 + (x-i) > n//2 or req1 + left2 + i > n//2: continue w_req = n//2 - i - req1-left2 if w_req > w : continue res_count = [i,req1,left2] can = True break if can : break if not can: print(-1) exit(0) res = [] for i in range(res_count[0]): res.append(X[i]+1) for i in range(res_count[1]): res.append(Y[i]+1) for i in range(res_count[2]): res.append(Z[i]+1) for i in range(n//2-len(res)): res.append(W[i]+1) res.sort() print(' '.join(map(str,res))) ```
output
1
90,172
24
180,345
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well.
instruction
0
90,173
24
180,346
Tags: brute force, greedy, math, strings Correct Solution: ``` import sys n=int(input()) s=input() s1=input() a=0 b=0 c=0 d=0 an=[] for i in range(n): if s[i]=='0' and s1[i]=='0': a+=1 elif s[i]=='1' and s1[i]=='0': b+=1 elif s[i]=='0' and s1[i]=='1': c+=1 else: d+=1 x=0 y=0 z=0 w=0 t=0 #print(a,b,c,d) for i in range(a+1): for j in range(d+1): if (n//2)-i-j==c+d-2*j and n//2-i-j>=0 and n//2-i-j<=b+c: x=i y=min(b,n//2-i-j) z=n//2-i-j-y w=j t=1 break if t==0: print(-1) sys.exit() for i in range(n): if s[i]=='0' and s1[i]=='0' and x>0: an.append(i+1) x-=1 elif s[i]=='1' and s1[i]=='0' and y>0: an.append(i+1) y-=1 elif s[i]=='0' and s1[i]=='1' and z>0: an.append(i+1) z-=1 elif s[i]=='1' and s1[i]=='1' and w>0: an.append(i+1) w-=1 print(*an,sep=" ") ```
output
1
90,173
24
180,347
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` import sys N = int(input()) n = N//2 A = input() B = input() C = [(a == '1') * 2 + (b == '1') for a, b in zip(A, B)] w = C.count(0) x = C.count(1) y = C.count(2) z = N - w - x - y Ans = [] for i in range(x + 1): for j in range(y + 1): z1 = (x + z - i - j) if z1 % 2: continue z1 //= 2 if not 0 <= z1 <= z: continue w1 = n - i - j - z1 if not 0 <= w1 <= w: continue cnt = [w1, i, j, z1] ans = [] for k, a, b in zip(range(1, N+1), A, B): if cnt[(a == '1') * 2 + (b == '1')] > 0: cnt[(a == '1') * 2 + (b == '1')] -= 1 Ans.append(k) print(*Ans) sys.exit() print(-1) ```
instruction
0
90,174
24
180,348
Yes
output
1
90,174
24
180,349
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` """ 4 0011 0101 """ def calc(s, n, d): cnts = [len(v) for v in d.values()] half = n // 2 for a in range(0, cnts[0] + 1): for b in range(0, cnts[1] + 1): c = n - 2*a - b - s d = a + s - half if 0 <= c <= cnts[2] and 0 <= d <= cnts[3] and a + b + c + d == half and b + c + 2*d == s: return True, a, b, c, d return False, def main(): n = int(input()) c_arr = list(map(int, list(input()))) a_arr = list(map(int, list(input()))) s = 0 kinds = [(0, 0), (0, 1), (1, 0), (1, 1)] d = {kind: [] for kind in kinds} for i in range(n): if a_arr[i] == 1: s += 1 d[(c_arr[i], a_arr[i])].append(i) result, *params = calc(s, n, d) if not result: print(-1) else: ans = [] for i, kind in enumerate(kinds): for j in range(params[i]): ix = d[kind][j] ans.append(str(ix + 1)) print(' '.join(ans)) if __name__ == '__main__': main() ```
instruction
0
90,175
24
180,350
Yes
output
1
90,175
24
180,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` from sys import stdin, stdout #T = int(input()) #s = input() N = int(input()) #N,K = [int(x) for x in stdin.readline().split()] #arr = [int(x) for x in stdin.readline().split()] clown = input() acro = input() clown = list(clown) acro = list(acro) k1 = 0 k2 = 0 k3 = 0 k4 = 0 for i in range(N): if clown[i]=='0' and acro[i]=='0': k1 += 1 if clown[i]=='0' and acro[i]=='1': k2 += 1 if clown[i]=='1' and acro[i]=='0': k3 += 1 if clown[i]=='1' and acro[i]=='1': k4 += 1 a = 0 b = 0 c = 0 d = 0 target = k1 + k3 - k2 - k4 if target%2==1: print(-1) quit() if target<0: a = 0 d = -target//2 else: a = target//2 d = 0 valid = 0 for i in range(10000): if a<=k1 and d<=k4: #print(a,d) # b+c = N//2 - a - d, find combination of b+c b = N//2 - a - d c = 0 while b>=0 and c>=0: if b<=k2 and c<=k3: # valid !!! #print(a,b,c,d) for j in range(N): if clown[j]=='0' and acro[j]=='0' and a>0: print(j+1,end=' ') a -= 1 if clown[j]=='0' and acro[j]=='1' and b>0: print(j+1,end=' ') b -= 1 if clown[j]=='1' and acro[j]=='0' and c>0: print(j+1,end=' ') c -= 1 if clown[j]=='1' and acro[j]=='1' and d>0: print(j+1,end=' ') d -= 1 quit() b -= 1 c += 1 else: break a += 1 d += 1 print(-1) ```
instruction
0
90,176
24
180,352
Yes
output
1
90,176
24
180,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` """ 4 0011 0101 """ def calc(s, n, d): cnts = [len(v) for v in d.values()] half = n // 2 for a in range(0, cnts[0] + 1): for b in range(0, cnts[1] + 1): c = n - 2*a - b - s d = a + s - half if 0 <= c <= cnts[2] and 0 <= d <= cnts[3] and a + b + c + d == half and b + c + 2*d == s: return True, a, b, c, d return False, def main(): n = int(input()) c_arr = list(map(int, list(input()))) a_arr = list(map(int, list(input()))) s = 0 kinds = [(0, 0), (0, 1), (1, 0), (1, 1)] d = {kind: [] for kind in kinds} for i in range(n): if a_arr[i] == 1: s += 1 d[(c_arr[i], a_arr[i])].append(i) result, *params = calc(s, n, d) if not result: print(-1) else: flags = [False] * n for i, kind in enumerate(kinds): for j in range(params[i]): ix = d[kind][j] flags[ix] = True for i in range(n): if flags[i]: print(i + 1, end=' ') if __name__ == '__main__': main() ```
instruction
0
90,177
24
180,354
Yes
output
1
90,177
24
180,355
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` n = int(input()) p = [[int(i), 0] for i in input()] p00 = [[], []] p01 = [[], []] p11 = [[], []] p10 = [[] ,[]] indx = 0 for i, j in enumerate(list(input())): p[i][1] = int(j) if i>=n//2: indx = 1 if p[i] == [0, 0]: p00[indx].append(i) if p[i] == [0, 1]: p01[indx].append(i) if p[i] == [1, 0]: p10[indx].append(i) if p[i] == [1, 1]: p11[indx].append(i) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if s1 > s2: p00[0], p00[1] = p00[1], p00[0] p10[0], p10[1] = p10[1], p10[0] p01[0], p01[1] = p01[1], p01[0] p11[0], p11[1] = p11[1], p11[0] s1, s2 = s2, s1 for i in range(100000): while s1 <= s2-2 and len(p00[0])>0 and len(p11[1])>0: p00[1].append(p00[0].pop()) p11[0].append(p11[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p01[0])>0 and len(p11[1])>0: p01[1].append(p01[0].pop()) p11[0].append(p11[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p10[0])>0 and len(p11[1])>0: p10[1].append(p10[0].pop()) p11[0].append(p11[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p00[0])>0 and len(p10[1])>0: p00[1].append(p00[0].pop()) p10[0].append(p10[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p00[0])>0 and len(p01[1])>0: p00[1].append(p00[0].pop()) p01[0].append(p01[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) if s1 > s2: p00[0], p00[1] = p00[1], p00[0] p10[0], p10[1] = p10[1], p10[0] p01[0], p01[1] = p01[1], p01[0] p11[0], p11[1] = p11[1], p11[0] s1, s2 = s2, s1 if n==5000: #pass print(s1, s2, len(p00[0]), len(p01[0]), len(p10[0]), len(p11[0]),len(p00[1]), len(p01[1]), len(p10[1]), len(p11[1])) if s1==s2: res = [] res += p00[0] res += p01[0] res += p10[0] res += p11[0] for i in res: print(i + 1, end=' ') print() import sys sys.exit(0) print(-1) ```
instruction
0
90,178
24
180,356
No
output
1
90,178
24
180,357
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` a,b,c=0,0,0 n,s,t=int(input()),input(),input() for i in range(n): if s[i]==t[i]: a+=1 elif s[i]=='1': c+=1 else: b+=1 if a+c<b or a+b<c or (a+c-b)%2==1: print(-1) exit(0) cnt=(a+c-b)/2 for i in range(n): if s[i]==t[i]: if cnt>0: print(i,end=" ") cnt-=1 elif s[i]==1: print(i,end=" ") ```
instruction
0
90,179
24
180,358
No
output
1
90,179
24
180,359
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` n=int(input()) a=input() b=input() init=sum(int(c) for c in b)-sum(int(c) for c in a) mp={-1: [], 0: [], 1: []} for i in range(n): c=int(b[i])-int(a[i]) mp[c]+=[i+1] need=n//2 ans=[] while init<0: if not mp[1]: print(-1) exit() ans+=[mp[1].pop()] need-=1 while init>0: if not mp[-1]: print(-1) exit() ans+=[mp[-1].pop()] need-=1 if need<0: print(-1) exit() if need%2>0: if not mp[0]: print(-1) exit() ans+=[mp[0].pop()] o=min(len(mp[-1]), len(mp[1])) while need>0 and o>0: ans+=[mp[-1].pop(), mp[1].pop()] need-=2 o-=1 if len(mp[0])<need: print(-1) exit() while need>0: ans+=[mp[0].pop()] need-=1 print(*ans) ```
instruction
0
90,180
24
180,360
No
output
1
90,180
24
180,361
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n β€” an even number β€” artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≀ n ≀ 5 000, n is even) β€” the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers β€” the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` n = int(input()) s1 = input() s2 = input() c = s1.count('1') a = s2.count('1') ca = sum(1 for i in range(n) if s1[i] == '1' and s2[i] == '1') c -= ca a -= ca if c > n//2 or a > n//2: print(-1) else: p = lambda x: print(x + 1, end=' ') v = n//2 - a # print(n, n//2, v, ca) for i in range(n): if s1[i] == s2[i]: if v > 0: v -= 1 p(i) elif s2[i] == '1': p(i) ```
instruction
0
90,181
24
180,362
No
output
1
90,181
24
180,363
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,348
24
180,696
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right import time from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict as dd, deque as dq, Counter as dc import math, string start_time = time.time() def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def isInt(s): return '0' <= s[0] <= '9' MOD = 10**9 + 7 """ """ def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def solve(): x = input() N, M = getInts() graph = dd(set) for m in range(M): U, V = getInts() U -= 1 V -= 1 graph[U].add(V) D = [0]*N def bfs(node): queue = dq([]) queue.append((node,0)) visited = set() visited.add(node) while queue: node, level = queue.popleft() for neigh in graph[node]: if neigh not in visited: D[neigh] = level+1 visited.add(neigh) queue.append((neigh,level+1)) bfs(0) visited = set() ans = [0]*N @bootstrap def dfs(node): visited.add(node) ans[node] = D[node] for neigh in graph[node]: if neigh not in visited and D[node] < D[neigh]: yield dfs(neigh) if D[node] < D[neigh]: ans[node] = min(ans[node],ans[neigh]) else: ans[node] = min(ans[node],D[neigh]) yield dfs(0) print(*ans) return for _ in range(getInt()): #print(solve()) solve() #print(time.time()-start_time) ```
output
1
90,348
24
180,697
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,349
24
180,698
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` import math,sys #from itertools import permutations, combinations;import heapq,random; from collections import defaultdict,deque import bisect as bi def yes():print('YES') def no():print('NO') #sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w'); def I():return (int(sys.stdin.readline())) def In():return(map(int,sys.stdin.readline().split())) def Sn():return sys.stdin.readline().strip() #sys.setrecursionlimit(1500) def dict(a): d={} for x in a: if d.get(x,-1)!=-1: d[x]+=1 else: d[x]=1 return d def find_gt(a, x): 'Find leftmost value greater than x' i = bi.bisect_left(a, x) if i != len(a): return i else: return -1 from types import GeneratorType 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 @bootstrap def dfs(d,visit,node,dp,high): visit[node]=True dp[node]=high[node] for x in d[node]: if not visit[x] and (high[node]<high[x]): yield (dfs(d,visit,x,dp,high)) if high[node]<high[x]: dp[node]=min(dp[node],dp[x]) else: dp[node]=min(dp[node],high[x]) yield def main(): try: Extra=Sn() d=defaultdict(list) n,m=In() for i in range(m): a,b=In();d[a].append(b) high=[-1]*(n+1);q=deque([1]);high[1]=0 while q: node=q.popleft() for x in d[node]: if high[x]==-1: high[x]=high[node]+1 q.append(x) dp=[0]*(n+1) # print(high) visit=[False]*(n+1) dfs(d,visit,1,dp,high) print(*dp[1:]) except: pass M = 998244353 P = 1000000007 if __name__ == '__main__': for _ in range(I()):main() #for _ in range(1):main() #End# # ******************* All The Best ******************* # ```
output
1
90,349
24
180,699
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,350
24
180,700
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def mint(): return int(input()) def mints(): return map(int, input().split()) for i in range(mint()): input() n, m = mints() n2 = n*2 e = [[] for i in range(n)] eb = [[] for i in range(n)] for i in range(m): u, v = mints() e[u-1].append(v-1) eb[v-1].append(u-1) q = [0] d = [None]*n d[0] = 0 i = 0 while i < len(q): x = q[i] i += 1 for v in e[x]: if d[v] is None: d[v] = d[x] + 1 q.append(v) idx = [None]*n for i in range(n): idx[i] = (d[i], i) idx.sort() q = [] i = 0 was = [[None]*n for _ in range(2)] ans = [int(2e9)]*n for _, id in idx: dd = d[id] for s in range(2): if was[s][id] is None: was[s][id] = (-1,-1) q.append((id,s)) ans[id] = min(ans[id],dd) while i < len(q): x, s = q[i] i += 1 for v in eb[x]: if d[x] > d[v]: if was[s][v] is None: q.append((v,s)) was[s][v] = (x, s) ans[v] = min(ans[v],dd) elif s == 1: if was[0][v] is None: q.append((v,0)) was[0][v] = (x, s) ans[v] = min(ans[v],dd) print(' '.join(map(str,ans))) ```
output
1
90,350
24
180,701
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,351
24
180,702
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` from queue import Queue class Node: def __init__(self, idx, d = -1): self.d = d self.idx = idx self.par = [] t = int(input()) for _ in range(t): dkk = input() c, eds = tuple([int(x) for x in input().split()]) adl = [[] for i in range(c + 1)] for z in range(eds): u, v = tuple([int(x) for x in input().split()]) adl[u - 1].append(v - 1) nodes = [Node(i) for i in range(c)] q = Queue() q.put(0) ans = [10 ** 9] * c ans[0] = nodes[0].d = 0 def rewind(x, dis): if ans[x] > dis: ans[x] = dis else: return for sdd in nodes[x].par: rewind(sdd, dis) while q.qsize(): front = q.get() # print('fr', front) for e in adl[front]: # print('e', e) if nodes[e].d == -1: q.put(e) nodes[e].d = nodes[front].d + 1 nodes[e].par.append(front) ans[e] = min(ans[e], nodes[e].d) elif nodes[e].d > nodes[front].d: nodes[e].par.append(front) ans[e] = min(ans[e], nodes[e].d) else: rewind(front, nodes[e].d) for e in ans: print(e, end=' ') print() ```
output
1
90,351
24
180,703
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,352
24
180,704
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) from queue import deque from types import GeneratorType 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 def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) @bootstrap def dp(node,nMove2): #return the min d value possible starting from node with at most nMove2 move 2s # print('node:{} nMove2:{}'.format(node,nMove2)) if memo[node][nMove2]==None: ans=d[node] for nex in adj[node]: if d[node]<d[nex]: #nMove doesnt change ans=min(ans, (yield dp(nex,nMove2))) else: #nMove2 increases by 1 if nMove2+1<=1: ans=min(ans, (yield dp(nex,nMove2+1))) memo[node][nMove2]=ans yield memo[node][nMove2] t=int(input()) allAns=[] for _ in range(t): input() # for the empty line n,m=[int(x) for x in input().split()] adj=[[] for _ in range(n+1)] for __ in range(m): u,v=[int(x) for x in input().split()] adj[u].append(v) d=[0 for _ in range(n+1)] visited=[False for _ in range(n+1)] q=deque() #[road,distance from capital] q.append([1,0]) while q: road,distance=q.popleft() if visited[road]==True: continue d[road]=distance visited[road]=True for nex in adj[road]: if visited[nex]==False: q.append([nex,distance+1]) memo=[[None,None] for __ in range(n+1)] ans=[] for i in range(1,n+1): ans.append(dp(i,0)) allAns.append(ans) multiLineArrayOfArraysPrint(allAns) ```
output
1
90,352
24
180,705
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,353
24
180,706
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` # https://codeforces.com/problemset/problem/1472/G from collections import defaultdict, deque import sys input = sys.stdin.readline def get_distances(graph): q = deque() q.append(1) q.append(None) d, distances = 0, {} while len(q) > 1: u = q.popleft() if u is None: d += 1 q.append(None) continue if u in distances: continue distances[u] = d for v in graph[u]: if v not in distances: q.append(v) return distances def bfs(starting_vertex, graph, visited, dists): q = deque() q.append((starting_vertex, None)) q.append((None, None)) d, nodes_at_d = 0, defaultdict(list) while len(q) > 1: u, parent = q.popleft() if u is None: d += 1 q.append((None, None)) continue nodes_at_d[d].append((u, parent)) if u in visited: continue visited.add(u) for v in graph[u]: if v not in visited: q.append((v, u)) else: dists[u] = min(dists[u], dists[v]) while d >= 0: for u, parent in nodes_at_d[d]: if parent is not None: dists[parent] = min(dists[parent], dists[u]) d -= 1 t = int(input()) for _ in range(t): _ = input() n, m = (int(i) for i in input().split(' ')) graph = defaultdict(list) for _ in range(m): u, v = (int(i) for i in input().split(' ')) graph[u].append(v) dists = get_distances(graph) new_graph = defaultdict(list) for u in graph: while graph[u]: v = graph[u].pop() if dists[v] > dists[u]: new_graph[u].append(v) new_graph[u+n].append(v+n) else: new_graph[u].append(v+n) for u in range(1, n + 1): dists[u + n] = dists[u] visited = set() bfs(1, new_graph, visited, dists) for u in range(1, n + 1): print(min(dists[u], dists[u + n]), end=' ') print() ```
output
1
90,353
24
180,707
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,354
24
180,708
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(100000) from collections import deque class Graph(object): """docstring for Graph""" def __init__(self,n,d): # Number of nodes and d is True if directed self.n = n self.graph = [[] for i in range(n)] self.parent = [-1 for i in range(n)] self.directed = d def addEdge(self,x,y): self.graph[x].append(y) if not self.directed: self.graph[y].append(x) def bfs(self, root): # NORMAL BFS queue = [root] queue = deque(queue) vis = [0]*self.n dist = [0]*self.n while len(queue)!=0: element = queue.popleft() vis[element] = 1 for i in self.graph[element]: if vis[i]==0: queue.append(i) self.parent[i] = element dist[i] = dist[element] + 1 vis[i] = 1 return dist def dfs(self, root, minn): # Iterative DFS ans = [i for i in minn] stack=[root] vis=[0]*self.n stack2=[] while len(stack)!=0: # INITIAL TRAVERSAL element = stack.pop() if vis[element]: continue vis[element] = 1 stack2.append(element) for i in self.graph[element]: if vis[i]==0: self.parent[i] = element stack.append(i) # print (stack2) while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question element = stack2.pop() m = minn[element] for i in self.graph[element]: if i!=self.parent[element]: m = min(m, ans[i]) ans[element] = m return ans def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes self.bfs(source) path = [dest] while self.parent[path[-1]]!=-1: path.append(parent[path[-1]]) return path[::-1] def detect_cycle(self): indeg = [0]*self.n for i in range(self.n): for j in self.graph[i]: indeg[j] += 1 q = deque() vis = 0 for i in range(self.n): if indeg[i]==0: q.append(i) while len(q)!=0: e = q.popleft() vis += 1 for i in self.graph[e]: indeg[i] -= 1 if indeg[i]==0: q.append(i) if vis!=self.n: return True return False def reroot(self, root, ans): stack = [root] vis = [0]*n while len(stack)!=0: e = stack[-1] if vis[e]: stack.pop() # Reverse_The_Change() continue vis[e] = 1 for i in graph[e]: if not vis[e]: stack.append(i) if self.parent[e]==-1: continue # Change_The_Answers() def eulertour(self, root): stack=[root] t = [] while len(stack)!=0: element = stack[-1] if vis[element]: t.append(stack.pop()) continue t.append(element) vis[element] = 1 for i in self.graph[element]: if not vis[i]: stack.append(i) return t for nt in range(int(input())): input() n, m = map(int, input().split()) adj = [[] for xy in range(n)] for xy in range(m): u, v = map(lambda x: int(x) - 1, input().split()) adj[u].append(v) dis = [-1] * n dis[0] = 0 que = [0] for i in range(n): u = que[i] for v in adj[u]: if dis[v] == -1: dis[v] = dis[u] + 1 que.append(v) ans = [0] * n for u in sorted([i for i in range(n)], key=lambda x: dis[x], reverse=True): ans[u] = dis[u] for v in adj[u]: if dis[u] >= dis[v]: ans[u] = min(ans[u], dis[v]) else: ans[u] = min(ans[u], ans[v]) print(*ans) ```
output
1
90,354
24
180,709
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0
instruction
0
90,355
24
180,710
Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` from collections import deque 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 @bootstrap def dfs(u): vis[u]=1 for j in adj[u]: if dist[u]>=dist[j]: continue if not vis[j]: yield dfs(j) ans[u]=min(ans[u],ans[j]) yield t=int(input()) for i in range(t): p=input() n,m=map(int,input().split()) adj=[[] for j in range(n+1)] for j in range(m): u,v=map(int,input().split()) adj[u].append(v) dist=[float("inf")]*(n+1) dist[1]=0 q=deque() q.append(1) vis=[0]*(n+1) vis[1]=1 while(q): u=q.popleft() for j in adj[u]: if not vis[j]: dist[j]=1+dist[u] vis[j]=1 q.append(j) ans=[float("inf")]*(n+1) for j in range(1,n+1): vis[j]=0 ans[j]=dist[j] for v in adj[j]: ans[j]=min(ans[j],dist[v]) for i in range(1,n+1): if not vis[i]: dfs(i) ans.pop(0) print(*ans) ```
output
1
90,355
24
180,711
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` import sys from collections import deque input = sys.stdin.buffer.readline for _ in range(int(input())): unko = input() n,m = map(int,input().split()) pre_edge = [[] for i in range(n)] for i in range(m): u,v = map(int,input().split()) pre_edge[u-1].append(v-1) deq = deque([0]) dist = [10**17 for i in range(n)] dist[0] = 0 edge = [[] for i in range(n)] while deq: v = deq.popleft() for nv in pre_edge[v]: if dist[nv] > dist[v] + 1: dist[nv] = dist[v] + 1 edge[v].append(nv) deq.append(nv) #print(dist) dist_sort = [[] for i in range(n)] for i in range(n): dist_sort[dist[i]].append(i) ans = [dist[i] for i in range(n)] for d in range(n-1,-1,-1): for v in dist_sort[d]: for nv in pre_edge[v]: if dist[nv] > dist[v]: ans[v] = min(ans[v],ans[nv]) else: ans[v] = min(dist[nv],ans[v]) print(*ans) ```
instruction
0
90,356
24
180,712
Yes
output
1
90,356
24
180,713
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): def __init__(self, file): self.newlines = 0 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() # -------------------------------------------------------------------- def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def S(): return input().strip() def print_list(l): print(' '.join(map(str, l))) # sys.setrecursionlimit(200000) # import random # from functools import reduce # from functools import lru_cache # from heapq import * # from collections import deque as dq # from math import ceil # import bisect as bs # from collections import Counter # from collections import defaultdict as dc for i in range(N()): input() n, m = RL() dic = [[] for _ in range(n)] for _ in range(m): u, v = RL() dic[u - 1].append(v - 1) dist = [-1] * n dist[0] = 0 now = [0] k = 1 while now: nex = [] for u in now: for v in dic[u]: if dist[v] == -1: dist[v] = k nex.append(v) now = nex k += 1 deep = sorted([i for i in range(n)], key=lambda x:dist[x], reverse=True) res = [n] * n for u in deep: res[u] = dist[u] for v in dic[u]: t = dist[v] if dist[v] <= dist[u] else res[v] if t < res[u]: res[u] = t print_list(res) ```
instruction
0
90,357
24
180,714
Yes
output
1
90,357
24
180,715
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import heapq INF=10**9 def Dijkstra(graph, start): dist=[INF]*len(graph) parent=[INF]*len(graph) queue=[(0, start)] while queue: path_len, v=heapq.heappop(queue) if dist[v]==INF: dist[v]=path_len for w in graph[v]: if dist[w[0]]==INF: parent[w[0]]=v heapq.heappush(queue, (dist[v]+w[1], w[0])) return (dist,parent) t=int(input()) for _ in range(t): input() n,m=map(int,input().split()) graph=[] for i in range(n): graph.append([]) edges=[] for i in range(m): x,y=map(int,input().split()) graph[x-1].append([y-1,1]) edges.append([x-1,y-1]) dist,parent=Dijkstra(graph,0) visited=set() mindist=[INF]*n for i in range(n): mindist[i]=dist[i] for j in graph[i]: mindist[i]=min(mindist[i],dist[j[0]]) graph2=[] for i in range(n): graph2.append([]) edges2=[] for edge in edges: x=edge[0] y=edge[1] if dist[y]>dist[x]: graph2[x].append(y) edges2.append([x,y]) vertices=[] for i in range(n): vertices.append([dist[i],i]) vertices.sort() vertices.reverse() for i in range(n): index=vertices[i][1] for j in graph2[index]: mindist[index]=min(mindist[index],mindist[j]) for i in range(n): mindist[i]=str(mindist[i]) print(' '.join(mindist)) ```
instruction
0
90,358
24
180,716
Yes
output
1
90,358
24
180,717
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` import sys input = sys.stdin.readline from collections import deque class Graph: def __init__(self, N, M=False): self.V = N if M: self.E = M self.edge = [[] for _ in range(self.V)] self.visited = [False]*self.V def add_edges(self, ind=1, bi=False): self.edges = [0]*self.E for i in range(self.E): a,b = map(int, input().split()) a -= ind; b -= ind self.edge[a].append(b) self.edges[i] = (a,b) if bi: self.edge[b].append(a) def add_edge(self, a, b, bi=False): self.edge[a].append(b) if bi: self.edge[b].append(a) def bfs(self, start): d = deque([start]) self.min_cost = [-1]*self.V; self.min_cost[start]=0 while len(d)>0: v = d.popleft() for w in self.edge[v]: if self.min_cost[w]==-1: self.min_cost[w]=self.min_cost[v]+1 d.append(w) return def dfs(self, start, cost, N): stack = deque([start]) self.visited[start] = True ans[start] = min(ans[start], cost) while stack: v = stack.pop() for u in self.edge[v]: if self.visited[u]: continue stack.append(u) self.visited[u] = True ans[u%N] = min(ans[u%N], cost) T = int(input()) for t in range(T): input() N, M = map(int, input().split()) G = Graph(N,M) G.add_edges(ind=1, bi=False) G.bfs(0) costs = [] for i,cos in enumerate(G.min_cost): costs.append((cos,i)) costs.sort() G2 = Graph(N*2) for a,b in G.edges: if G.min_cost[b]>G.min_cost[a]: G2.add_edge(b,a); G2.add_edge(N+b,N+a) else: G2.add_edge(b,a+N) ans = [N]*N for cos,i in costs: G2.dfs(i, cos, N) print(*ans, sep=' ') ```
instruction
0
90,359
24
180,718
Yes
output
1
90,359
24
180,719
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` for _ in range(int(input())): input() n, m = list(map(int,input().split())) q = [[int(i) for i in input().split()] for j in range(m)] tree = {i: [] for i in range(1, n+1)} rTree = {i: [] for i in range(1, n+1)} for i in q: tree[i[0]].append(i[1]) rTree[i[1]].append(i[0]) weight = {i: n for i in range(1, n+1)} weight[1] = 0 r = [1] pas = set() while r!= []: i = r.pop() if i not in pas: pas.add(i) for j in tree[i]: r.append(j) weight[j] = min(weight[j], weight[i]+1) print(tree) tree = weight.copy() print(tree) r = [1] t= 1 pas = set() while r!= []: i = r.pop() if i not in pas: pas.add(i) for j in rTree[i]: if j!= 1: r.append(j) if tree[j]> tree[i]: if t == 1: weight[j] = weight[i] else: weight[j] = tree[i] elif t == 1: weight[j] = weight[i] t-= 1 for i in range(1,n+1): print(weight[i], end = " ") print() ```
instruction
0
90,360
24
180,720
No
output
1
90,360
24
180,721
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` from collections import defaultdict as dd,deque as dq import sys import bisect input=sys.stdin.readline t=int(input()) inf=10**6 def bfs(dis,d,n): vis=[0]*(n+1) q=dq([1]) dis[1]=0 while q: u=q.pop() val=dis[u] for i in d[u]: if(dis[i]>val+1): dis[i]=val+1 q.append(i) while t: d=dd(list) rd=dd(list) _=input().split() n,m=map(int,input().split()) dis=[inf]*(n+1) dis1=[inf]*(n+1) for i in range(m): u,v=map(int,input().split()) d[u].append(v) rd[v].append(u) bfs(dis,d,n) bfs(dis1,rd,n) res=[0]*(n+1) #print(*dis) #print(*dis1) for i in range(1,n+1): res[i]=dis[i] for j in d[i]: #print(i,j) if(dis1[j]-1<dis[j] and dis[j]>dis[i]): res[i]=dis1[j]-1 res[i]=min(res[i],dis[j]) res[i]=max(res[i],0) print(res[i],end=" ") print() t-=1 ```
instruction
0
90,361
24
180,722
No
output
1
90,361
24
180,723
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` import sys from collections import deque as dq input = sys.stdin.readline for _ in range(int(input())): input() n, m = map(int, input().split()) e = [[] for _ in range(n + 1)] re = [[] for _ in range(n + 1)] for _ in range(m): u, v = map(int, input().split()) e[u].append(v) re[v].append(u) Q = dq([1]) d = [n] * (n + 1) d[1] = 0 while len(Q): x = Q.popleft() for y in e[x]: if d[y] > d[x] + 1: d[y] = d[x] + 1 Q.append(y) dp = [d[: ] for _ in range(2)] vis = [0] * (n + 1) s = [x for _, x in sorted([(d[i], i) for i in range(n)], reverse = True)] #print(s) while len(s): x = s.pop() for y in re[x]: if vis[y]: continue if d[y] >= d[x] and dp[1][y] > dp[0][x]: dp[1][y] = dp[0][x] s.append(y) vis[y] = 1 if d[y] < d[x]: if dp[1][y] > dp[1][x]: dp[1][y] = dp[1][x] if dp[0][y] > dp[0][x]: dp[0][y] = dp[0][x] s.append(y) vis[y] = 1 #print(s, dp, x) res = [min(dp[0][i], dp[1][i]) for i in range(1, n + 1)] print(*res) ```
instruction
0
90,362
24
180,724
No
output
1
90,362
24
180,725
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 Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1. Before the trip, Polycarp for each city found out the value of d_i β€” the shortest distance from the capital (the 1-st city) to the i-th city. Polycarp begins his journey in the city with number s and, being in the i-th city, chooses one of the following actions: 1. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i < d_j; 2. Travel from the i-th city to the j-th city if there is a road from the i-th city to the j-th and d_i β‰₯ d_j; 3. Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp no more than once can take the second action from the list. in other words, he can perform the second action 0 or 1 time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. <image> For example, if n = 6 and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): * 2 β†’ 5 β†’ 1 β†’ 2 β†’ 5; * 3 β†’ 6 β†’ 2; * 1 β†’ 3 β†’ 6 β†’ 2 β†’ 5. Polycarp wants for each starting city i to find out how close he can get to the capital. More formally: he wants to find the minimal value of d_j that Polycarp can get from the city i to the city j according to the rules described above. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers n (2 ≀ n ≀ 2 β‹… 10^5) and m (1 ≀ m ≀ 2 β‹… 10^5) β€” number of cities and roads, respectively. This is followed by m lines describing the roads. Each road is characterized by two integers u and v (1 ≀ u, v ≀ n, u β‰  v) β€” the numbers of cities connected by a one-way road. It is guaranteed that the sums of n and m over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that for each pair of different cities (u, v) there is at most one road from u to v (but a pair of roads from u to v and from v to u β€” is valid). It is guaranteed that there is a path from the capital to all cities. Output For each test case, on a separate line output n numbers, the i-th of which is equal to the minimum possible distance from the capital to the city where Polycarp ended his journey. Example Input 3 6 7 1 2 1 3 2 5 2 4 5 1 3 6 6 2 2 2 1 2 2 1 6 8 1 2 1 5 2 6 6 1 2 3 3 4 4 2 5 4 Output 0 0 1 2 0 1 0 0 0 0 2 1 1 0 Submitted Solution: ``` import sys input = sys.stdin.readline from collections import * def bfs(): q = deque([0]) dist = [-1]*n dist[0] = 0 while q: v = q.popleft() for nv in G[v]: if dist[nv]==-1: dist[nv] = dist[v]+1 q.append(nv) return dist for _ in range(int(input())): input() n, m = map(int, input().split()) G = [[] for _ in range(n)] edges = [] for _ in range(m): u, v = map(int, input().split()) G[u-1].append(v-1) edges.append((u-1, v-1)) dist = bfs() m = [dist[v] for v in range(n)] for v in range(n): for nv in G[v]: m[v] = min(m[v], dist[nv]) ins = [0]*n outs = defaultdict(list) for u, v in edges: if dist[u]<dist[v]: ins[v] += 1 outs[u].append(v) q = deque([v for v in range(n)]) order = [] while q: v = q.popleft() order.append(v) for nv in outs[v]: ins[nv] -= 1 if ins[nv]==0: q.append(nv) for v in order[::-1]: for nv in outs[v]: m[v] = min(m[v], m[nv]) print(*m) ```
instruction
0
90,363
24
180,726
No
output
1
90,363
24
180,727
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,435
24
180,870
Tags: graphs, implementation Correct Solution: ``` from collections import Counter n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): x, y = map(int, input().split()) g[x - 1].append(y - 1) g[y - 1].append(x - 1) bus = ([2] * (n - 2)) + ([1] * 2) star = [1] * (n - 1) + [n - 1] lns = [len(lst) for lst in g] if lns == [2] * n: print("ring topology") elif Counter(lns) == Counter(bus): print("bus topology") elif Counter(lns) == Counter(star): print("star topology") else: print("unknown topology") ```
output
1
90,435
24
180,871
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,436
24
180,872
Tags: graphs, implementation Correct Solution: ``` from collections import defaultdict I = lambda: map(int, input().split()) degrees = defaultdict(int) n, m = I() for _ in range(m): u, v = I() degrees[u] += 1 degrees[v] += 1 values = set(degrees.values()) answer = 'unknown' if values == {2}: answer = 'ring' elif values == {1, 2}: answer = 'bus' elif values == {1, m}: answer = 'star' print(answer, 'topology') ```
output
1
90,436
24
180,873
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,437
24
180,874
Tags: graphs, implementation Correct Solution: ``` n, m = map(int, input().split()) graph = { i: [] for i in range(1, n+1) } for i in range(m): start, end = map(int, input().split()) graph[start].append(end) graph[end].append(start) length_array = [] for i in graph: length_array.append(len(graph[i])) if min(length_array) == max(length_array) and max(length_array) == 2: print('ring topology') elif length_array.count(1) == 2 and length_array.count(2) == n - 2: print('bus topology') elif max(length_array) == m and m == n - 1: print('star topology') else: print('unknown topology') ```
output
1
90,437
24
180,875
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,438
24
180,876
Tags: graphs, implementation Correct Solution: ``` n, m = [int(i) for i in input().split()] s = [] for i in range(n + 1): s.append([]) for i in range(m): x, y = [int(i) for i in input().split()] s[x].append(y) s[y].append(x) sbool = [False] * (n + 1) v2 = 0 v1 = 0 other = 0 def dfs(new): global sbool, s, v2, v1, other sbool[new] = True if len(s[new]) == 1: v1 += 1 elif len(s[new]) == 2: v2 += 1 else: other += 1 for i in range(1, n + 1): dfs(i) if v1 == 2 and v2 == n - 2: print('bus topology') elif v1 == n - 1 and other == 1: print('star topology') elif v2 == n: print('ring topology') else: print('unknown topology') ```
output
1
90,438
24
180,877
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,439
24
180,878
Tags: graphs, implementation Correct Solution: ``` n, m = [int(i) for i in input().split()] graf = [[] for i in range(n + 1)] for i in range(m): k1, k2 = [int(i) for i in input().split()] graf[k1].append(k2) graf[k2].append(k1) seks = [0, 0, 0] for i in range(1, n + 1): if len(graf[i]) == 1 or len(graf[i]) == 2: seks[len(graf[i])] += 1 else: seks[0] += 1 if seks[0] == 0 and seks[1] == 2: print('bus topology') elif seks[0] == seks[1] == 0: print('ring topology') elif seks[0] == 1 and seks[2] == 0: print('star topology') else: print('unknown topology') ```
output
1
90,439
24
180,879
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,440
24
180,880
Tags: graphs, implementation Correct Solution: ``` n, m = map(int, input().split()) d = dict() maxi = 0 maxv = 0 for _ in range(m): a, b = map(int, input().split()) if a - 1 in d: d[a - 1] += 1 else: d[a - 1] = 1 if b - 1 in d: d[b - 1] += 1 else: d[b - 1] = 1 if d[a - 1] > maxv: maxv = d[a - 1] maxi = a - 1 if d[b - 1] > maxv: maxv = d[b - 1] maxi = b - 1 if m + 1 == n: if maxv == m: print('star topology') elif maxv == 2: print('bus topology') else: print('unknown topology') elif m == n: if maxv == 2: print('ring topology') else: print('unknown topology') else: print('unknown topology') ```
output
1
90,440
24
180,881
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,441
24
180,882
Tags: graphs, implementation Correct Solution: ``` n,m = map(int,input().split()) v = [] def chek_star(v): t = 0 for i in v: if i != 1: t+=1 if t == 1: return True return False for i in range(n): v.append(0) for i in range(m): t1,t2 = map(int,input().split()) v[t1-1]+=1 v[t2-1]+=1 if max(v) == 2 and min(v) == 2: print("ring topology") elif set(v) == set([1,2]): print("bus topology") elif set(v) == set([1,max(v)]) and chek_star(v): print("star topology") else: print("unknown topology") ```
output
1
90,441
24
180,883
Provide tags and a correct Python 3 solution for this coding contest problem. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology
instruction
0
90,442
24
180,884
Tags: graphs, implementation Correct Solution: ``` # brute force baby from sys import stdin node,edge = map(int,input().split()) capt = [0]*node for l in stdin.readlines(): a,b = map(int,l.split()) capt[a-1] +=1; capt[b-1] += 1 if capt.count(1) == node - 1: print('star topology') elif capt.count(2) == node: print('ring topology') elif capt.count(1) == 2 and capt.count(2) == node - 2: print('bus topology') else: print('unknown topology') ```
output
1
90,442
24
180,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology Submitted Solution: ``` from functools import reduce def add(a,b): return a+b n,m = [int(x) for x in input().split()] neigh = [[] for x in range(n)] for i in range(m): x,y = [int(a) for a in input().split()] neigh[x-1].append(y) neigh[y-1].append(x) oneneigh, twoneigh, nneigh = 0,0,0 for i in neigh: if len(i) == 1: oneneigh += 1 elif len(i) == 2: twoneigh += 1 else: nneigh += 1 if twoneigh == n: print('ring topology') elif oneneigh == 2 and twoneigh == n-2: print('bus topology') elif nneigh == 1 and oneneigh == m: print('star topology') else: print('unknown topology') ```
instruction
0
90,443
24
180,886
Yes
output
1
90,443
24
180,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices. Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node. Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. <image> (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. Input The first line contains two space-separated integers n and m (4 ≀ n ≀ 105; 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself. Output In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes). Examples Input 4 3 1 2 2 3 3 4 Output bus topology Input 4 4 1 2 2 3 3 4 4 1 Output ring topology Input 4 3 1 2 1 3 1 4 Output star topology Input 4 4 1 2 2 3 3 1 1 4 Output unknown topology Submitted Solution: ``` n,m = map(int, input().split()) db = [[] for i in range(n)] for i in range(m): x,y = map(int, input().split()) db[x-1].append(y) db[y-1].append(x) one = 0 two = 0 mx = 0 for i in range(n): ln = len(db[i]) if ln == 1: one += 1 elif ln == 2: two += 1 mx = max(mx,ln) if one == 2 and two == n-2: print("bus topology") elif two == n: print("ring topology") elif one == n-1 and mx == n-1: print("star topology") else: print("unknown topology") ```
instruction
0
90,444
24
180,888
Yes
output
1
90,444
24
180,889