message
stringlengths
2
45.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
254
108k
cluster
float64
3
3
__index_level_0__
int64
508
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi. Mr. Kitayuta has just arrived at island 0. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process: * First, he will jump from island 0 to island d. * After that, he will continue jumping according to the following rule. Let l be the length of the previous jump, that is, if his previous jump was from island prev to island cur, let l = cur - prev. He will perform a jump of length l - 1, l or l + 1 to the east. That is, he will jump to island (cur + l - 1), (cur + l) or (cur + l + 1) (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length 0 when l = 1. If there is no valid destination, he will stop jumping. Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect. Input The first line of the input contains two space-separated integers n and d (1 ≀ n, d ≀ 30000), denoting the number of the gems in the Shuseki Islands and the length of the Mr. Kitayuta's first jump, respectively. The next n lines describe the location of the gems. The i-th of them (1 ≀ i ≀ n) contains a integer pi (d ≀ p1 ≀ p2 ≀ ... ≀ pn ≀ 30000), denoting the number of the island that contains the i-th gem. Output Print the maximum number of gems that Mr. Kitayuta can collect. Examples Input 4 10 10 21 27 27 Output 3 Input 8 8 9 19 28 36 45 55 66 78 Output 6 Input 13 7 8 8 9 16 17 17 18 21 23 24 24 26 30 Output 4 Note In the first sample, the optimal route is 0 β†’ 10 (+1 gem) β†’ 19 β†’ 27 (+2 gems) β†’ ... In the second sample, the optimal route is 0 β†’ 8 β†’ 15 β†’ 21 β†’ 28 (+1 gem) β†’ 36 (+1 gem) β†’ 45 (+1 gem) β†’ 55 (+1 gem) β†’ 66 (+1 gem) β†’ 78 (+1 gem) β†’ ... In the third sample, the optimal route is 0 β†’ 7 β†’ 13 β†’ 18 (+1 gem) β†’ 24 (+2 gems) β†’ 30 (+1 gem) β†’ ... Submitted Solution: ``` import bisect import os, sys, atexit,threading from io import BytesIO, StringIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline _OUTPUT_BUFFER = StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) def calculate(i,l): global maxGem,offset if l==0 or l<offset or i>maxGem : return 0 # print (i, l,offset) if dp[i][l-offset]==-1: answer = 0 answer+=gems[i] answer+=max(calculate(i+l-1,l-1),calculate(i+l,l),calculate(i+l+1,l+1)) dp[i][l-offset] = answer return dp[i][l-offset] def solve(): n,d = map(int,input().split()) global maxGem, offset for _ in range(n): gem = int(input()) gems[gem]+=1 maxGem = max(maxGem,gem) if d<=maxGem: totalDpLength = d+245-max(d-245,0)+1 offset = max(d-245,0) for _ in range(maxGem+1): dp.append([-1]*totalDpLength) for x in range(maxGem+1,d-1,-1): for y in range(totalDpLength+offset-1,offset-1,-1): # print ("x,y ",x,y) calculate(x,y) print (dp[d][d]) else: print (0) try: dp = [] gems = [0]*30001 maxGem = 0 offset = 0 solve() except Exception as e: print (e) ```
instruction
0
14,595
3
29,190
No
output
1
14,595
3
29,191
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,610
3
29,220
Tags: data structures, greedy, sortings Correct Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = i + 1 heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass for n in self.result: if n is None: return "No" answer = " ".join([str(n) for n in self.result]) return "Yes\n" + answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return sys.stdin.readline() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 20000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string print(calculate()) ```
output
1
14,610
3
29,221
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,611
3
29,222
Tags: data structures, greedy, sortings Correct Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = i + 1 heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass answer = "" for (i, n) in enumerate(self.result): if n is None: return "No" answer += (" " if i > 0 else "") + str(n) return "Yes\n" + answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return input() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 50000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string print(calculate()) ```
output
1
14,611
3
29,223
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,612
3
29,224
Tags: data structures, greedy, sortings Correct Solution: ``` import heapq n,m=[int(x) for x in input().split()] l1,r1=[int(x) for x in input().split()] req=[] start=[] for i in range(n-1): l2,r2=[int(x) for x in input().split()] req.append((l2-r1,r2-l1,i)) l1,r1=l2,r2 have=[int(x) for x in input().split()] for i in range(m): have[i]=(have[i],i) have.sort() req.sort() now=[] i=0 j=0 slen=len(req) hlen=len(have) ans=[0]*(n-1) while j<hlen: if i<slen and req[i][0]<=have[j][0]: heapq.heappush(now,(req[i][1],req[i][2])) i+=1 else: try: x=heapq.heappop(now) except IndexError: j+=1 continue if x[0]<have[j][0]: break else: ans[x[1]]=have[j][1] j+=1 if i<slen or len(now)!=0 or j<hlen: print('No') else: print('Yes') print(' '.join([str(x+1) for x in ans])) ```
output
1
14,612
3
29,225
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,613
3
29,226
Tags: data structures, greedy, sortings Correct Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [()]*self.gn prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps[i] = (min, max, i) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = i + 1 heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass answer = "" for (i, n) in enumerate(self.result): if n is None: return "No" answer += (" " if i > 0 else "") + str(n) return "Yes\n" + answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return input() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 100000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string print(calculate()) ```
output
1
14,613
3
29,227
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,614
3
29,228
Tags: data structures, greedy, sortings Correct Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = i + 1 heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass for n in self.result: if n is None: return "No" answer = " ".join([str(n) for n in self.result]) return "Yes\n" + answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return input() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 20000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string print(calculate()) ```
output
1
14,614
3
29,229
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,615
3
29,230
Tags: data structures, greedy, sortings Correct Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = str(i + 1) heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass for n in self.result: if n is None: return "No" answer = "Yes\n" answer += " ".join(self.result) return answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return sys.stdin.readline() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 10000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string sys.stdout.write(calculate()) ```
output
1
14,615
3
29,231
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,616
3
29,232
Tags: data structures, greedy, sortings Correct Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard modules import unittest import sys import re # Additional modules import bisect ############################################################################### # Fastlist Class ############################################################################### class Fastlist(object): """ Fastlist representation """ def __init__(self, l=[], load=5000, sorted=0): self._load = load self._sorted = sorted self._lists = [] self._starts = [] self._mins = [] self._insert_list() self._irev = 0 self.extend(l) def _index_location(self, index): if len(self._lists[0]) == 0: raise IndexError("List index out of range") if index == 0: return (0, 0) if index == -1: return (len(self._lists) - 1, len(self._lists[-1]) - 1) if self._sorted: raise RuntimeError("No index access to the sorted list, exc 0, -1") length = len(self) if index < 0: index = length + index if index >= length: raise IndexError("List index out of range") il = bisect.bisect_right(self._starts, index) - 1 return (il, index - self._starts[il]) def _insert_list(self, il=None): if il is None: il = len(self._lists) self._lists.insert(il, []) if self._sorted: if il == 0: self._mins.insert(il, None) else: self._mins.insert(il, self._lists[il-1][-1]) else: if il == 0: self._starts.insert(il, 0) else: start = self._starts[il-1] + len(self._lists[il-1]) self._starts.insert(il, start) def _del_list(self, il): del self._lists[il] if self._sorted: del self._mins[il] else: del self._starts[il] def _rebalance(self, il): illen = len(self._lists[il]) if illen >= self._load * 2: self._insert_list(il) self._even_lists(il) if illen <= self._load * 0.2: if il != 0: self._even_lists(il-1) elif len(self._lists) > 1: self._even_lists(il) def _even_lists(self, il): tot = len(self._lists[il]) + len(self._lists[il+1]) if tot < self._load * 1: self._lists[il] += self._lists[il+1] self._del_list(il+1) if self._sorted: self._mins[il] = self._lists[il][0] else: half = tot//2 ltot = self._lists[il] + self._lists[il+1] self._lists[il] = ltot[:half] self._lists[il+1] = ltot[half:] if self._sorted: self._mins[il] = self._lists[il][0] self._mins[il+1] = self._lists[il+1][0] else: self._starts[il+1] = self._starts[il] + len(self._lists[il]) def _obj_location(self, obj, l=0): if not self._sorted: raise RuntimeError("No by value access to an unserted list") il = 0 if len(self._mins) > 1 and obj > self._mins[0]: if l: il = bisect.bisect_left(self._mins, obj) - 1 else: il = bisect.bisect_right(self._mins, obj) - 1 if l: ii = bisect.bisect_left(self._lists[il], obj) else: ii = bisect.bisect_right(self._lists[il], obj) if ii == len(self._lists[il]) and il != len(self._lists) - 1: ii = 0 il += 1 return (il, ii) def insert(self, index, obj): (il, ii) = self._index_location(index) self._lists[il].insert(ii, obj) for j in range(il + 1, len(self._starts)): self._starts[j] += 1 self._rebalance(il) def append(self, obj): if len(self._lists[-1]) >= self._load: self._insert_list() self._lists[-1].append(obj) if self._sorted and self._mins[0] is None: self._mins[0] = self._lists[0][0] def extend(self, iter): for n in iter: self.append(n) def pop(self, index=None): if index is None: index = -1 (il, ii) = self._index_location(index) item = self._lists[il].pop(ii) if self._sorted: if ii == 0 and len(self._lists[il]) > 0: self._mins[il] = self._lists[il][0] else: for j in range(il + 1, len(self._starts)): self._starts[j] -= 1 self._rebalance(il) return item def clear(self): self._lists.clear() self._starts.clear() self._mins.clear() self._insert_list() def as_list(self): return sum(self._lists, []) def insort(self, obj, l=0): (il, ii) = self._obj_location(obj, l) self._lists[il].insert(ii, obj) if ii == 0: self._mins[il] = obj self._rebalance(il) def add(self, obj): if self._sorted: self.insort(obj) else: self.append(obj) def insort_left(self, obj): self.insort(obj, l=1) def lower_bound(self, obj): (self._il, self._ii) = self._obj_location(obj, l=1) return self def upper_bound(self, obj): (self._il, self._ii) = self._obj_location(obj) return self def __str__(self): return str(self.as_list()) def __setitem__(self, index, obj): if isinstance(index, int): (il, ii) = self._index_location(index) self._lists[il][ii] = obj elif isinstance(index, slice): raise RuntimeError("Slice assignment is not supported") def __getitem__(self, index): if isinstance(index, int): (il, ii) = self._index_location(index) return self._lists[il][ii] elif isinstance(index, slice): rg = index.indices(len(self)) if rg[0] == 0 and rg[1] == len(self) and rg[2] == 1: return self.as_list() return [self.__getitem__(index) for index in range(*rg)] def __iadd__(self, obj): if self._sorted: [self.insort(n) for n in obj] else: [self.append(n) for n in obj] return self def __delitem__(self, index): if isinstance(index, int): self.pop(index) elif isinstance(index, slice): rg = index.indices(len(self)) [self.__delitem__(rg[0]) for i in range(*rg)] def __len__(self): if self._sorted: return sum([len(l) for l in self._lists]) return self._starts[-1] + len(self._lists[-1]) def __contains__(self, obj): if self._sorted: it = self.lower_bound(obj) return not it.iter_end() and obj == it.iter_getitem() else: for n in self: if obj == n: return True return False def __bool__(self): return len(self._lists[0]) != 0 def __iter__(self): self._il = self._ii = self._irev = 0 return self def __reversed__(self): self._il = len(self._lists) - 1 self._ii = len(self._lists[self._il]) - 1 self._irev = 1 return self def __next__(self): if self._il in (-1, len(self._lists)) or len(self._lists[0]) == 0: raise StopIteration("Iteration stopped") item = self._lists[self._il][self._ii] if not self._irev: self._ii += 1 if self._ii == len(self._lists[self._il]): self._il += 1 self._ii = 0 else: self._ii -= 1 if self._ii == 0: self._il -= 1 self._ii = len(self._lists[self._il]) return item def iter_getitem(self): return self._lists[self._il][self._ii] def iter_end(self): return (self._il == len(self._lists) - 1 and self._ii == len(self._lists[self._il])) def iter_del(self): self.iter_pop() def iter_pop(self): item = self._lists[self._il].pop(self._ii) if self._sorted: if self._ii == 0 and len(self._lists[self._il]) > 0: self._mins[self._il] = self._lists[self._il][0] else: for j in range(self._il + 1, len(self._starts)): self._starts[j] -= 1 self._rebalance(self._il) return item ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.gsrt = args[0] self.asrt = args[1] self.gn = args[2] self.result = [0]*self.gn self.a = Fastlist(self.asrt, load=500, sorted=1) def calculate(self): """ Main calcualtion function of the class """ for i in range(self.gn): g = self.gsrt[i] it = self.a.lower_bound((g[1], 0)) if not it.iter_end(): alb = it.iter_getitem() if alb[0] > g[0]: return "No" self.result[g[2]] = alb[1]+1 it.iter_del() else: return "No" answer = "Yes\n" + " ".join(str(n) for n in self.result) return answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return sys.stdin.readline() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] gaps = [] prevli = [int(s) for s in uinput().split()] for i in range(num[0] - 1): li = [int(s) for s in uinput().split()] min = li[0] - prevli[1] max = li[1] - prevli[0] gaps.append((max, min, i)) prevli = li alist = [(int(s), i) for i, s in enumerate(uinput().split())] # Decoding inputs into a list inputs = [sorted(gaps), sorted(alist), num[0]-1] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[(3, 1, 1), (5, 2, 2), (7, 3, 0)], [(3, 2), (4, 0), (5, 1), (8, 3)], 3]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 200000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): test += str(x) + " " + str(x + i + 1) + "\n" x += 2 * (i + 1) for i in reversed(range(size)): test += str(i) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[(1, 3, 1), (2, 5, 2), (3, 7, 0)], [(3, 2), (4, 0), (5, 1), (8, 3)], 3]) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gsrt[0], (1, 3, 1)) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string sys.stdout.write(calculate()) ```
output
1
14,616
3
29,233
Provide tags and a correct Python 3 solution for this coding contest problem. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
instruction
0
14,617
3
29,234
Tags: data structures, greedy, sortings Correct Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = i + 1 heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass for n in self.result: if n is None: return "No" answer = " ".join([str(n) for n in self.result]) return "Yes\n" + answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return sys.stdin.readline() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 20000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string sys.stdout.write(calculate() + "\n") ```
output
1
14,617
3
29,235
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist. Submitted Solution: ``` # Standard libraries import unittest import sys import re # Additional libraries import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [n[0] for n in self.gsrt] self.result = [None]*self.gn self.heap = [] def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = i + 1 heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass for n in self.result: if n is None: return "No" answer = " ".join([str(n) for n in self.result]) return "Yes\n" + answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return input() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 20000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string print(calculate()) ```
instruction
0
14,618
3
29,236
Yes
output
1
14,618
3
29,237
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist. Submitted Solution: ``` #!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input The first line contains integers n and m - the number of islands and bridges. Next n lines each contain two integers li and ri - the coordinates of the island endpoints. The last line contains m integer numbers a1..am - the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes) , otherwise print in the first line "Yes" (without the quotes), and in the second line print n-1 numbers b1, bn-1, which mean that between islands i and i+1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case """ # Standard libraries import unittest import sys import re # Additional libraries import bisect import heapq ############################################################################### # Fug Class ############################################################################### class Fug: """ Fug representation """ def __init__(self, args): """ Default constructor """ self.list = args[0] self.alist = args[1] self.gn = len(self.list) - 1 # Sorted list of bridges self.asrt = sorted((n, i) for i, n in enumerate(self.alist)) # List of gaps between islands self.gaps = [] prevli = self.list[0] for i in range(self.gn): li = self.list[i+1] min = li[0] - prevli[1] max = li[1] - prevli[0] self.gaps.append((min, max, i)) prevli = li # Sorted list of gaps between islands self.gsrt = sorted(self.gaps) self.gmin = [] self.result = [] self.heap = [] for n in self.gsrt: self.gmin.append(n[0]) self.result.append(None) def iterate(self): j = 0 for (b, i) in self.asrt: # Traverse gmin array while j < self.gn and self.gmin[j] <= b: it = self.gsrt[j] heapq.heappush(self.heap, (it[1], it[0], it[2])) j += 1 # Update result and remove the element from lists if self.heap: (mmax, mmin, mi) = self.heap[0] if mmin <= b and mmax >= b: self.result[mi] = i + 1 heapq.heappop(self.heap) yield def calculate(self): """ Main calcualtion function of the class """ for it in self.iterate(): pass answer = "" for (i, n) in enumerate(self.result): if n is None: return "No" answer += (" " if i > 0 else "") + str(n) return "Yes\n" + answer ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return input() # Getting string inputs. Place all uinput() calls here num = [int(s) for s in uinput().split()] list = [[int(s) for s in uinput().split()] for i in range(num[0])] alist = [int(s) for s in uinput().split()] # Decoding inputs into a list inputs = [list, alist] return inputs def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Fug(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8" self.assertEqual(calculate(test), "Yes\n2 3 1") self.assertEqual( get_inputs(test), [[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) # My tests test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2" self.assertEqual(calculate(test), "Yes\n1 2 5 4") # Other tests test = "2 2\n11 14\n17 18\n2 9" self.assertEqual(calculate(test), "No") # Other tests test = ( "2 1\n1 1\n1000000000000000000 1000000000000000000" + "\n999999999999999999") self.assertEqual(calculate(test), "Yes\n1") test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5") self.assertEqual(calculate(test), "Yes\n1 6 3 2") size = 50000 test = str(size) + " " + str(size) + "\n" x = size*1000 for i in range(size): x += 2 test += str(x) + " " + str(x+1) + "\n" for i in range(size): test += str(2) + " " self.assertEqual(calculate(test)[0], "Y") def test_Fug_class__basic_functions(self): """ Fug class basic functions testing """ # Constructor test d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]]) self.assertEqual(d.list[0][0], 1) self.assertEqual(d.alist[0], 4) # Sort bridges self.assertEqual(d.asrt[0], (3, 2)) # Sort Gaps self.assertEqual(d.gaps[0], (2, 7, 0)) self.assertEqual(d.gsrt[0], (1, 3, 1)) iter = d.iterate() next(iter) self.assertEqual(d.gmin, [1, 2, 2]) self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)]) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string print(calculate()) ```
instruction
0
14,619
3
29,238
Yes
output
1
14,619
3
29,239
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist. Submitted Solution: ``` from sys import stdin import heapq n,m = [int(x) for x in stdin.readline().split()] islands = [] for i in range(n): islands.append([int(x) for x in stdin.readline().split()]) gaps = [] for i in range(n-1): gaps.append((islands[i+1][0]-islands[i][1], islands[i+1][1]-islands[i][0])) bridges = [int(x) for x in stdin.readline().split()] bridges = sorted([(bridges[x],x+1) for x in range(m)]) gaps2 = [] for l,r in gaps: low = 0 high = m-1 while low <= high: mid = (low+high)//2 if bridges[mid][0] < l: low = mid+1 else: high = mid-1 trueL = low low = 0 high = m-1 while low <= high: mid = (low+high)//2 if bridges[mid][0] > r: high = mid-1 else: low = mid+1 trueR = high gaps2.append((trueL,trueR)) gaps2 = [(gaps2[x], x) for x in range(n-1)] gaps2.sort() final = [0 for x in range(n-1)] ind = 0 q = [] valid = True for x in range(m): i2 = bridges[x][1] if ind < n-1: while gaps2[ind][0][0] == x: heapq.heappush(q, (gaps2[ind][0][1], gaps2[ind][1])) ind += 1 if ind >= n-1: break if not q: continue nxt,ind = heapq.heappop(q) if nxt < x: valid = False break else: final[ind] = i2 if 0 in final: valid = False if valid: print('Yes') print(' '.join([str(x) for x in final])) else: print('No') ```
instruction
0
14,620
3
29,240
No
output
1
14,620
3
29,241
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist. Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import time def test(i, island, bridge, n, m): if i == n-1: return [True, []] flag = [False, []] lmax = island[i+1][1] - island[i][0] lmin = island[i+1][0] - island[i][1] for j in range(m): if bridge[j] > 0 and bridge[j] <= lmax and bridge[j] >= lmin: buf = bridge[j] bridge[j] = 0 flag = test(i+1, island, bridge, n, m) if flag[0] == True: flag[1].append(j) break bridge[j] = buf return flag (n, m) = (int(i) for i in input().split()) if m < n-1 : print("No") else: island = [] for i in range(n): island.append([int(i) for i in input().split()]) bridge = [int(i) for i in input().split()] start = time.time() ans = test(0, island, bridge, n, m); if ans[0] == True: print("Yes") for i in range(n-1): print(ans[1][i]+1, end=" ") print() else: print("No") finish = time.time() #print(finish - start) ```
instruction
0
14,621
3
29,242
No
output
1
14,621
3
29,243
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist. Submitted Solution: ``` n, m = (int(x) for x in input().split()) coord, dest, br = [], [], [] for i in range(n): coord.append(tuple(int(x) for x in input().split())) temp = input().split() br = [(int(temp[x]), x + 1) for x in range(len(temp))] coord.sort() for i in range(len(coord) - 1): dest.append((coord[i+1][0] - coord[i][1], coord[i+1][1] - coord[i][0], i)) dest.sort(key = lambda x: (x[1], x[0])) br.sort() def f(dest, br): brIt = len(br) - 1 res = [0 for i in range(len(dest))] for dIt in range(len(dest) - 1, -1, -1): if brIt < 0: print("No") return while not (dest[dIt][0] <= br[brIt][0] <= dest[dIt][1]): brIt -= 1 if brIt < 0: print("No") return res[dest[dIt][2]] = brIt brIt -= 1 print("Yes") print(" ".join(str(x) for x in res)) f(dest, br) ```
instruction
0
14,622
3
29,244
No
output
1
14,622
3
29,245
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. Input The first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got. Output If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. Examples Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 Note In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist. Submitted Solution: ``` islands, nbridges = map(int, input().split(' ')) data = [] for _ in range(islands): data.append(tuple(map(int, input().split(' ')))) bridges = iter(sorted(enumerate(map(int, input().split(' '))), key=lambda x: x[1])) lengths = [] for i in range(islands-1): outer = data[i+1][1] - data[i][0] inner = data[i+1][0] - data[i][1] lengths.append((inner, outer, i)) lengths = sorted(lengths) ans = [] try: for inner, outer, i in lengths: b = next(bridges) while not inner <= b[1] <= outer: b = next(bridges) ans.append((i, b[0])) print('Yes') print(' '.join(str(i[1]+1) for i in sorted(ans))) except StopIteration: print('No') ```
instruction
0
14,623
3
29,246
No
output
1
14,623
3
29,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has m seedlings, and the j-th seedling needs at least kj minutes of sunlight to grow up. Most of the time it's sunny in Sweetland, but sometimes some caramel clouds come, the i-th of which will appear at time moment (minute) li and disappear at time moment ri. Of course, the clouds make shadows, and the seedlings can't grow when there is at least one cloud veiling the sun. Slastyona wants to grow up her muffins as fast as possible. She has exactly C candies, which is the main currency in Sweetland. One can dispel any cloud by paying ci candies. However, in order to comply with Sweetland's Department of Meteorology regulations, one can't dispel more than two clouds. Slastyona hasn't decided yet which of the m seedlings will be planted at the princess' garden, so she needs your help. For each seedling determine the earliest moment it can grow up if Slastyona won't break the law and won't spend more candies than she has. Note that each of the seedlings is considered independently. The seedlings start to grow at time moment 0. Input The first line contains two integers n and C (0 ≀ n ≀ 3Β·105, 0 ≀ C ≀ 109) – the number of caramel clouds and the number of candies Slastyona has. The next n lines contain three integers each: li, ri, ci (0 ≀ li < ri ≀ 109, 0 ≀ ci ≀ 109), describing one caramel cloud. The next line contains single integer m (1 ≀ m ≀ 3Β·105) – the number of seedlings. Each of the seedlings is described with one integer kj (1 ≀ kj ≀ 109) – the required number of sunny minutes. Output For each seedling print one integer – the minimum minute Slastyona can grow it up. Examples Input 3 5 1 7 1 1 6 2 1 7 1 3 7 2 5 Output 12 7 10 Input 3 15 1 4 17 2 8 6 4 8 9 2 5 1 Output 8 1 Input 2 10 3 7 9 10 90 10 2 10 100 Output 10 104 Note Consider the first example. For each k it is optimal to dispel clouds 1 and 3. Then the remaining cloud will give shadow on time segment [1..6]. So, intervals [0..1] and [6..inf) are sunny. <image> In the second example for k = 1 it is not necessary to dispel anything, and for k = 5 the best strategy is to dispel clouds 2 and 3. This adds an additional sunny segment [4..8], which together with [0..1] allows to grow up the muffin at the eight minute. <image> <image> If the third example the two seedlings are completely different. For the first one it is necessary to dispel cloud 1 and obtain a sunny segment [0..10]. However, the same strategy gives answer 180 for the second seedling. Instead, we can dispel cloud 2, to make segments [0..3] and [7..inf) sunny, and this allows up to shorten the time to 104. Submitted Solution: ``` class my_sum: _a = [(0, -1), (0, -1)] def add(self, id, value): if self._a[0][1] == id: _tmp = max(self._a[0][0], value) self._a[0] = (_tmp, self._a[0][1]) elif self._a[1][0] < value: self._a[1] = (value, id) if self._a[0][0] < self._a[1][0]: _tmp = self._a[0] self._a[0], self._a[1] = self._a[1], _tmp def ask(self, id): return self._a[0][0] if self._a[0][1] != id else self._a[1][0] cost = [] toupd = [0 for _ in range(300000)] if __name__ == '__main__': _first_line = input().split(' ') n = int(_first_line[0]) budget = int(_first_line[1]) # cost[n] = 0 events = [(0, n), (2000000000, n)] for _i in range(n): _line = input().split(' ') _l, _r, _cost = int(_line[0]), int(_line[1]), int(_line[2]) cost.append(_cost) events.append((_l, _i)) events.append((_r, _i)) events.sort() _values = cost[0:n] _values.sort() values = [] while len(_values) > 0: _first = _values[0] _values.remove(_first) if len(values) == 0 or _first != values[-1]: values.append(_first) covers = set([]) if events[0][1] < n: covers.add(events[0][1]) curmx = 0 parts = [] bit = [] for i in range(len(values)): bit.append(my_sum()) _length = dict() for _t in range(1, len(events)): mxlen = events[_t][0] - events[_t - 1][0] if mxlen > 0 and len(covers) <= 2: p, q = n, n if len(covers) > 0: p = list(covers)[0] if len(covers) > 1: q = list(covers)[-1] _start = -1 if p == n: _start = curmx else: if q == n: if cost[p] <= budget: _start = toupd[p] k = len(values) - 1 for _index, _v in enumerate(values): if _v > cost[p] - values[0]: k = _index - 1 break while k >= 0: _start = max(_start, bit[k].ask(p)) k -= ~k & k + 1 if (p, q) not in _length: _length[(p, q)] = 0 _tmp_value = _length[(p, q)] + mxlen k = len(values) - 1 for _index, _v in enumerate(values): if _v < cost[p] - values[0]: k = _index break while k < len(values): bit[k].add(p, _tmp_value) k += ~k & k + 1 elif cost[p] + cost[q] <= budget: if (p, n) not in _length: _length[(p, n)] = 0 if (q, n) not in _length: _length[(q, n)] = 0 _start = _length[(p, n)] + _length[(q, n)] if (p, q) not in _length: _length[(p, q)] = 0 toupd[p] = max(toupd[p], _length[(q, n)] + _length[(p, q)] + mxlen) toupd[q] = max(toupd[q], _length[(p, n)] + _length[(p, q)] + mxlen) if ~_start: if (p, q) not in _length: _length[(p, q)] = 0 if (n, n) not in _length: _length[(n, n)] = 0 _start += _length[(p, q)] + _length[(n, n)] if ~_start and _start + mxlen > curmx: curmx = _start + mxlen parts.append((curmx, events[_t][0])) if (p, q) not in _length: _length[(p, q)] = 0 _length[(p, q)] += + mxlen _tmp_i = events[_t][1] if _tmp_i < n: if _tmp_i in covers: covers.remove(_tmp_i) else: covers.add(_tmp_i) q = int(input()) t = 0 for _ in range(q): t = int(input()) for _first, _second in parts: if _first >= t: print(_second - (_first - t)) break ```
instruction
0
14,693
3
29,386
No
output
1
14,693
3
29,387
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not. Input The first line contains integer n (3 ≀ n ≀ 100) β€” amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 β€” the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s. Output If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO. Examples Input 8 00111000 Output YES Input 7 1001011 Output NO Input 7 1010100 Output YES Submitted Solution: ``` inpt = open('input.txt', 'r') outpt = open('output.txt', 'w') n = int(inpt.readline()) s = inpt.readline() check = [] for i in range(len(s)): if s[i] == '1': check.append(i) flag = 0 for j in range(1, len(check)-1): if check[j] - check[j-1] == check[j+1] - check[j]: flag = 0 else: flag = 1 outpt.write('YES' if flag ==0 else 'NO') outpt.close() # 10 # 0011111011 ```
instruction
0
15,407
3
30,814
No
output
1
15,407
3
30,815
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not. Input The first line contains integer n (3 ≀ n ≀ 100) β€” amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 β€” the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s. Output If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO. Examples Input 8 00111000 Output YES Input 7 1001011 Output NO Input 7 1010100 Output YES Submitted Solution: ``` from collections import Counter I = open('input.txt', 'r') O = open('output.txt', 'w') input = lambda: I.readline()[:-1] print = lambda x: O.write(str(x) + '\n') n = int(input()) s = input().strip('0').split('1') cnt = Counter(len(x) for x in s) print('YES' if len(cnt.items()) <= 1 else 'NO') ```
instruction
0
15,408
3
30,816
No
output
1
15,408
3
30,817
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not. Input The first line contains integer n (3 ≀ n ≀ 100) β€” amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 β€” the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s. Output If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO. Examples Input 8 00111000 Output YES Input 7 1001011 Output NO Input 7 1010100 Output YES Submitted Solution: ``` Inp = open('input.txt') out = open('output.txt', 'w') n = Inp.readline().rstrip() n = int(n) s = Inp.readline().rstrip() s = list(s) pas = 0 res = [] f = 0 for i in range(len(s)): if s[i] == '1': f = 1 if i == 0: res.append(1) else: res.append(pas) pas = 0 elif s[i] == '0' and f != 0: pas += 1 if len(set(res)) == 1: out.write('YES') exit() out.write('NO') ```
instruction
0
15,409
3
30,818
No
output
1
15,409
3
30,819
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not. Input The first line contains integer n (3 ≀ n ≀ 100) β€” amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 β€” the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s. Output If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO. Examples Input 8 00111000 Output YES Input 7 1001011 Output NO Input 7 1010100 Output YES Submitted Solution: ``` import sys f = open("input.txt") o = open("output.txt", "w") n_bits = int(f.readline()) bits = [x for x in f.readline().strip()] if bits[-1] == "1": o.write("NO") sys.exit(0) cur_str = "" values = [] for bit in bits: if bit == "1": cur_str += "1" else: if cur_str != "": values.append(cur_str) cur_str = "" lengths = [len(x) for x in values] for i in range(1, len(lengths)): if lengths[i] != lengths[i-1]: o.write("NO") sys.exit(0) o.write("YES") ```
instruction
0
15,410
3
30,820
No
output
1
15,410
3
30,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight. The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument. You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≀ ai ≀ 108, 1 ≀ li ≀ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates. It is guaranteed that all the ai's are distinct. Output Print a single integer β€” the maximum total length of the illuminated part of the path. Examples Input 3 1 1 2 2 3 3 Output 5 Input 4 1 2 3 3 4 3 6 2 Output 9 Submitted Solution: ``` no = int(input()) details = [] for _ in range(no): v = input().split() v[0] = int(v[0]) v[1] = int(v[1]) details.append(v) details.sort() ans = 0 for i in range(no): if i==0 or i==(no-1): ans+=details[i][1] else: if details[i-1][0]<details[i+1][0]: ans+=details[i-1][0] else: ans+=details[i+1][0] print(ans) ```
instruction
0
15,470
3
30,940
No
output
1
15,470
3
30,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight. The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument. You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≀ ai ≀ 108, 1 ≀ li ≀ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates. It is guaranteed that all the ai's are distinct. Output Print a single integer β€” the maximum total length of the illuminated part of the path. Examples Input 3 1 1 2 2 3 3 Output 5 Input 4 1 2 3 3 4 3 6 2 Output 9 Submitted Solution: ``` import random n = int(input()) al = [] for i in range (n): ii = [int(c) for c in input().split()] al.append(ii) random.seed() ch = [-1, 1] def rc(): intervals = [] for i in range(n): nc = random.choice(ch) ni = [al[i][0], al[i][0] + nc * al[i][1]] ni.sort() while intervals and ni[0] <= intervals[-1][1]: ni[0] = min(ni[0], intervals[-1][0]) ni[1] = max(ni[1], intervals[-1][1]) del intervals[-1] intervals.append(ni) ml = 0 for ii in intervals: l = ii[1] - ii[0] if l > ml: ml = l return ml gl = 0 for i in range(n**2): ll = rc() if ll > gl: gl = ll print(gl) ```
instruction
0
15,471
3
30,942
No
output
1
15,471
3
30,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight. The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument. You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≀ ai ≀ 108, 1 ≀ li ≀ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates. It is guaranteed that all the ai's are distinct. Output Print a single integer β€” the maximum total length of the illuminated part of the path. Examples Input 3 1 1 2 2 3 3 Output 5 Input 4 1 2 3 3 4 3 6 2 Output 9 Submitted Solution: ``` no = int(input()) details = [] for _ in range(no): v = input().split() v[0] = int(v[0]) v[1] = int(v[1]) details.append(v) details.sort() ans = 0 for i in range(no): if i==0 or i==(no-1): ans+=details[i][1] else: if details[i-1][0]<details[i+1][0]: ans+=details[i-1][1] else: ans+=details[i+1][1] print(ans) ```
instruction
0
15,472
3
30,944
No
output
1
15,472
3
30,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight. The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument. You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≀ ai ≀ 108, 1 ≀ li ≀ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates. It is guaranteed that all the ai's are distinct. Output Print a single integer β€” the maximum total length of the illuminated part of the path. Examples Input 3 1 1 2 2 3 3 Output 5 Input 4 1 2 3 3 4 3 6 2 Output 9 Submitted Solution: ``` import random n = int(input()) al = [] for i in range (n): ii = [int(c) for c in input().split()] al.append(ii) random.seed() ch = [-1, 1] def rc(): intervals = [] for i in range(n): nc = random.choice(ch) ni = [al[i][0], al[i][0] + nc * al[i][1]] ni.sort() while intervals and ni[0] <= intervals[-1][1]: ni[0] = min(ni[0], intervals[-1][0]) ni[1] = max(ni[1], intervals[-1][1]) del intervals[-1] intervals.append(ni) ml = 0 for ii in intervals: l = ii[1] - ii[0] if l > ml: ml = l return ml gl = 0 for i in range(n**2 + 10000): ll = rc() if ll > gl: gl = ll print(gl) ```
instruction
0
15,473
3
30,946
No
output
1
15,473
3
30,947
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,650
3
31,300
Tags: brute force, geometry, implementation, math Correct Solution: ``` import math n,r=map(int,input().split()) a=list(map(int,input().split())) new=[r for i in range(n)] for i in range(1,n): for j in range(i): temp=(2*r)**2 - (a[i]-a[j])**2 if(temp>=0): new[i]=max(new[i],math.sqrt(temp)+new[j]) print(*new) ```
output
1
15,650
3
31,301
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,651
3
31,302
Tags: brute force, geometry, implementation, math Correct Solution: ``` n, r = map(int, input().split()) a = input().split() ans = [] for i in range(n): res = r for j in range(i): if (abs(int(a[j]) - int(a[i])) <= 2 * r): res = max(res, ans[j] + (4 * r * r - abs(int(a[j]) - int(a[i])) ** 2) ** 0.5) ans.append(res) for i in range(n): print(ans[i], end = ' ') ```
output
1
15,651
3
31,303
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,652
3
31,304
Tags: brute force, geometry, implementation, math Correct Solution: ``` from math import * n, r = map(int, input().split()) x = list(map(int, input().split())) ans = [] for i in range(n): yi = r for j in range(i): if abs(x[j] - x[i]) <= 2 * r: yi = max(yi, ans[j] + sqrt(4 * r**2 - (x[j] - x[i])**2)) ans.append(yi) print(' '.join(map(str, ans))) ```
output
1
15,652
3
31,305
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,653
3
31,306
Tags: brute force, geometry, implementation, math Correct Solution: ``` import math as mt import sys,string,bisect input=sys.stdin.readline from collections import deque,defaultdict from decimal import * getcontext().prec = 100 L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) def dist(x,y,c,d): return (x-c)**2+(y-d)**2 def circle(x1, y1, x2,y2, r1, r2): distSq = (((x1 - x2)* (x1 - x2))+ ((y1 - y2)* (y1 - y2)))**(.5) if (distSq + r2 <= r1): return True else: return False n,r=M() l=L() c=[(l[0],r,0)] for i in range(1,n): x=len(c) k=0 f=0 while(k<x): a=c[k][0] b=c[k][1] g=l[i] if(4*(r**2)>=(g-a)**2): re=mt.sqrt(4*(r**2)-(g-a)**2)+b f=max(f,re) k+=1 c.append((g,max(f,r),i)) c.sort(key=lambda x:x[2]) for i in range(n): print(c[i][1],end=" ") ```
output
1
15,653
3
31,307
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,654
3
31,308
Tags: brute force, geometry, implementation, math Correct Solution: ``` n,r=map(int,input().split()) a=list(map(int,input().split())) st=[] for i in a: left,right,cen=i-r,i+r,-1 for j in st: if (not(j[0]>right or j[1]<left)) and cen< ((2*r)**2 - ((j[0]+j[1])/2 - i)**2 )**0.5 + j[2]: cen=((2*r)**2 - ((j[0]+j[1])/2 - i)**2 )**0.5 + j[2] k=j if cen==-1: st.append((left,right,r)) c=r else: c=cen st.append((left,right,cen )) # print(st) # print print(c,end=" ") ```
output
1
15,654
3
31,309
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,655
3
31,310
Tags: brute force, geometry, implementation, math Correct Solution: ``` import math def get_n(): return int(input()) def get_int_vector(): return [int(x) for x in input().split()] def list2string(list): result = [] for i in list: result.append(str(i)) return ':'.join(result) def string2vector(string): return [int(x) for x in string.split(':')] n, r = get_int_vector() final = [] for x in get_int_vector(): center = [x, None] for pair in final: if (x-r >= pair[0]-r and x-r <= pair[0]+r) or (x+r >= pair[0]-r and x+r <= pair[0]+r): y = pair[1] + math.sqrt(4*r**2-(x-pair[0])**2) if center[1] == None or center[1] < y: center[1] = y if center[1] == None: center[1] = r print("{:.7f}".format(center[1])) final.append(center) ```
output
1
15,655
3
31,311
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,656
3
31,312
Tags: brute force, geometry, implementation, math Correct Solution: ``` import math; n, r = map(int, input().split()); X = list(map(int, input().split())); C = []; for q in range(len(X)): y = r; for w in range(len(C)): if abs(X[w] - X[q]) <= 2 * r: yc = math.sqrt(4 * r * r - (X[w] - X[q]) ** 2) +C[w]; #print(yc); y = max(y, yc); C.append(y); print(*C); ```
output
1
15,656
3
31,313
Provide tags and a correct Python 3 solution for this coding contest problem. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk.
instruction
0
15,657
3
31,314
Tags: brute force, geometry, implementation, math Correct Solution: ``` import math n, r = tuple(int(k) for k in input().split()) xs = tuple(map(int, input().split())) ts = [] for x2 in xs: y2 = r for (x1, y1) in ts: dx = abs(x1 - x2) if 2.0 * r - dx >= -10e-4: y2 = max(y2, y1 + math.sqrt(4 * r ** 2 - dx ** 2)) ts.append((x2, y2)) ys = [str(t[1]) for t in ts] print(' '.join(ys)) ```
output
1
15,657
3
31,315
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` n,r=map(int,input().split()) a=list(map(int,input().split())) y=[] for i in a: ini=r for x,j in y: if abs(x-i)<=2*r: ini=max(ini,((4*r*r-(x-i)**2)**0.5)+j) y.append([i,ini]) print(ini,end=" ") ```
instruction
0
15,658
3
31,316
Yes
output
1
15,658
3
31,317
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` # CF 908/C : Disc Falling n,r = map(int, input().split()) x_data = list(map(int, input().split())) y_data = [] for i in range(n): y=r for j in range(i): if abs(x_data[j]-x_data[i])<=2*r: y = max(y, ( 4*r*r - (x_data[i]-x_data[j])**2 )**(0.5)+y_data[j] ) y_data.append(y) print(*y_data) ```
instruction
0
15,659
3
31,318
Yes
output
1
15,659
3
31,319
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` n, r = map(int, input().split()) data = list(map(int, input().split())) save = [] for i in range(n): ans = r for j in save: d = abs(data[i] - j[0]) if d <= 2 * r: ans = max(ans, j[1] + (4 * r**2 - d**2)**0.5) save.append([data[i], ans]) print(ans, end=" ") ```
instruction
0
15,660
3
31,320
Yes
output
1
15,660
3
31,321
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` from math import sqrt n, r = map(int, input().split()) a = list(map(int, input().split())) result = [0]*n result[0] = r coord = {i:[0,0] for i in range(n)} coord[0] = [a[0], result[0]] for i in range(1, n): f = True for j in range(i - 1, -1, -1): if abs(a[j] - a[i]) <= 2*r: A = sqrt((2*r - a[i] + a[j])*(2*r +a[i] - a[j])) ans = coord[j][1] + A if ans > result[i]: coord[i][0] = a[i] result[i] = ans coord[i][1] = result[i] f = False if f: result[i] = r coord[i] = [a[i], result[i]] print(*result) ```
instruction
0
15,661
3
31,322
Yes
output
1
15,661
3
31,323
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` import math n, r = [int(i) for i in input().split()] a = [int(i) for i in input().split()] b = [] def inter1(x1, x2, b): x3, x4, y = b if x1 < x3: if x2 >= x3: return True else: return False else: if x4 >= x1: return True else: return False ans = [] def inter2(b, xl, xr, r): x1 = xl + r x2 = b[0] + r y = b[2] dy = math.sqrt(4 * r * r - abs(x1 - x2) * abs(x1 - x2)) return y + dy for i in range(len(a)): xl = a[i] - r xr = a[i] + r maxy = 0 for z in range(len(b)): if inter1(xl, xr, b[z]): if b[z][2] > maxy: maxy = b[z][2] index = z if maxy == 0: b.append((xl, xr, r)) ans.append(r) else: ny = inter2(b[index], xl, xr, r) b.append((xl, xr, ny)) ans.append(ny) print(*ans) ```
instruction
0
15,662
3
31,324
No
output
1
15,662
3
31,325
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` n, r = map(int, input().split()) s = list(map(int, input().split())) l = [r] for i in range(1, len(s)): bo = 1 for j in range(i-1, -1, -1): if abs(s[i]-s[j]) <= 2*r: l.append(l[j] + (4*r*r - (s[i]-s[j])**2)**0.5) bo = 0; break if bo: l.append(r) print(*l) ```
instruction
0
15,663
3
31,326
No
output
1
15,663
3
31,327
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` import math n, r = map(int, input().split()) a = list(map(int, input().split())) re = [] for i in a: shape = [] pp = -1 for j in range(len(re) - 1, -1, -1): if re[j][0] >= (i - 2*r) and re[j][0] <= (i + 2*r): shape = [re[j][0], re[j][1]] pp = j break if shape == []: re.append([i, r]) else: re.append([i, shape[1] + math.sqrt(pow((2 * r), 2) - pow(i - re[pp][0], 2))]) for i in re: print(i[1], end=' ') ```
instruction
0
15,664
3
31,328
No
output
1
15,664
3
31,329
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed. Input The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks. Output Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates. Example Input 6 2 5 5 6 8 3 12 Output 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613 Note The final positions of the disks will look as follows: <image> In particular, note the position of the last disk. Submitted Solution: ``` import sys input = sys.stdin.readline def gcd(a, b): if a == 0: return b return gcd(b % a, a) def lcm(a, b): return (a * b) / gcd(a, b) def main(): n,r=map(int, input().split()) a=list(map(int, input().split())) x=[[0,i] for i in range(3001)] # [ymax, a[i]] ans=[] for i in range(max(0,a[0]-r), a[0]+r): x[i]=max([r,a[0]], x[i]) ans.append(r) for i in range(1,n): ymax=r for j in range(0, i): if abs(a[j]-a[i])<=2*r: ymax=max(ymax, ans[j]+(4*r*r-(a[i]-a[j]))**0.5) ans.append(ymax) print(*ans) # for i in range(15): # print(x[i],end=' ') return if __name__=="__main__": main() ```
instruction
0
15,665
3
31,330
No
output
1
15,665
3
31,331
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` import sys sys.setrecursionlimit(100000) while True: h, w = map(int, input().split()) if not h: break mp = [list("X" + input() + "X") for _ in range(h)] mp.insert(0, ["X"] * (w + 2)) mp.append(["X"] * (w + 2)) direct = ((0, 1), (0, -1), (1, 0), (-1, 0)) def search(x, y, target): mp[y][x] = "X" for dx, dy in direct: nx, ny = x + dx, y + dy if mp[ny][nx] == target: search(nx, ny, target) ans = 0 for x in range(1, w + 1): for y in range(1, h + 1): target = mp[y][x] if target != "X": search(x, y, target) ans += 1 print(ans) ```
instruction
0
15,852
3
31,704
Yes
output
1
15,852
3
31,705
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` import sys def setLine(tempH, line): for i in range(0, len(line)): geo[tempH][i] = line[i:i+1] def solve(): person = 0 for i in range(0,H): for j in range(0,W): if geo[i][j] is not "_": search(i,j) person += 1 print(person) def search(i,j): temp = geo[i][j] geo[i][j] = "_" dx = [-1,0,1,0] dy = [0,-1,0,1] for a in range(0,4): idx = i + dx[a] jdy = j + dy[a] if(isOnMap(idx, jdy)): if(isNeededToSolve(temp, idx, jdy)): search(idx,jdy) def isOnMap(i,j): return (0<=i and 0<=j and i<H and j<W) def isNeededToSolve(temp,i,j): target = geo[i][j] return (target is not "_" and temp is target) limit = 10**7 sys.setrecursionlimit(limit) H = -1 W = -1 tempH = 0 geo = [[0 for i in range(1)]for j in range(1)] repeat = True while repeat: line = input() if H is -1 and W is -1: H = int(line.split(" ")[0]) W = int(line.split(" ")[1]) geo = [[0 for i in range(W)] for j in range(H)] else: setLine(tempH, line) tempH+=1 #break if H is 0 and W is 0: break #solve if tempH is H: solve() H = -1 W = -1 tempH = 0 ```
instruction
0
15,853
3
31,706
Yes
output
1
15,853
3
31,707
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` import sys def solve(): person = 0 for i in range(0,H): for j in range(0,W): if geo[i][j] is not "_": search(i,j) person += 1 print(person) def search(i,j): temp = geo[i][j] geo[i][j] = "_" for a in range(0,4): idx, jdy = i + dx[a], j + dy[a] if(isOnMap(idx, jdy)): if(isNeededToSolve(temp, idx, jdy)): search(idx,jdy) def isOnMap(i,j): return (0<=i and 0<=j and i<H and j<W) def isNeededToSolve(temp,i,j): target = geo[i][j] return (target is not "_" and temp is target) limit = 10**7 sys.setrecursionlimit(limit) H, W, tempH = -1, -1, 0 dx = [-1,0,1,0] dy = [0,-1,0,1] geo = [[0 for i in range(1)]for j in range(1)] while True: line = input() if H is -1 and W is -1: p = line.split(" ") H, W = int(p[0]), int(p[1]) geo = [[0 for i in range(W)] for j in range(H)] else: geo[tempH] = list(line) tempH+=1 if H is 0 and W is 0:break if tempH is H: solve() H, W, tempH = -1, -1, 0 ```
instruction
0
15,854
3
31,708
Yes
output
1
15,854
3
31,709
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` import sys def setLine(tempH, line): for i in range(0, len(line)): geo[tempH][i] = line[i:i+1] def solve(): person = 0 for i in range(0,H): for j in range(0,W): if geo[i][j] is not "_": search(i,j) person += 1 print(person) def search(i,j): temp = geo[i][j] geo[i][j] = "_" dx = [-1,0,1,0] dy = [0,-1,0,1] for a in range(0,4): idx, jdy = i + dx[a], j + dy[a] if(isOnMap(idx, jdy)): if(isNeededToSolve(temp, idx, jdy)): search(idx,jdy) def isOnMap(i,j): return (0<=i and 0<=j and i<H and j<W) def isNeededToSolve(temp,i,j): target = geo[i][j] return (target is not "_" and temp is target) limit = 10**7 sys.setrecursionlimit(limit) H, W, tempH = -1, -1, 0 geo = [[0 for i in range(1)]for j in range(1)] while True: line = input() if H is -1 and W is -1: p = line.split(" ") H, W = int(p[0]), int(p[1]) geo = [[0 for i in range(W)] for j in range(H)] else: setLine(tempH, line) tempH+=1 #break if H is 0 and W is 0: break #solve if tempH is H: solve() H, W, tempH = -1, -1, 0 ```
instruction
0
15,855
3
31,710
Yes
output
1
15,855
3
31,711
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` # -*- coding:utf-8 -*- import sys def dfs(x, y, sym): tile[x][y] = "." for i in range(len(DX)): nx = x + DX[i] ny = y + DY[i] if nx>=0 and nx<N and ny>=0 and ny<M and tile[nx][ny]==sym: dfs(nx, ny, sym) def solve(): res = 0 for i in range(N): for j in range(M): if tile[i][j] != ".": if tile[i][j] == "@": dfs(i, j, "@") res += 1 elif tile[i][j] == "#": dfs(i, j, "#") res += 1 elif tile[i][j] == "*": dfs(i, j, "*") res += 1 print(res) counter=0 DX = [-1, 0, 1, 0] DY = [0, -1, 0, 1] sys.setrecursionlimit(1000000) tile = [[0 for i in range(1)] for j in range(1)] while True: counter+=1 line = input() if ' ' in line: nums = line.split(" ") N = int(nums[0]) M = int(nums[1]) tile = [[0 for i in range(N)] for j in range(M)] if N==0 and M==0: break else: tile[counter-2] = list(line) if (counter-1)==M: solve() counter = 0 ```
instruction
0
15,856
3
31,712
No
output
1
15,856
3
31,713
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` # -*- coding:utf-8 -*- import sys sys.setrecursionlimit(10000000) def dfs(x, y, sym): tile[x][y] = '.' for i in range(len(DX)): nx = x + DX[i] ny = y + DY[i] if nx>=0 and nx<N and ny>=0 and ny<M and tile[nx][ny]==sym: dfs(nx, ny, sym) def solve(): res = 0 for i in range(N): for j in range(M): if not tile[i][j] == '.': if tile[i][j] == '@': dfs(i, j, '@') res += 1 elif tile[i][j] == '#': dfs(i, j, '#') res += 1 elif tile[i][j] == '*': dfs(i, j, '*') res += 1 return res res=0 counter=0 DX = [-1, 0, 1, 0] DY = [0, -1, 0, 1] while True: counter+=1 line = input() if ' ' in line: nums = line.split(' ') N = int(nums[0]) M = int(nums[1]) tile = [[0 for i in range(N)]for j in range(M)] if N==0 and M==0: break else: tile[counter-2] = list(line) if (counter-1)==M: res = solve() counter = 0 print(res) ```
instruction
0
15,857
3
31,714
No
output
1
15,857
3
31,715
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` def visiting(values,hp,vp,item): if not (0<=hp<len(values)): return if not (0<=vp<len(values[hp])): return if item!=values[hp][vp]: return values[hp][vp]=True visiting(values,hp-1,vp,item) visiting(values,hp+1,vp,item) visiting(values,hp,vp-1,item) visiting(values,hp,vp+1,item) def solve(values): count=0 for i in range(len(values)): for j in range(len(values[i])): if values[i][j] in ['@','#','*']: visiting(values,i,j,values[i][j]) count+=1 return count def main(): line,values=input(),list() while line!='0 0': H,W = list(map(int,line.strip().split(' '))) value = list() for _ in range(H): value.append(list(x for x in input().strip())) values.append(value) line = input() for value in values: print(solve(value)) if __name__=='__main__': main() ```
instruction
0
15,858
3
31,716
No
output
1
15,858
3
31,717
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will. Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown. For example, in the following 3 Γ— 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange) <image> Eliminating the boundaries between plots with the same tree gives: <image> In the end, it will be divided into 10 compartments, or 10 people. The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard. Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution. Input Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≀ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges. The input ends with two lines of zeros. The number of datasets does not exceed 20. Output For each dataset, output the number of people to be distributed on one line. Examples Input 10 10 ####*****@ @#@@@@#*#* @##***@@@* #****#*@** ##@*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Input 10 10 *****@ @#@@@@#*#* @##***@@@* ****#*@** @*#@@*## *@@@@*@@@# ***#@*@##* *@@@*@@##@ *@*#*@##** @****#@@#@ 0 0 Output 33 Submitted Solution: ``` # -*- coding:utf-8 -*- import sys sys.setrecursionlimit(100000) def preDatasets(q): line = input() print(line) datas[q] = line return datas def dfs(x, y, sym): tile[x][y] = '.' for i in range(len(DX)): nx = x + DX[i] ny = y + DY[i] if nx>=0 and nx<N and ny>=0 and ny<M and tile[nx][ny]==sym: dfs(nx, ny, sym) def solve(): res = 0 for i in range(N): for j in range(M): if not tile[i][j] == '.': if tile[i][j] == '@': dfs(i, j, '@') res += 1 elif tile[i][j] == '#': dfs(i, j, '#') res += 1 elif tile[i][j] == '*': dfs(i, j, '*') res += 1 print(res) index = 0 counter=0 datas = [[0 for i in range(1)]for j in range(1)] DX = [-1, 0, 1, 0] DY = [0, -1, 0, 1] while True: line = input() if ' ' in line: N = int(datas[index].split(' ')[0]) M = int(datas[index].split(' ')[1]) tile = [[0 for i in range(N)]for j in range(M)] if N == 0: break if not counter<=M: for i in range(len(tile)): tile[i] = list(datas[index+i+1]) solve() index += N+1 counter+=1 ```
instruction
0
15,859
3
31,718
No
output
1
15,859
3
31,719
Provide tags and a correct Python 3 solution for this coding contest problem. Thanks to the Doctor's help, the rebels managed to steal enough gold to launch a full-scale attack on the Empire! However, Darth Vader is looking for revenge and wants to take back his gold. The rebels have hidden the gold in various bases throughout the galaxy. Darth Vader and the Empire are looking to send out their spaceships to attack these bases. The galaxy can be represented as an undirected graph with n planets (nodes) and m wormholes (edges), each connecting two planets. A total of s empire spaceships and b rebel bases are located at different planets in the galaxy. Each spaceship is given a location x, denoting the index of the planet on which it is located, an attacking strength a, and a certain amount of fuel f. Each base is given a location x, and a defensive strength d. A spaceship can attack a base if both of these conditions hold: * the spaceship's attacking strength is greater or equal than the defensive strength of the base * the spaceship's fuel is greater or equal to the shortest distance, computed as the number of wormholes, between the spaceship's planet and the base's planet Vader is very particular about his attacking formations. He requires that each spaceship is to attack at most one base and that each base is to be attacked by at most one spaceship. Vader knows that the rebels have hidden k gold in each base, so he will assign the spaceships to attack bases in such a way that maximizes the number of bases attacked. Therefore, for each base that is attacked, the rebels lose k gold. However, the rebels have the ability to create any number of dummy bases. With the Doctor's help, these bases would exist beyond space and time, so all spaceship can reach them and attack them. Moreover, a dummy base is designed to seem irresistible: that is, it will always be attacked by some spaceship. Of course, dummy bases do not contain any gold, but creating such a dummy base costs h gold. What is the minimum gold the rebels can lose if they create an optimal number of dummy bases? Input The first line contains two integers n and m (1 ≀ n ≀ 100, 0 ≀ m ≀ 10000), the number of nodes and the number of edges, respectively. The next m lines contain two integers u and v (1 ≀ u, v ≀ n) denoting an undirected edge between the two nodes. The next line contains four integers s, b, k and h (1 ≀ s, b ≀ 1000, 0 ≀ k, h ≀ 10^9), the number of spaceships, the number of bases, the cost of having a base attacked, and the cost of creating a dummy base, respectively. The next s lines contain three integers x, a, f (1 ≀ x ≀ n, 0 ≀ a, f ≀ 10^9), denoting the location, attack, and fuel of the spaceship. The next b lines contain two integers x, d (1 ≀ x ≀ n, 0 ≀ d ≀ 10^9), denoting the location and defence of the base. Output Print a single integer, the minimum cost in terms of gold. Example Input 6 7 1 2 2 3 3 4 4 6 6 5 4 4 3 6 4 2 7 3 1 10 2 3 8 2 5 1 0 6 5 4 3 7 5 2 Output 12 Note One way to minimize the cost is to build 4 dummy bases, for a total cost of 4 Γ— 3 = 12. One empire spaceship will be assigned to attack each of these dummy bases, resulting in zero actual bases attacked.
instruction
0
16,024
3
32,048
Tags: flows, graph matchings, graphs, shortest paths, sortings Correct Solution: ``` def naiveSolve(): return def floyd_warshall(n, edges): dist = [[0 if i == j else float("inf") for i in range(n)] for j in range(n)] # dist = [[float("inf") for i in range(n)] for j in range(n)] # if nodes are not directly connected to themselves # pred = [[None] * n for _ in range(n)] for u, v, d in edges: dist[u][v] = d # pred[u][v] = u for k in range(n): for i in range(n): for j in range(n): if dist[i][k] + dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j] # pred[i][j] = pred[k][j] return dist # return dist, pred def hopcroft_karp(graph, n, m): """ Maximum bipartite matching using Hopcroft-Karp algorithm, running in O(|E| sqrt(|V|)) """ assert (n == len(graph)) match1 = [-1] * n match2 = [-1] * m # Find a greedy match for possible speed up for node in range(n): for nei in graph[node]: if match2[nei] == -1: match1[node] = nei match2[nei] = node break while 1: bfs = [node for node in range(n) if match1[node] == -1] depth = [-1] * n for node in bfs: depth[node] = 0 for node in bfs: for nei in graph[node]: next_node = match2[nei] if next_node == -1: break if depth[next_node] == -1: depth[next_node] = depth[node] + 1 bfs.append(next_node) else: continue break else: break pointer = [len(c) for c in graph] dfs = [node for node in range(n) if depth[node] == 0] while dfs: node = dfs[-1] while pointer[node]: pointer[node] -= 1 nei = graph[node][pointer[node]] next_node = match2[nei] if next_node == -1: # Augmenting path found while nei != -1: node = dfs.pop() match2[nei], match1[node], nei = node, nei, match1[node] break elif depth[node] + 1 == depth[next_node]: dfs.append(next_node) break else: dfs.pop() return match1, match2 def main(): n,m=readIntArr() adj=[set() for _ in range(n+1)] for _ in range(m): u,v=readIntArr() adj[u].add(v) adj[v].add(u) s,b,k,h=readIntArr() # ships ships=[] # (location,attack,fuel) for _ in range(s): loc,atk,fuel=readIntArr() ships.append((loc,atk,fuel)) bases=[] # (location,def) for _ in range(b): loc,deff=readIntArr() bases.append((loc,deff)) edges=[] for u in range(1,n+1): for v in adj[u]: if u!=v: edges.append((u,v,1)) dist=floyd_warshall(n+1,edges) graph=[[] for _ in range(s)] # graph[ship]=[base1,base2,...] for ship in range(s): for base in range(b): ls,atk,fuel=ships[ship] lb,deff=bases[base] if atk>=deff and fuel>=dist[ls][lb]: graph[ship].append(base) match1,match2=hopcroft_karp(graph,s,b) matchCnts=0 for v in match1: if v!=-1: matchCnts+=1 zeroDummiesCost=k*matchCnts # assuming all ships can reach a base, we try to block all ships shipsDummiesCost=h*s print(min(zeroDummiesCost,shipsDummiesCost)) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(r): print('? {}'.format(r)) sys.stdout.flush() return readIntArr() def answerInteractive(adj,n): print('!') for u in range(1,n+1): for v in adj[u]: if v>u: print('{} {}'.format(u,v)) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil # from math import floor,ceil # for Python2 for _abc in range(1): main() ```
output
1
16,024
3
32,049
Provide tags and a correct Python 3 solution for this coding contest problem. Thanks to the Doctor's help, the rebels managed to steal enough gold to launch a full-scale attack on the Empire! However, Darth Vader is looking for revenge and wants to take back his gold. The rebels have hidden the gold in various bases throughout the galaxy. Darth Vader and the Empire are looking to send out their spaceships to attack these bases. The galaxy can be represented as an undirected graph with n planets (nodes) and m wormholes (edges), each connecting two planets. A total of s empire spaceships and b rebel bases are located at different planets in the galaxy. Each spaceship is given a location x, denoting the index of the planet on which it is located, an attacking strength a, and a certain amount of fuel f. Each base is given a location x, and a defensive strength d. A spaceship can attack a base if both of these conditions hold: * the spaceship's attacking strength is greater or equal than the defensive strength of the base * the spaceship's fuel is greater or equal to the shortest distance, computed as the number of wormholes, between the spaceship's planet and the base's planet Vader is very particular about his attacking formations. He requires that each spaceship is to attack at most one base and that each base is to be attacked by at most one spaceship. Vader knows that the rebels have hidden k gold in each base, so he will assign the spaceships to attack bases in such a way that maximizes the number of bases attacked. Therefore, for each base that is attacked, the rebels lose k gold. However, the rebels have the ability to create any number of dummy bases. With the Doctor's help, these bases would exist beyond space and time, so all spaceship can reach them and attack them. Moreover, a dummy base is designed to seem irresistible: that is, it will always be attacked by some spaceship. Of course, dummy bases do not contain any gold, but creating such a dummy base costs h gold. What is the minimum gold the rebels can lose if they create an optimal number of dummy bases? Input The first line contains two integers n and m (1 ≀ n ≀ 100, 0 ≀ m ≀ 10000), the number of nodes and the number of edges, respectively. The next m lines contain two integers u and v (1 ≀ u, v ≀ n) denoting an undirected edge between the two nodes. The next line contains four integers s, b, k and h (1 ≀ s, b ≀ 1000, 0 ≀ k, h ≀ 10^9), the number of spaceships, the number of bases, the cost of having a base attacked, and the cost of creating a dummy base, respectively. The next s lines contain three integers x, a, f (1 ≀ x ≀ n, 0 ≀ a, f ≀ 10^9), denoting the location, attack, and fuel of the spaceship. The next b lines contain two integers x, d (1 ≀ x ≀ n, 0 ≀ d ≀ 10^9), denoting the location and defence of the base. Output Print a single integer, the minimum cost in terms of gold. Example Input 6 7 1 2 2 3 3 4 4 6 6 5 4 4 3 6 4 2 7 3 1 10 2 3 8 2 5 1 0 6 5 4 3 7 5 2 Output 12 Note One way to minimize the cost is to build 4 dummy bases, for a total cost of 4 Γ— 3 = 12. One empire spaceship will be assigned to attack each of these dummy bases, resulting in zero actual bases attacked.
instruction
0
16,025
3
32,050
Tags: flows, graph matchings, graphs, shortest paths, sortings Correct Solution: ``` import sys def matching(node, visited, adj, assigned): if node == -1: return True if visited[node]: return False visited[node] = True for neighbor in adj[node]: if matching(assigned[neighbor], visited, adj, assigned): assigned[neighbor] = node return True return False INF = 1000 * 1000 inp = [int(x) for x in sys.stdin.read().split()] n, m = inp[0], inp[1] inp_idx = 2 G = [[INF] * n for _ in range(n)] for _ in range(m): a, b = inp[inp_idx] - 1, inp[inp_idx + 1] - 1 inp_idx += 2 G[a][b] = G[b][a] = 1 for v in range(n): G[v][v] = 0 for k in range(n): for i in range(n): for j in range(n): G[i][j] = min(G[i][j], G[i][k] + G[k][j]) s, b, k, h = inp[inp_idx], inp[inp_idx + 1], inp[inp_idx + 2], inp[inp_idx + 3] inp_idx += 4 spaceships = [] for _ in range(s): x, a, f = inp[inp_idx] - 1, inp[inp_idx + 1], inp[inp_idx + 2] inp_idx += 3 spaceships.append((x, a, f)) bases = [] for _ in range(b): x, d = inp[inp_idx] - 1, inp[inp_idx + 1] inp_idx += 2 bases.append((x, d)) adj = [[] for _ in range(s)] assigned = [[] for _ in range(b)] for i in range(s): space = spaceships[i] for j in range(b): base = bases[j] u, v = space[0], base[0] fuel = space[2] if G[u][v] <= fuel and space[1] >= base[1]: adj[i].append(j) visited = [False] * s assigned = [-1] * b matched = 0 for i in range(s): visited = [False] * s if matching(i, visited, adj, assigned): matched += 1 print(min(matched * k, h * s)) ```
output
1
16,025
3
32,051