{ "546d": { "name": "546_D. Soldier and Number Game", "description": "Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x > 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.\n\nTo make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a \u2265 b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.\n\nWhat is the maximum possible score of the second soldier?\n\nInput\n\nFirst line of input consists of single integer t (1 \u2264 t \u2264 1 000 000) denoting number of games soldiers play.\n\nThen follow t lines, each contains pair of integers a and b (1 \u2264 b \u2264 a \u2264 5 000 000) defining the value of n for a game.\n\nOutput\n\nFor each game output a maximum score that the second soldier can get.\n\nExamples\n\nInput\n\n2\n3 1\n6 3\n\n\nOutput\n\n2\n5", "public_tests": { "input": [ "2\n3 1\n6 3\n" ], "output": [ "2\n5\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 546, "cf_index": "D", "cf_points": 1500.0, "cf_rating": 1700, "cf_tags": [ "constructive algorithms", "dp", "math", "number theory" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 3, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "#include \nint a[5555555];\nint main() {\n int i, j, k, n;\n for (i = 2; i <= 5000000; i++) {\n if (!a[i])\n for (j = 1; i * j <= 5000000; j++)\n for (k = i * j; k % i == 0; k /= i) a[i * j]++;\n a[i] += a[i - 1];\n }\n scanf(\"%d\", &n);\n for (i = 0; i < n; i++) {\n scanf(\"%d%d\", &j, &k);\n printf(\"%d\\n\", a[j] - a[k]);\n }\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/546/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Fast IO||" ] }, "4a": { "name": "4_A. Watermelon", "description": "One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.\n\nPete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.\n\nInput\n\nThe first (and the only) input line contains integer number w (1 \u2264 w \u2264 100) \u2014 the weight of the watermelon bought by the boys.\n\nOutput\n\nPrint YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.\n\nExamples\n\nInput\n\n8\n\n\nOutput\n\nYES\n\nNote\n\nFor example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant \u2014 two parts of 4 and 4 kilos).", "public_tests": { "input": [ "8\n" ], "output": [ "YES\n" ] }, "source": 2, "difficulty": 7, "cf_contest_id": 4, "cf_index": "A", "cf_points": 0.0, "cf_rating": 800, "cf_tags": [ "brute force", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 64000000, "solution": "print\"YNEOS\"[(-2)**input()<5::2]", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/4/A", "anno_source": "usaco_guide", "anno_tag": [ "Expected Knowledge||" ] }, "231a": { "name": "231_A. Team", "description": "One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.\n\nThis contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.\n\nInput\n\nThe first input line contains a single integer n (1 \u2264 n \u2264 1000) \u2014 the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.\n\nOutput\n\nPrint a single integer \u2014 the number of problems the friends will implement on the contest.\n\nExamples\n\nInput\n\n3\n1 1 0\n1 1 1\n1 0 0\n\n\nOutput\n\n2\n\n\nInput\n\n2\n1 0 0\n0 1 1\n\n\nOutput\n\n1\n\nNote\n\nIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. \n\nIn the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution.", "public_tests": { "input": [ "2\n1 0 0\n0 1 1\n", "3\n1 1 0\n1 1 1\n1 0 0\n" ], "output": [ "1\n", "2\n" ] }, "source": 2, "difficulty": 7, "cf_contest_id": 231, "cf_index": "A", "cf_points": 500.0, "cf_rating": 800, "cf_tags": [ "brute force", "greedy" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "print(sum(a.count('1')>1for a in [*open(0)][1:]))", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/231/A", "anno_source": "usaco_guide", "anno_tag": [ "Expected Knowledge||" ] }, "546a": { "name": "546_A. Soldier and Bananas", "description": "A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i\u00b7k dollars for the i-th banana). \n\nHe has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?\n\nInput\n\nThe first line contains three positive integers k, n, w (1 \u2264 k, w \u2264 1000, 0 \u2264 n \u2264 109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants. \n\nOutput\n\nOutput one integer \u2014 the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.\n\nExamples\n\nInput\n\n3 17 4\n\n\nOutput\n\n13", "public_tests": { "input": [ "3 17 4\n" ], "output": [ "13\n" ] }, "source": 2, "difficulty": 7, "cf_contest_id": 546, "cf_index": "A", "cf_points": 500.0, "cf_rating": 800, "cf_tags": [ "brute force", "implementation", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "k,n,w=map(int,input().split())\nprint(max(0,w*(w+1)*k//2-n))", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/546/A", "anno_source": "usaco_guide", "anno_tag": [ "Math||", "Expected Knowledge||" ] }, "863b": { "name": "863_B. Kayaking", "description": "Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.\n\nNow the party is ready to start its journey, but firstly they have to choose kayaks. There are 2\u00b7n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is wi, and weight is an important matter in kayaking \u2014 if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.\n\nFormally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.\n\nHelp the party to determine minimum possible total instability! \n\nInput\n\nThe first line contains one number n (2 \u2264 n \u2264 50).\n\nThe second line contains 2\u00b7n integer numbers w1, w2, ..., w2n, where wi is weight of person i (1 \u2264 wi \u2264 1000).\n\nOutput\n\nPrint minimum possible total instability.\n\nExamples\n\nInput\n\n2\n1 2 3 4\n\n\nOutput\n\n1\n\n\nInput\n\n4\n1 3 4 6 3 4 100 200\n\n\nOutput\n\n5", "public_tests": { "input": [ "4\n1 3 4 6 3 4 100 200\n", "2\n1 2 3 4\n" ], "output": [ "5\n", "1\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 863, "cf_index": "B", "cf_points": 0.0, "cf_rating": 1500, "cf_tags": [ "brute force", "greedy", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n=2*input()\nw=sorted(map(int,raw_input().split()))\nr=10000\nfor i in range(n):\n for j in range(i):\n u=w[:j]+w[j+1:i]+w[i+1:]\n r=min(r,sum(u[i+1]-u[i] for i in range(0,n-3,2)) )\nprint(r)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/863/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Greedy||", "Sorting||" ] }, "1216c": { "name": "1216_C. White Sheet", "description": "There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates (x_1, y_1), and the top right \u2014 (x_2, y_2).\n\nAfter that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are (x_3, y_3), and the top right \u2014 (x_4, y_4). Coordinates of the bottom left corner of the second black sheet are (x_5, y_5), and the top right \u2014 (x_6, y_6). \n\n Example of three rectangles.\n\nDetermine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying not strictly inside the white sheet and strictly outside of both black sheets.\n\nInput\n\nThe first line of the input contains four integers x_1, y_1, x_2, y_2 (0 \u2264 x_1 < x_2 \u2264 10^{6}, 0 \u2264 y_1 < y_2 \u2264 10^{6}) \u2014 coordinates of the bottom left and the top right corners of the white sheet.\n\nThe second line of the input contains four integers x_3, y_3, x_4, y_4 (0 \u2264 x_3 < x_4 \u2264 10^{6}, 0 \u2264 y_3 < y_4 \u2264 10^{6}) \u2014 coordinates of the bottom left and the top right corners of the first black sheet.\n\nThe third line of the input contains four integers x_5, y_5, x_6, y_6 (0 \u2264 x_5 < x_6 \u2264 10^{6}, 0 \u2264 y_5 < y_6 \u2264 10^{6}) \u2014 coordinates of the bottom left and the top right corners of the second black sheet.\n\nThe sides of each sheet of paper are parallel (perpendicular) to the coordinate axes.\n\nOutput\n\nIf some part of the white sheet can be seen from the above after the two black sheets are placed, print \"YES\" (without quotes). Otherwise print \"NO\".\n\nExamples\n\nInput\n\n\n2 2 4 4\n1 1 3 5\n3 1 5 5\n\n\nOutput\n\n\nNO\n\n\nInput\n\n\n3 3 7 5\n0 0 4 6\n0 0 7 4\n\n\nOutput\n\n\nYES\n\n\nInput\n\n\n5 2 10 5\n3 1 7 6\n8 1 11 7\n\n\nOutput\n\n\nYES\n\n\nInput\n\n\n0 0 1000000 1000000\n0 0 499999 1000000\n500000 0 1000000 1000000\n\n\nOutput\n\n\nYES\n\nNote\n\nIn the first example the white sheet is fully covered by black sheets.\n\nIn the second example the part of the white sheet can be seen after two black sheets are placed. For example, the point (6.5, 4.5) lies not strictly inside the white sheet and lies strictly outside of both black sheets.", "public_tests": { "input": [ "0 0 1000000 1000000\n0 0 499999 1000000\n500000 0 1000000 1000000\n", "3 3 7 5\n0 0 4 6\n0 0 7 4\n", "5 2 10 5\n3 1 7 6\n8 1 11 7\n", "2 2 4 4\n1 1 3 5\n3 1 5 5\n" ], "output": [ "YES\n", "YES\n", "YES\n", "NO\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1216, "cf_index": "C", "cf_points": 0.0, "cf_rating": 1700, "cf_tags": [ "geometry", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "def R():x,y,*u=map(int,input().split());return[-x,-y]+u\nx=lambda a,b:[*map(min,a,b)]\ns=lambda x,y,u,v:max(0,x+u)*max(0,y+v)\na,b,c=R(),R(),R()\nd=x(a,b)\nprint('YNEOS'[s(*a)==s(*d)+s(*x(a,c))-s(*x(d,c))::2])", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1216/problem/C", "anno_source": "usaco_guide", "anno_tag": [ "Rectangle Geometry||", "Rectangle||" ] }, "1555b": { "name": "1555_B. Two Tables", "description": "You have an axis-aligned rectangle room with width W and height H, so the lower left corner is in point (0, 0) and the upper right corner is in (W, H).\n\nThere is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in (x_1, y_1), and the upper right corner in (x_2, y_2).\n\nYou want to place another rectangular table in this room with width w and height h with the width of the table parallel to the width of the room.\n\nThe problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).\n\nYou can't rotate any of the tables, but you can move the first table inside the room. \n\n Example of how you may move the first table.\n\nWhat is the minimum distance you should move the first table to free enough space for the second one?\n\nInput\n\nThe first line contains the single integer t (1 \u2264 t \u2264 5000) \u2014 the number of the test cases.\n\nThe first line of each test case contains two integers W and H (1 \u2264 W, H \u2264 10^8) \u2014 the width and the height of the room.\n\nThe second line contains four integers x_1, y_1, x_2 and y_2 (0 \u2264 x_1 < x_2 \u2264 W; 0 \u2264 y_1 < y_2 \u2264 H) \u2014 the coordinates of the corners of the first table.\n\nThe third line contains two integers w and h (1 \u2264 w \u2264 W; 1 \u2264 h \u2264 H) \u2014 the width and the height of the second table.\n\nOutput\n\nFor each test case, print the minimum distance you should move the first table, or -1 if there is no way to free enough space for the second table.\n\nYour answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.\n\nExample\n\nInput\n\n\n5\n8 5\n2 1 7 4\n4 2\n5 4\n2 2 5 4\n3 3\n1 8\n0 3 1 6\n1 5\n8 1\n3 0 6 1\n5 1\n8 10\n4 5 7 8\n8 5\n\n\nOutput\n\n\n1.000000000\n-1\n2.000000000\n2.000000000\n0.000000000\n\nNote\n\nThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by (0, -1), so the lower left corner will move from (2, 1) to (2, 0). Then you can place the second table at (0, 3)-(4, 5).\n\nIn the second test case, there is no way to fit both tables in the room without intersecting.\n\nIn the third test case, you can move the first table by (0, 2), so the lower left corner will move from (0, 3) to (0, 5).", "public_tests": { "input": [ "5\n8 5\n2 1 7 4\n4 2\n5 4\n2 2 5 4\n3 3\n1 8\n0 3 1 6\n1 5\n8 1\n3 0 6 1\n5 1\n8 10\n4 5 7 8\n8 5\n" ], "output": [ "1.000000000\n-1\n2.000000000\n2.000000000\n0.000000000\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 1555, "cf_index": "B", "cf_points": 0.0, "cf_rating": 1300, "cf_tags": [ "brute force" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "t = int(input())\nfor _ in range(t):\n\tw,h = map(int,input().split())\n\tx1,y1,x2,y2 = map(int,input().split())\n\txx,yy = map(int,input().split())\n\tans = 10**8\n\tif w>=x2-x1+xx:\n\t ans = min(ans,max(0,xx-x1),max(0,x2-(w-xx)))\n\tif h>=y2-y1+yy:\n\t ans = min(ans,max(0,yy-y1),max(0,y2-(h-yy)))\n\tprint(ans if ans<10**8 else -1)", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1555/B", "anno_source": "usaco_guide", "anno_tag": [ "Rectangle Geometry||", "Rectangle||" ] }, "358c": { "name": "358_C. Dima and Containers", "description": "Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.\n\nInna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands:\n\n 1. Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. \n 2. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. \n\n\n\nEvery time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.\n\nAs we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!\n\nInput\n\nThe first line contains integer n (1 \u2264 n \u2264 105) \u2014 the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer:\n\n 1. Integer a (1 \u2264 a \u2264 105) means that Inna gives Dima a command to add number a into one of containers. \n 2. Integer 0 shows that Inna asks Dima to make at most three extractions from different containers. \n\nOutput\n\nEach command of the input must correspond to one line of the output \u2014 Dima's action.\n\nFor the command of the first type (adding) print one word that corresponds to Dima's choice:\n\n * pushStack \u2014 add to the end of the stack; \n * pushQueue \u2014 add to the end of the queue; \n * pushFront \u2014 add to the beginning of the deck; \n * pushBack \u2014 add to the end of the deck. \n\n\n\nFor a command of the second type first print an integer k (0 \u2264 k \u2264 3), that shows the number of extract operations, then print k words separated by space. The words can be:\n\n * popStack \u2014 extract from the end of the stack; \n * popQueue \u2014 extract from the beginning of the line; \n * popFront \u2014 extract from the beginning from the deck; \n * popBack \u2014 extract from the end of the deck. \n\n\n\nThe printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers.\n\nThe printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.\n\nExamples\n\nInput\n\n10\n0\n1\n0\n1\n2\n0\n1\n2\n3\n0\n\n\nOutput\n\n0\npushStack\n1 popStack\npushStack\npushQueue\n2 popStack popQueue\npushStack\npushQueue\npushFront\n3 popStack popQueue popFront\n\n\nInput\n\n4\n1\n2\n3\n0\n\n\nOutput\n\npushStack\npushQueue\npushFront\n3 popStack popQueue popFront", "public_tests": { "input": [ "10\n0\n1\n0\n1\n2\n0\n1\n2\n3\n0\n", "4\n1\n2\n3\n0\n" ], "output": [ "0\npushStack\n1 popStack\npushQueue\npushStack\n2 popStack popQueue\npushFront\npushQueue\npushStack\n3 popStack popQueue popFront\n", "pushFront\npushQueue\npushStack\n3 popStack popQueue popFront\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 358, "cf_index": "C", "cf_points": 1500.0, "cf_rating": 2000, "cf_tags": [ "constructive algorithms", "greedy", "implementation" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "i, n = 0, int(input())\ns = ['pushQueue'] * n\na, b, c = ' popQueue', ' popStack', ' popBack'\np = ['0', '1' + a, '2' + a + b, '3' + a + b + c]\nt = []\nfor j in range(n):\n x = int(input())\n if x:\n t.append((x, j))\n continue\n t = sorted(k for x, k in sorted(t)[-3:])\n k = len(t)\n if k > 0: s[i: t[0]] = ['pushStack'] * (t[0] - i)\n if k > 1: s[t[1]] = 'pushStack'\n if k > 2: s[t[2]] = 'pushBack'\n i, t, s[j] = j + 1, [], p[k]\nprint('\\n'.join(s))", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/358/C", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "Simulation||" ] }, "581d": { "name": "581_D. Three Logos", "description": "Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. \n\nAdvertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.\n\nYour task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.\n\nInput\n\nThe first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 \u2264 x1, y1, x2, y2, x3, y3 \u2264 100), where xi and yi determine the length and width of the logo of the i-th company respectively.\n\nOutput\n\nIf it is impossible to place all the three logos on a square shield, print a single integer \"-1\" (without the quotes).\n\nIf it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters \"A\", \"B\" or \"C\". The sets of the same letters should form solid rectangles, provided that:\n\n * the sizes of the rectangle composed from letters \"A\" should be equal to the sizes of the logo of the first company, \n * the sizes of the rectangle composed from letters \"B\" should be equal to the sizes of the logo of the second company, \n * the sizes of the rectangle composed from letters \"C\" should be equal to the sizes of the logo of the third company, \n\n\n\nNote that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.\n\nSee the samples to better understand the statement.\n\nExamples\n\nInput\n\n5 1 2 5 5 2\n\n\nOutput\n\n5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC\n\n\nInput\n\n4 4 2 6 4 2\n\n\nOutput\n\n6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC", "public_tests": { "input": [ "4 4 2 6 4 2\n", "5 1 2 5 5 2\n" ], "output": [ "6\nBBBBBB\nBBBBBB\nAAAACC\nAAAACC\nAAAACC\nAAAACC\n", "5\nAAAAA\nBBBBB\nBBBBB\nCCCCC\nCCCCC\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 581, "cf_index": "D", "cf_points": 2000.0, "cf_rating": 1700, "cf_tags": [ "bitmasks", "brute force", "constructive algorithms", "geometry", "implementation", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "a,b,c,d,e,f=list(map(int,input().split()))\nn,n2=1,a*b+c*d+e*f\nwhile n**2n2:\n print(-1)\n exit()\nl=sorted([[max(a,b),min(a,b),'A'],[max(c,d),min(d,c),'B'],[max(e,f),min(e,f),'C']])\nif l[2][0]!=n:\n print(-1)\n exit(0)\nv=str(n)+'\\n'+(l[2][2]*n+'\\n')*l[2][1]\nif l[0][0]==n and l[1][0]==n:\n for i in range(2):\n v+=(l[i][2]*n+'\\n')*l[i][1]\nelse:\n s=n-l[2][1]\n if s not in l[0] or s not in l[1]:\n print(-1)\n exit()\n if s!=l[0][0]:\n l[0][0],l[0][1]=l[0][1],l[0][0]\n if s!=l[1][0]:\n l[1][0],l[1][1]=l[1][1],l[1][0]\n v+=(l[0][2]*l[0][1]+l[1][2]*l[1][1]+'\\n')*s\nprint(v)\n", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/581/D", "anno_source": "usaco_guide", "anno_tag": [ "Complete Search||", "Subsets||", "Permutation||", "Complete Search with Recursion||" ] }, "831c": { "name": "831_C. Jury Marks", "description": "Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.\n\nPolycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n \u2264 k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.\n\nYour task is to determine the number of options for the score the participant could have before the judges rated the participant.\n\nInput\n\nThe first line contains two integers k and n (1 \u2264 n \u2264 k \u2264 2 000) \u2014 the number of jury members and the number of scores Polycarp remembers.\n\nThe second line contains k integers a1, a2, ..., ak ( - 2 000 \u2264 ai \u2264 2 000) \u2014 jury's marks in chronological order.\n\nThe third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 \u2264 bj \u2264 4 000 000) \u2014 the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.\n\nOutput\n\nPrint the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print \"0\" (without quotes).\n\nExamples\n\nInput\n\n4 1\n-5 5 0 20\n10\n\n\nOutput\n\n3\n\n\nInput\n\n2 2\n-2000 -2000\n3998000 4000000\n\n\nOutput\n\n1\n\nNote\n\nThe answer for the first example is 3 because initially the participant could have - 10, 10 or 15 points.\n\nIn the second example there is only one correct initial score equaling to 4 002 000.", "public_tests": { "input": [ "4 1\n-5 5 0 20\n10\n", "2 2\n-2000 -2000\n3998000 4000000\n" ], "output": [ "3\n", "1\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 831, "cf_index": "C", "cf_points": 1000.0, "cf_rating": 1700, "cf_tags": [ "brute force", "constructive algorithms" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "o=lambda:[int(f)for f in input().split()]\nk,n=o()\na=o()\nb=o()\ns=[]\nfor x in b:\n t=x\n t1=set()\n for y in a:\n t-=y\n t1.add(t)\n s+=[t1]\nprint(len(set.intersection(*s)))\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/831/problem/C", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||", "Set||", "Sets||" ] }, "1209g1": { "name": "1209_G1. Into Blocks (easy version)", "description": "This is an easier version of the next problem. In this version, q = 0.\n\nA sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal.\n\nLet's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value x to value y, you must also change all other elements of value x into y as well. For example, for [3, 3, 1, 3, 2, 1, 2] it isn't allowed to change first 1 to 3 and second 1 to 2. You need to leave 1's untouched or change them to the same value.\n\nYou are given a sequence of integers a_1, a_2, \u2026, a_n and q updates.\n\nEach update is of form \"i x\" \u2014 change a_i to x. Updates are not independent (the change stays for the future).\n\nPrint the difficulty of the initial sequence and of the sequence after every update.\n\nInput\n\nThe first line contains integers n and q (1 \u2264 n \u2264 200 000, q = 0), the length of the sequence and the number of the updates.\n\nThe second line contains n integers a_1, a_2, \u2026, a_n (1 \u2264 a_i \u2264 200 000), the initial sequence.\n\nEach of the following q lines contains integers i_t and x_t (1 \u2264 i_t \u2264 n, 1 \u2264 x_t \u2264 200 000), the position and the new value for this position.\n\nOutput\n\nPrint q+1 integers, the answer for the initial sequence and the answer after every update.\n\nExamples\n\nInput\n\n\n5 0\n3 7 3 7 3\n\n\nOutput\n\n\n2\n\n\nInput\n\n\n10 0\n1 2 1 2 3 1 1 1 50 1\n\n\nOutput\n\n\n4\n\n\nInput\n\n\n6 0\n6 6 3 3 4 4\n\n\nOutput\n\n\n0\n\n\nInput\n\n\n7 0\n3 3 1 3 2 1 2\n\n\nOutput\n\n\n4", "public_tests": { "input": [ "7 0\n3 3 1 3 2 1 2\n", "6 0\n6 6 3 3 4 4\n", "10 0\n1 2 1 2 3 1 1 1 50 1\n", "5 0\n3 7 3 7 3\n" ], "output": [ "4", "0", "4", "2" ] }, "source": 2, "difficulty": 13, "cf_contest_id": 1209, "cf_index": "G1", "cf_points": 1500.0, "cf_rating": 2000, "cf_tags": [ "data structures", "dsu", "greedy", "implementation", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 5, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "MAXN = 200100\n\nn, q = map(int, input().split())\na = list(map(int, input().split()))\nlpos = [-1]*MAXN\nfor i in range(n):\n\tlpos[a[i]] = i\nneed = 0\ni = 0\nwhile i < n:\n\tstart = i\n\tr = lpos[a[i]]\n\tcnts = {}\n\twhile i <= r:\n\t\tr = max(r, lpos[a[i]])\n\t\tif a[i] in cnts:\n\t\t\tcnts[a[i]] += 1\n\t\telse:\n\t\t\tcnts[a[i]] = 1\n\t\ti += 1 \n\tneed += i - start - max(cnts.values())\n\nprint(need)\n ", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1209/problem/G1", "anno_source": "usaco_guide", "anno_tag": [ "Map||", "Set||", "Sets||" ] }, "1000c": { "name": "1000_C. Covered Points Count", "description": "You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.\n\nYour task is the following: for every k \u2208 [1..n], calculate the number of points with integer coordinates such that the number of segments that cover these points equals k. A segment with endpoints l_i and r_i covers point x if and only if l_i \u2264 x \u2264 r_i.\n\nInput\n\nThe first line of the input contains one integer n (1 \u2264 n \u2264 2 \u22c5 10^5) \u2014 the number of segments.\n\nThe next n lines contain segments. The i-th line contains a pair of integers l_i, r_i (0 \u2264 l_i \u2264 r_i \u2264 10^{18}) \u2014 the endpoints of the i-th segment.\n\nOutput\n\nPrint n space separated integers cnt_1, cnt_2, ..., cnt_n, where cnt_i is equal to the number of points such that the number of segments that cover these points equals to i.\n\nExamples\n\nInput\n\n3\n0 3\n1 3\n3 8\n\n\nOutput\n\n6 2 1 \n\n\nInput\n\n3\n1 3\n2 4\n5 7\n\n\nOutput\n\n5 2 0 \n\nNote\n\nThe picture describing the first example:\n\n\n\nPoints with coordinates [0, 4, 5, 6, 7, 8] are covered by one segment, points [1, 2] are covered by two segments and point [3] is covered by three segments.\n\nThe picture describing the second example:\n\n\n\nPoints [1, 4, 5, 6, 7] are covered by one segment, points [2, 3] are covered by two segments and there are no points covered by three segments.", "public_tests": { "input": [ "3\n0 3\n1 3\n3 8\n", "3\n1 3\n2 4\n5 7\n" ], "output": [ "6 2 1\n", "5 2 0\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1000, "cf_index": "C", "cf_points": 0.0, "cf_rating": 1700, "cf_tags": [ "data structures", "implementation", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 3, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "from collections import*\nn=int(input())\nd=defaultdict(int)\nfor _ in [0]*n:\n l,r=map(int,input().split());d[l]+=1;d[r+1]-=1\ns=p=0\nf=[0]*(n+1)\nfor k in sorted(d):\n f[s]+=k-p;s+=d[k];p=k\nprint(*f[1:])", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1000/C", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||", "Coordinate Compression||", "Sorting Custom||", "Sorting||" ] }, "632c": { "name": "632_C. The Smallest String Concatenation", "description": "You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.\n\nGiven the list of strings, output the lexicographically smallest concatenation.\n\nInput\n\nThe first line contains integer n \u2014 the number of strings (1 \u2264 n \u2264 5\u00b7104).\n\nEach of the next n lines contains one string ai (1 \u2264 |ai| \u2264 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5\u00b7104.\n\nOutput\n\nPrint the only string a \u2014 the lexicographically smallest string concatenation.\n\nExamples\n\nInput\n\n4\nabba\nabacaba\nbcd\ner\n\n\nOutput\n\nabacabaabbabcder\n\n\nInput\n\n5\nx\nxx\nxxa\nxxaa\nxxaaa\n\n\nOutput\n\nxxaaaxxaaxxaxxx\n\n\nInput\n\n3\nc\ncb\ncba\n\n\nOutput\n\ncbacbc", "public_tests": { "input": [ "4\nabba\nabacaba\nbcd\ner\n", "5\nx\nxx\nxxa\nxxaa\nxxaaa\n", "3\nc\ncb\ncba\n" ], "output": [ "abacabaabbabcder\n", "xxaaaxxaaxxaxxx\n", "cbacbc\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 632, "cf_index": "C", "cf_points": 0.0, "cf_rating": 1700, "cf_tags": [ "sortings", "strings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 3, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "import sys\nprint \"\".join(sorted(map(lambda s: s.rstrip(), sys.stdin.readlines()[1:]), cmp=lambda x,y: cmp(x+y,y+x)))", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/632/C", "anno_source": "usaco_guide", "anno_tag": [ "Sorting Custom||", "Sorting||" ] }, "1478c": { "name": "1478_C. Nezzar and Symmetric Array", "description": "Long time ago there was a symmetric array a_1,a_2,\u2026,a_{2n} consisting of 2n distinct integers. Array a_1,a_2,\u2026,a_{2n} is called symmetric if for each integer 1 \u2264 i \u2264 2n, there exists an integer 1 \u2264 j \u2264 2n such that a_i = -a_j.\n\nFor each integer 1 \u2264 i \u2264 2n, Nezzar wrote down an integer d_i equal to the sum of absolute differences from a_i to all integers in a, i. e. d_i = \u2211_{j = 1}^{2n} {|a_i - a_j|}.\n\nNow a million years has passed and Nezzar can barely remember the array d and totally forget a. Nezzar wonders if there exists any symmetric array a consisting of 2n distinct integers that generates the array d.\n\nInput\n\nThe first line contains a single integer t (1 \u2264 t \u2264 10^5) \u2014 the number of test cases. \n\nThe first line of each test case contains a single integer n (1 \u2264 n \u2264 10^5).\n\nThe second line of each test case contains 2n integers d_1, d_2, \u2026, d_{2n} (0 \u2264 d_i \u2264 10^{12}).\n\nIt is guaranteed that the sum of n over all test cases does not exceed 10^5.\n\nOutput\n\nFor each test case, print \"YES\" in a single line if there exists a possible array a. Otherwise, print \"NO\".\n\nYou can print letters in any case (upper or lower).\n\nExample\n\nInput\n\n\n6\n2\n8 12 8 12\n2\n7 7 9 11\n2\n7 11 7 11\n1\n1 1\n4\n40 56 48 40 80 56 80 48\n6\n240 154 210 162 174 154 186 240 174 186 162 210\n\n\nOutput\n\n\nYES\nNO\nNO\nNO\nNO\nYES\n\nNote\n\nIn the first test case, a=[1,-3,-1,3] is one possible symmetric array that generates the array d=[8,12,8,12].\n\nIn the second test case, it can be shown that there is no symmetric array consisting of distinct integers that can generate array d.", "public_tests": { "input": [ "6\n2\n8 12 8 12\n2\n7 7 9 11\n2\n7 11 7 11\n1\n1 1\n4\n40 56 48 40 80 56 80 48\n6\n240 154 210 162 174 154 186 240 174 186 162 210\n" ], "output": [ "\nYES\nNO\nNO\nNO\nNO\nYES\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1478, "cf_index": "C", "cf_points": 1500.0, "cf_rating": 1700, "cf_tags": [ "implementation", "math", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 512000000, "solution": "for _ in range(int(input())):\n n = int(input())\n t = 2*n\n s = 0\n l = list(map(int, input().split()))\n q = set(l)\n if 2*len(q) != t:\n print('NO')\n continue\n l = sorted(q, reverse=True)[:n]\n j = None\n for k in l:\n p = k-s\n if (p<=0) or (p%t!=0):\n print('NO')\n break\n j = p//t\n s += 2*j\n t -= 2\n else:\n print('YES')\n", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1478/C", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||", "Sorting Custom||", "Sorting||" ] }, "1472e": { "name": "1472_E. Correct Placement", "description": "Polycarp has invited n friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.\n\nEach friend is characterized by two values h_i (their height) and w_i (their width). On the photo the i-th friend will occupy a rectangle h_i \u00d7 w_i (if they are standing) or w_i \u00d7 h_i (if they are lying on the side).\n\nThe j-th friend can be placed in front of the i-th friend on the photo if his rectangle is lower and narrower than the rectangle of the i-th friend. Formally, at least one of the following conditions must be fulfilled:\n\n * h_j < h_i and w_j < w_i (both friends are standing or both are lying); \n * w_j < h_i and h_j < w_i (one of the friends is standing and the other is lying). \n\n\n\nFor example, if n = 3, h=[3,5,3] and w=[4,4,3], then:\n\n * the first friend can be placed in front of the second: w_1 < h_2 and h_1 < w_2 (one of the them is standing and the other one is lying); \n * the third friend can be placed in front of the second: h_3 < h_2 and w_3 < w_2 (both friends are standing or both are lying). \n\n\n\nIn other cases, the person in the foreground will overlap the person in the background.\n\nHelp Polycarp for each i find any j, such that the j-th friend can be located in front of the i-th friend (i.e. at least one of the conditions above is fulfilled).\n\nPlease note that you do not need to find the arrangement of all people for a group photo. You just need to find for each friend i any other friend j who can be located in front of him. Think about it as you need to solve n separate independent subproblems.\n\nInput\n\nThe first line contains one integer t (1 \u2264 t \u2264 10^4) \u2014 the number of test cases. Then t test cases follow.\n\nThe first line of each test case contains one integer n (1 \u2264 n \u2264 2 \u22c5 10^5) \u2014 the number of friends.\n\nThis is followed by n lines, each of which contains a description of the corresponding friend. Each friend is described by two integers h_i and w_i (1 \u2264 h_i, w_i \u2264 10^9) \u2014 height and width of the i-th friend, respectively.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \u22c5 10^5.\n\nOutput\n\nFor each test case output n integers on a separate line, where the i-th number is the index of a friend that can be placed in front of the i-th. If there is no such friend, then output -1.\n\nIf there are several answers, output any.\n\nExample\n\nInput\n\n\n4\n3\n3 4\n5 4\n3 3\n3\n1 3\n2 2\n3 1\n4\n2 2\n3 1\n6 3\n5 4\n4\n2 2\n2 3\n1 1\n4 4\n\n\nOutput\n\n\n-1 3 -1 \n-1 -1 -1 \n-1 -1 2 2 \n3 3 -1 3 \n\nNote\n\nThe first test case is described in the statement.\n\nIn the third test case, the following answers are also correct: \n\n * [-1, -1, 1, 2]; \n * [-1, -1, 1, 1]; \n * [-1, -1, 2, 1]. ", "public_tests": { "input": [ "4\n3\n3 4\n5 4\n3 3\n3\n1 3\n2 2\n3 1\n4\n2 2\n3 1\n6 3\n5 4\n4\n2 2\n2 3\n1 1\n4 4\n" ], "output": [ "\n-1 3 -1 \n-1 -1 -1 \n-1 -1 2 2 \n3 3 -1 3 \n" ] }, "source": 2, "difficulty": 11, "cf_contest_id": 1472, "cf_index": "E", "cf_points": 0.0, "cf_rating": 1700, "cf_tags": [ "binary search", "data structures", "dp", "sortings", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 4, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "for _ in range(int(input())):\n n = int(input());hw = []\n for i in range(n):\n h,w = map(int,input().split())\n if h > w:h,w = w,h\n hw.append((i,h,w)) \n hw.sort(key=lambda x:x[2],reverse=True);hw.sort(key=lambda x:x[1]);mw = (-1,10**10);ans = [-1]*n\n for i,h,w in hw:\n if mw[1] < w:ans[i] = mw[0]+1\n else:mw = (i,w) \n print(*ans)\n", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1472/E", "anno_source": "usaco_guide", "anno_tag": [ "Sorting Custom||", "Sorting||" ] }, "1020b": { "name": "1020_B. Badge", "description": "In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick. \n\nLet's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, however, claimed that the main culprit is some other student p_a.\n\nAfter that, the teacher came to student p_a and made a hole in his badge as well. The student in reply said that the main culprit was student p_{p_a}.\n\nThis process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.\n\nAfter that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.\n\nYou don't know the first student who was caught by the teacher. However, you know all the numbers p_i. Your task is to find out for every student a, who would be the student with two holes in the badge if the first caught student was a.\n\nInput\n\nThe first line of the input contains the only integer n (1 \u2264 n \u2264 1000) \u2014 the number of the naughty students.\n\nThe second line contains n integers p_1, ..., p_n (1 \u2264 p_i \u2264 n), where p_i indicates the student who was reported to the teacher by student i.\n\nOutput\n\nFor every student a from 1 to n print which student would receive two holes in the badge, if a was the first student caught by the teacher.\n\nExamples\n\nInput\n\n3\n2 3 2\n\n\nOutput\n\n2 2 3 \n\n\nInput\n\n3\n1 2 3\n\n\nOutput\n\n1 2 3 \n\nNote\n\nThe picture corresponds to the first example test case.\n\n\n\nWhen a = 1, the teacher comes to students 1, 2, 3, 2, in this order, and the student 2 is the one who receives a second hole in his badge.\n\nWhen a = 2, the teacher comes to students 2, 3, 2, and the student 2 gets a second hole in his badge. When a = 3, the teacher will visit students 3, 2, 3 with student 3 getting a second hole in his badge.\n\nFor the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.", "public_tests": { "input": [ "3\n1 2 3\n", "3\n2 3 2\n" ], "output": [ "1 2 3\n", "2 2 3\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 1020, "cf_index": "B", "cf_points": 750.0, "cf_rating": 1000, "cf_tags": [ "brute force", "dfs and similar", "graphs" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n=input()\np=map(int,raw_input().split())\nfor i in range(n):\n s=[1]*n\n while s[i]:s[i]=0;i=p[i]-1\n print i+1,", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1020/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Functional Graphs||", "Functional Graph||" ] }, "1137d": { "name": "1137_D. Cooperative Game", "description": "This is an interactive problem.\n\nMisha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game \"Lake\".\n\nMisha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of c vertices. The second part is a path from home to the lake which is a chain of t vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither t nor c.\n\n\n\nNote that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.\n\nAt the beginning of the game pieces of all the ten players, indexed with consecutive integers from 0 to 9, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than q such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.\n\nThe goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of c, t and q, but luckily they are your friends. Help them: coordinate their actions to win the game. \n\nMisha has drawn such a field that 1 \u2264 t, c, (t+c) \u2264 1000 and q = 3 \u22c5 (t+c).\n\nInput\n\nThere is no input \u2014 go to the interaction part straight away.\n\nOutput\n\nAfter all friends gather at the finish vertex, print \"done\" and terminate your program.\n\nInteraction\n\nTo give a command to move the friends, print \"next\" and then space-separated indices of the friends you want to move. For example, to give the command to move the friends with indices 0, 2, 5 and 9 print \"next 0 2 5 9\". At each turn, you must move at least one of your friends.\n\nAs an answer, first read an integer k, and then 10 digits divided into k space-separated groups. The friends that correspond to the indices in the same group are in the same vertex. The friends that correspond to indices in different groups are in different vertices. The indices in each group follow in ascending order.\n\nFor example, the answer \"2 05 12346789\" means that the friends with indices 0 and 5 are in one vertex, and all other friends are in the same but different vertex. The answer \"4 01 567 234 89\" means that Misha's friends are in four different vertices: the friends with indices 0 and 1 are in the first, the friends with indices 5, 6 and 7 are in the second, the friends with indices 2, 3 and 4 are in the third, and the friends with indices 8 and 9 are in the fourth.\n\nAfter printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:\n\n * fflush(stdout) or cout.flush() in C++; \n * System.out.flush() in Java; \n * flush(output) in Pascal; \n * stdout.flush() in Python; \n * see documentation for other languages. \n\n\n\nAnswer \"stop\" instead of a valid one means that you made an invalid query. Exit immediately after receiving \"stop\" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.\n\nHacks\n\nIn order to hack, print two integers t and c in a single line (1 \u2264 t, c, (t+c) \u2264 1000).\n\nExample\n\nInput\n\n\n2 05 12346789\n\n3 246789 135 0\n\n3 246789 0 135\n\n3 246789 0 135\n\n2 135 0246789\n\n1 0123456789\n\n\nOutput\n\n\nnext 0 5\n\nnext 0 1 3\n\nnext 2 3 0 1 4 5 6 7 8 9\n\nnext 9 8 7 6 5 4 3 2 1 0\n\nnext 0 1 3 5\n\nnext 1 3 5\n\ndone\n\nNote\n\nIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no \"extra\" line breaks should appear.\n\nIn the example, the friends move as follows:\n\n", "public_tests": { "input": [ "2 05 12346789\n\n3 246789 135 0\n\n3 246789 0 135\n\n3 246789 0 135\n\n2 135 0246789\n\n1 0123456789\n" ], "output": [ "next 0 1\nnext 0\nnext 0 1\nnext 0\nnext 0 1\nnext 0\nnext 0 1 2 3 4 5 6 7 8 9\ndone\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1137, "cf_index": "D", "cf_points": 2250.0, "cf_rating": 2400, "cf_tags": [ "constructive algorithms", "interactive", "number theory" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 512000000, "solution": "#include \nusing namespace std;\nint x;\nchar a[233];\nint nxt(const char *s) {\n puts(s), fflush(stdout), scanf(\"%d\", &x);\n for (int i = 0; i < x; ++i) scanf(\"%s\", a);\n return x;\n}\nint main() {\n while ((nxt(\"next 0 1\"), nxt(\"next 0\")) == 3)\n ;\n while (nxt(\"next 0 1 2 3 4 5 6 7 8 9\") == 2)\n ;\n return puts(\"done\"), fflush(stdout), 0;\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1137/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Functional Graphs||", "Functional Graph||" ] }, "1398c": { "name": "1398_C. Good Subarrays", "description": "You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (\u2211_{i=l}^{r} a_i = r - l + 1).\n\nFor example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0].\n\nCalculate the number of good subarrays of the array a.\n\nInput\n\nThe first line contains one integer t (1 \u2264 t \u2264 1000) \u2014 the number of test cases.\n\nThe first line of each test case contains one integer n (1 \u2264 n \u2264 10^5) \u2014 the length of the array a.\n\nThe second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 10^5.\n\nOutput\n\nFor each test case print one integer \u2014 the number of good subarrays of the array a.\n\nExample\n\nInput\n\n\n3\n3\n120\n5\n11011\n6\n600005\n\n\nOutput\n\n\n3\n6\n1\n\nNote\n\nThe first test case is considered in the statement.\n\nIn the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. \n\nIn the third test case there is only one good subarray: a_{2 ... 6}.", "public_tests": { "input": [ "3\n3\n120\n5\n11011\n6\n600005\n" ], "output": [ "3\n6\n1\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1398, "cf_index": "C", "cf_points": 0.0, "cf_rating": 1600, "cf_tags": [ "data structures", "dp", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "for s in[*open(0)][2::2]:\n d={0:1};r=t=0\n for x in s[:-1]:t+=int(x)-1;x=d.get(t,0);r+=x;d[t]=x+1\n print(r)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1398/problem/C", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||", "Math||" ] }, "gcd on blackboard125": { "name": "p03061 AtCoder Beginner Contest 125 - GCD on Blackboard", "description": "There are N integers, A_1, A_2, ..., A_N, written on the blackboard.\n\nYou will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.\n\nFind the maximum possible greatest common divisor of the N integers on the blackboard after your move.\n\nConstraints\n\n* All values in input are integers.\n* 2 \\leq N \\leq 10^5\n* 1 \\leq A_i \\leq 10^9\n\nOutput\n\nInput is given from Standard Input in the following format:\n\n\nN\nA_1 A_2 ... A_N\n\nOutput\n\nPrint the maximum possible greatest common divisor of the N integers on the blackboard after your move.\n\nExamples\n\nInput\n\n3\n7 6 8\n\n\nOutput\n\n2\n\n\nInput\n\n3\n12 15 18\n\n\nOutput\n\n6\n\n\nInput\n\n2\n1000000000 1000000000\n\n\nOutput\n\n1000000000", "public_tests": { "input": [ "3\n7 6 8", "2\n1000000000 1000000000", "3\n12 15 18" ], "output": [ "2", "1000000000", "6" ] }, "source": 5, "difficulty": 0, "cf_contest_id": 0, "cf_index": "", "cf_points": 0.0, "cf_rating": 0, "cf_tags": [ "" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 1073741824, "solution": "from math import*\nn,*a=map(int,open(0).read().split())\nb=[0]\nfor i in a:b+=gcd(b[-1],i),\nw=m=0\nfor i in range(n):m=max(m,gcd(w,b[-i-2]));w=gcd(w,a[~i])\nprint(m)", "prob_source": "atcoder", "url": "https://atcoder.jp/contests/abc125/tasks/abc125_c", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||" ] }, "1291d": { "name": "1291_D. Irreducible Anagrams", "description": "Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.\n\nLet's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k \u2265 2 and 2k non-empty strings s_1, t_1, s_2, t_2, ..., s_k, t_k that satisfy the following conditions:\n\n 1. If we write the strings s_1, s_2, ..., s_k in order, the resulting string will be equal to s; \n 2. If we write the strings t_1, t_2, ..., t_k in order, the resulting string will be equal to t; \n 3. For all integers i between 1 and k inclusive, s_i and t_i are anagrams of each other. \n\n\n\nIf such strings don't exist, then t is said to be an irreducible anagram of s. Note that these notions are only defined when s and t are anagrams of each other.\n\nFor example, consider the string s = \"gamegame\". Then the string t = \"megamage\" is a reducible anagram of s, we may choose for example s_1 = \"game\", s_2 = \"gam\", s_3 = \"e\" and t_1 = \"mega\", t_2 = \"mag\", t_3 = \"e\":\n\n\n\nOn the other hand, we can prove that t = \"memegaga\" is an irreducible anagram of s.\n\nYou will be given a string s and q queries, represented by two integers 1 \u2264 l \u2264 r \u2264 |s| (where |s| is equal to the length of the string s). For each query, you should find if the substring of s formed by characters from the l-th to the r-th has at least one irreducible anagram.\n\nInput\n\nThe first line contains a string s, consisting of lowercase English characters (1 \u2264 |s| \u2264 2 \u22c5 10^5).\n\nThe second line contains a single integer q (1 \u2264 q \u2264 10^5) \u2014 the number of queries.\n\nEach of the following q lines contain two integers l and r (1 \u2264 l \u2264 r \u2264 |s|), representing a query for the substring of s formed by characters from the l-th to the r-th.\n\nOutput\n\nFor each query, print a single line containing \"Yes\" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing \"No\" (without quotes) otherwise.\n\nExamples\n\nInput\n\n\naaaaa\n3\n1 1\n2 4\n5 5\n\n\nOutput\n\n\nYes\nNo\nYes\n\n\nInput\n\n\naabbbbbbc\n6\n1 2\n2 4\n2 2\n1 9\n5 7\n3 5\n\n\nOutput\n\n\nNo\nYes\nYes\nYes\nNo\nNo\n\nNote\n\nIn the first sample, in the first and third queries, the substring is \"a\", which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain \"a\". On the other hand, in the second query, the substring is \"aaa\", which has no irreducible anagrams: its only anagram is itself, and we may choose s_1 = \"a\", s_2 = \"aa\", t_1 = \"a\", t_2 = \"aa\" to show that it is a reducible anagram.\n\nIn the second query of the second sample, the substring is \"abb\", which has, for example, \"bba\" as an irreducible anagram.", "public_tests": { "input": [ "aaaaa\n3\n1 1\n2 4\n5 5\n", "aabbbbbbc\n6\n1 2\n2 4\n2 2\n1 9\n5 7\n3 5\n" ], "output": [ "Yes\nNo\nYes\n", "No\nYes\nYes\nYes\nNo\nNo\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1291, "cf_index": "D", "cf_points": 1000.0, "cf_rating": 1800, "cf_tags": [ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "s=raw_input()\nq=int(raw_input())\nn=len(s)\nhas=[[0 for j in range(26)] for i in range(n+1)]\nfor i in range(1,n+1):\n\tfor j in range(26):\n\t\thas[i][j]=has[i-1][j]\n\thas[i][ord(s[i-1])-ord('a')]+=1\n\nfor i in range(q):\n\tl,r=list(map(int,raw_input().split()))\n\tif l==r:\n\t\tprint(\"Yes\")\n\t\tcontinue\n\tif s[l-1]!=s[r-1]:\n\t\tprint(\"Yes\")\n\telse:\n\t\tcnt=0\n\t\tfor k in range(26):\n\t\t\tif has[r][k]-has[l-1][k]>0:\n\t\t\t\tcnt+=1\n\t\tif cnt>2:\n\t\t\tprint(\"Yes\")\n\t\telse:\n\t\t\tprint(\"No\")", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1291/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||" ] }, "multiple of 2019164": { "name": "p02702 AtCoder Beginner Contest 164 - Multiple of 2019", "description": "Given is a string S consisting of digits from `1` through `9`.\n\nFind the number of pairs of integers (i,j) (1 \u2264 i \u2264 j \u2264 |S|) that satisfy the following condition:\n\nCondition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.\n\nConstraints\n\n* 1 \u2264 |S| \u2264 200000\n* S is a string consisting of digits from `1` through `9`.\n\nInput\n\nInput is given from Standard Input in the following format:\n\n\nS\n\n\nOutput\n\nPrint the number of pairs of integers (i,j) (1 \u2264 i \u2264 j \u2264 |S|) that satisfy the condition.\n\nExamples\n\nInput\n\n1817181712114\n\n\nOutput\n\n3\n\n\nInput\n\n14282668646\n\n\nOutput\n\n2\n\n\nInput\n\n2119\n\n\nOutput\n\n0", "public_tests": { "input": [ "1817181712114", "2119", "14282668646" ], "output": [ "3", "0", "2" ] }, "source": 5, "difficulty": 0, "cf_contest_id": 0, "cf_index": "", "cf_points": 0.0, "cf_rating": 0, "cf_tags": [ "" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 1073741824, "solution": "m=2019\nl=[0]*m\na=b=0\nk=1\nfor c in input():l[b%m]+=1;b-=int(c)*k;a+=l[b%m];k=k*202%m\nprint(a)", "prob_source": "atcoder", "url": "https://atcoder.jp/contests/abc164/tasks/abc164_d", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||" ] }, "762b": { "name": "762_B. USB vs. PS/2", "description": "Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!\n\nThe computers bought for the room were different. Some of them had only USB ports, some \u2014 only PS/2 ports, and some had both options.\n\nYou have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.\n\nYou want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.\n\nInput\n\nThe first line contains three integers a, b and c (0 \u2264 a, b, c \u2264 105) \u2014 the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively.\n\nThe next line contains one integer m (0 \u2264 m \u2264 3\u00b7105) \u2014 the number of mouses in the price list.\n\nThe next m lines each describe another mouse. The i-th line contains first integer vali (1 \u2264 vali \u2264 109) \u2014 the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.\n\nOutput\n\nOutput two integers separated by space \u2014 the number of equipped computers and the total cost of the mouses you will buy.\n\nExample\n\nInput\n\n2 1 1\n4\n5 USB\n6 PS/2\n3 PS/2\n7 PS/2\n\n\nOutput\n\n3 14\n\nNote\n\nIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.", "public_tests": { "input": [ "2 1 1\n4\n5 USB\n6 PS/2\n3 PS/2\n7 PS/2\n" ], "output": [ "3 14\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 762, "cf_index": "B", "cf_points": 0.0, "cf_rating": 1400, "cf_tags": [ "greedy", "implementation", "sortings", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "a,b,c=map(int,input().split());ans=0\nm=int(input())\nu=[]\np=[]\nfor i in range(m):\n s=input().split()\n if s[1]=='USB': u.append(int(s[0]))\n else: p.append(int(s[0]))\nu.sort();p.sort()\na=min(a,len(u));b=min(b,len(p))\nans+=(sum(u[:a])+sum(p[:b]))\nd=sorted(u[a:]+p[b:]);c=min(c,len(d));ans+=sum(d[:c])\nprint(a+b+c,ans)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/762/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Greedy Sorting||", "Greedy||", "Two Pointers||", "Sorting||" ] }, "1158a": { "name": "1158_A. The Party and Sweets", "description": "n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 \u2264 i \u2264 n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 \u2264 j \u2264 m the maximal number of sweets, which j-th girl received from some boy is equal to g_j.\n\nMore formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, \u2026, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, \u2026, b_{n,j}.\n\nYou are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 \u2264 i \u2264 n and 1 \u2264 j \u2264 m. You are given the numbers b_1, \u2026, b_n and g_1, \u2026, g_m, determine this number. \n\nInput\n\nThe first line contains two integers n and m, separated with space \u2014 the number of boys and girls, respectively (2 \u2264 n, m \u2264 100 000). The second line contains n integers b_1, \u2026, b_n, separated by spaces \u2014 b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 \u2264 b_i \u2264 10^8). The third line contains m integers g_1, \u2026, g_m, separated by spaces \u2014 g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 \u2264 g_j \u2264 10^8).\n\nOutput\n\nIf the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.\n\nExamples\n\nInput\n\n\n3 2\n1 2 1\n3 4\n\n\nOutput\n\n\n12\n\nInput\n\n\n2 2\n0 1\n1 0\n\n\nOutput\n\n\n-1\n\nInput\n\n\n2 3\n1 0\n1 1 2\n\n\nOutput\n\n\n4\n\nNote\n\nIn the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12.\n\nIn the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.\n\nIn the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4.", "public_tests": { "input": [ "3 2\n1 2 1\n3 4\n", "2 3\n1 0\n1 1 2\n", "2 2\n0 1\n1 0\n" ], "output": [ "12\n", "4\n", "-1\n" ] }, "source": 2, "difficulty": 7, "cf_contest_id": 1158, "cf_index": "A", "cf_points": 500.0, "cf_rating": 1500, "cf_tags": [ "binary search", "constructive algorithms", "greedy", "implementation", "math", "sortings", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "I=lambda:map(int,input().split())\nn,m=I()\na,b=sorted(I(),reverse=1),sorted(I())\ns=sum(b)\nfor i in range(1,n):s+=a[i]*m\nif a[0]>b[0]:s=-1\nelif a[0]!=b[0]:s+=a[0]-a[1]\nprint(s)", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1158/A", "anno_source": "usaco_guide", "anno_tag": [ "Greedy Sorting||", "Greedy||", "Sorting||" ] }, "321b": { "name": "321_B. Ciel and Duel", "description": "Fox Ciel is playing a card game with her friend Jiro.\n\nJiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.\n\nNow is Ciel's battle phase, Ciel can do the following operation many times:\n\n 1. Choose one of her cards X. This card mustn't be chosen before. \n 2. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then: \n * If Y's position is Attack, then (X's strength) \u2265 (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength). \n * If Y's position is Defense, then (X's strength) > (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage. \n\n\n\nCiel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.\n\nInput\n\nThe first line contains two integers n and m (1 \u2264 n, m \u2264 100) \u2014 the number of cards Jiro and Ciel have.\n\nEach of the next n lines contains a string position and an integer strength (0 \u2264 strength \u2264 8000) \u2014 the position and strength of Jiro's current card. Position is the string \"ATK\" for attack, and the string \"DEF\" for defense.\n\nEach of the next m lines contains an integer strength (0 \u2264 strength \u2264 8000) \u2014 the strength of Ciel's current card.\n\nOutput\n\nOutput an integer: the maximal damage Jiro can get.\n\nExamples\n\nInput\n\n2 3\nATK 2000\nDEF 1700\n2500\n2500\n2500\n\n\nOutput\n\n3000\n\n\nInput\n\n3 4\nATK 10\nATK 100\nATK 1000\n1\n11\n101\n1001\n\n\nOutput\n\n992\n\n\nInput\n\n2 4\nDEF 0\nATK 0\n0\n0\n1\n1\n\n\nOutput\n\n1\n\nNote\n\nIn the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack \"ATK 2000\" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the \"DEF 1700\" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.\n\nIn the second test case, she should use the \"1001\" card to attack the \"ATK 100\" card, then use the \"101\" card to attack the \"ATK 10\" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.\n\nIn the third test case note that she can destroy the \"ATK 0\" card by a card with strength equal to 0, but she can't destroy a \"DEF 0\" card with that card.", "public_tests": { "input": [ "2 3\nATK 2000\nDEF 1700\n2500\n2500\n2500\n", "3 4\nATK 10\nATK 100\nATK 1000\n1\n11\n101\n1001\n", "2 4\nDEF 0\nATK 0\n0\n0\n1\n1\n" ], "output": [ "3000\n", "992\n", "1\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 321, "cf_index": "B", "cf_points": 1000.0, "cf_rating": 1900, "cf_tags": [ "dp", "flows", "greedy" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "R=lambda:raw_input().split()\nn,m=map(int,R())\na=[]\nd=[]\nfor _ in range(n):\n t,x=R()\n [d,a][t<'B']+=[int(x)]\na.sort()\nc=sorted(input() for _ in range(m))[::-1]\nw=sum(max(0,x-y) for x,y in zip(c,a))\ntry:\n for x in d:c.remove(min(y for y in c if y>x))\n t=sum(c)-sum(a)\n for x in a[::-1]:c.remove(min(y for y in c if y>=x))\n w=max(w,t)\nexcept:pass\nprint w", "prob_source": "codeforces", "url": "https://codeforces.com/contest/321/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Greedy Sorting||", "Greedy||" ] }, "755c": { "name": "755_C. PolandBall and Forest", "description": "PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.\n\nThere is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.\n\nHow many trees are there in the forest?\n\nInput\n\nThe first line contains single integer n (1 \u2264 n \u2264 104) \u2014 the number of Balls living in the forest.\n\nThe second line contains a sequence p1, p2, ..., pn of length n, where (1 \u2264 pi \u2264 n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.\n\nIt's guaranteed that the sequence p corresponds to some valid forest.\n\nHacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:\n\nIn the first line, output the integer n (1 \u2264 n \u2264 104) \u2014 the number of Balls and the integer m (0 \u2264 m < n) \u2014 the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:\n \n \n \n 5 3 \n 1 2 \n 3 4 \n 4 5 \n \n\nOutput\n\nYou should output the number of trees in the forest where PolandBall lives.\n\nInteraction\n\nFrom the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.\n\nExamples\n\nInput\n\n5\n2 1 5 3 3\n\nOutput\n\n2\n\nInput\n\n1\n1\n\n\nOutput\n\n1\n\nNote\n\nIn the first sample testcase, possible forest is: 1-2 3-4-5. \n\nThere are 2 trees overall.\n\nIn the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.", "public_tests": { "input": [ "1\n1\n", "5\n2 1 5 3 3" ], "output": [ "1\n", "2\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 755, "cf_index": "C", "cf_points": 1500.0, "cf_rating": 1300, "cf_tags": [ "dfs and similar", "dsu", "graphs", "interactive", "trees" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n, P = int(input()), list(map(int, input().split()))\nprint(sum(P[P[i]-1] == i+1 and P[i] < i+2 for i in range(n)))", "prob_source": "codeforces", "url": "https://codeforces.com/contest/755/problem/C", "anno_source": "usaco_guide", "anno_tag": [ "Tree Diameter||", "Connected Components||", "Tree||" ] }, "839c": { "name": "839_C. Journey", "description": "There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.\n\nTheon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can\u2019t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. \n\nLet the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link .\n\nInput\n\nThe first line contains a single integer n (1 \u2264 n \u2264 100000) \u2014 number of cities.\n\nThen n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 \u2264 ui, vi \u2264 n, ui \u2260 vi) \u2014 the cities connected by the i-th road.\n\nIt is guaranteed that one can reach any city from any other by the roads.\n\nOutput\n\nPrint a number \u2014 the expected length of their journey. The journey starts in the city 1.\n\nYour answer will be considered correct if its absolute or relative error does not exceed 10 - 6.\n\nNamely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .\n\nExamples\n\nInput\n\n4\n1 2\n1 3\n2 4\n\n\nOutput\n\n1.500000000000000\n\n\nInput\n\n5\n1 2\n1 3\n3 4\n2 5\n\n\nOutput\n\n2.000000000000000\n\nNote\n\nIn the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.\n\nIn the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.", "public_tests": { "input": [ "5\n1 2\n1 3\n3 4\n2 5\n", "4\n1 2\n1 3\n2 4\n" ], "output": [ "2.000000\n", "1.500000\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 839, "cf_index": "C", "cf_points": 1500.0, "cf_rating": 1500, "cf_tags": [ "dfs and similar", "dp", "graphs", "probabilities", "trees" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n=int(input())\ng={i:[] for i in range(n)}\nfor i in range(n-1):\n u,v=map(int,input().split())\n u-=1\n v-=1\n g[u].append(v)\n g[v].append(u)\nv=set()\nq=[(0,1,0)]\nres=0\nwhile q:\n s,p,l=q.pop()\n v.add(s)\n dep=0\n for to in g[s]:\n if to not in v:\n dep+=1\n if dep==0:\n res+=p*l\n else:\n for to in g[s]:\n if to not in v:\n q.append((to,p/dep,l+1))\nprint(res)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/839/problem/C", "anno_source": "usaco_guide", "anno_tag": [ "Tree||" ] }, "860d": { "name": "860_D. Wizard's Tour", "description": "All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland!\n\nIt is well-known that there are n cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other.\n\nThe tour will contain several episodes. In each of the episodes:\n\n * the wizard will disembark at some city x from the Helicopter; \n * he will give a performance and show a movie for free at the city x; \n * he will drive to some neighboring city y using a road; \n * he will give a performance and show a movie for free at the city y; \n * he will drive to some neighboring to y city z; \n * he will give a performance and show a movie for free at the city z; \n * he will embark the Helicopter and fly away from the city z. \n\n\n\nIt is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between a and b he only can drive once from a to b, or drive once from b to a, or do not use this road at all.\n\nThe wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard!\n\nPlease note that the wizard can visit the same city multiple times, the restriction is on roads only.\n\nInput\n\nThe first line contains two integers n, m (1 \u2264 n \u2264 2\u00b7105, 0 \u2264 m \u2264 2\u00b7105) \u2014 the number of cities and the number of roads in Berland, respectively.\n\nThe roads description follow, one in each line. Each description is a pair of two integers ai, bi (1 \u2264 ai, bi \u2264 n, ai \u2260 bi), where ai and bi are the ids of the cities connected by the i-th road. It is guaranteed that there are no two roads connecting the same pair of cities. Every road is bidirectional. The cities are numbered from 1 to n.\n\nIt is possible that the road network in Berland is not connected.\n\nOutput\n\nIn the first line print w \u2014 the maximum possible number of episodes. The next w lines should contain the episodes in format x, y, z \u2014 the three integers denoting the ids of the cities in the order of the wizard's visits.\n\nExamples\n\nInput\n\n4 5\n1 2\n3 2\n2 4\n3 4\n4 1\n\n\nOutput\n\n2\n1 4 2\n4 3 2\n\n\nInput\n\n5 8\n5 3\n1 2\n4 5\n5 1\n2 5\n4 3\n1 4\n3 2\n\n\nOutput\n\n4\n1 4 5\n2 3 4\n1 5 3\n5 2 1", "public_tests": { "input": [ "4 5\n1 2\n3 2\n2 4\n3 4\n4 1\n", "5 8\n5 3\n1 2\n4 5\n5 1\n2 5\n4 3\n1 4\n3 2\n" ], "output": [ "2\n2 4 1\n4 3 2\n", "4\n5 4 1\n4 3 2\n3 5 1\n5 2 1\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 860, "cf_index": "D", "cf_points": 3000.0, "cf_rating": 2300, "cf_tags": [ "constructive algorithms", "dfs and similar", "graphs" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "#include \nusing namespace std;\nconst int MAXN = 200007;\nvector G[MAXN];\nvector > res;\nint pre[MAXN], tim;\nbool dfs(int v, int anc = 0) {\n pre[v] = ++tim;\n vector t;\n for (auto w : G[v])\n if (pre[w] > pre[v] or (!pre[w] and !dfs(w, v))) t.push_back(w);\n for (int i = 0; i + 1 < (int)t.size(); i += 2)\n res.emplace_back(t[i], v, t[i + 1]);\n if (anc and t.size() % 2) {\n res.emplace_back(t.back(), v, anc);\n return true;\n } else\n return false;\n}\nint main() {\n ios_base::sync_with_stdio(0);\n int n, m;\n cin >> n >> m;\n while (m--) {\n int a, b;\n cin >> a >> b;\n G[a].push_back(b);\n G[b].push_back(a);\n }\n for (int i = 1; i <= n; i++)\n if (!pre[i]) dfs(i);\n cout << (int)res.size() << \"\\n\";\n for (auto& r : res)\n cout << get<0>(r) << \" \" << get<1>(r) << \" \" << get<2>(r) << \"\\n\";\n return 0;\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/860/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Spanning Tree||", "Tree||", "DFS||" ] }, "1201c": { "name": "1201_C. Maximum Median", "description": "You are given an array a of n integers, where n is odd. You can make the following operation with it:\n\n * Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1). \n\n\n\nYou want to make the median of the array the largest possible using at most k operations.\n\nThe median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.\n\nInput\n\nThe first line contains two integers n and k (1 \u2264 n \u2264 2 \u22c5 10^5, n is odd, 1 \u2264 k \u2264 10^9) \u2014 the number of elements in the array and the largest number of operations you can make.\n\nThe second line contains n integers a_1, a_2, \u2026, a_n (1 \u2264 a_i \u2264 10^9).\n\nOutput\n\nPrint a single integer \u2014 the maximum possible median after the operations.\n\nExamples\n\nInput\n\n\n3 2\n1 3 5\n\n\nOutput\n\n\n5\n\nInput\n\n\n5 5\n1 2 1 1 1\n\n\nOutput\n\n\n3\n\nInput\n\n\n7 7\n4 1 2 4 3 4 4\n\n\nOutput\n\n\n5\n\nNote\n\nIn the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.\n\nIn the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.\n\nIn the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.", "public_tests": { "input": [ "3 2\n1 3 5\n", "7 7\n4 1 2 4 3 4 4\n", "5 5\n1 2 1 1 1\n" ], "output": [ "5", "5", "3" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1201, "cf_index": "C", "cf_points": 1500.0, "cf_rating": 1400, "cf_tags": [ "binary search", "greedy", "math", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "R=lambda:map(int,input().split())\nn,k=R()\nm,*a=b=sorted(R())[n//2:]\ni=0\nfor x,y in zip(b,a+[1<<31]):i+=1;d=min(y-x,k//i);m+=d;k-=d*i\nprint(m)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1201/problem/C", "anno_source": "usaco_guide", "anno_tag": [ "Binary Search||" ] }, "862e": { "name": "862_E. Mahmoud and Ehab and the function", "description": "Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 \u2264 j \u2264 m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, . \n\nDr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer xi to all elements in a in range [li;ri] i.e. they should add xi to ali, ali + 1, ... , ari and then they should calculate the minimum value of f(j) for all valid j.\n\nPlease help Mahmoud and Ehab.\n\nInput\n\nThe first line contains three integers n, m and q (1 \u2264 n \u2264 m \u2264 105, 1 \u2264 q \u2264 105) \u2014 number of elements in a, number of elements in b and number of queries, respectively.\n\nThe second line contains n integers a1, a2, ..., an. ( - 109 \u2264 ai \u2264 109) \u2014 elements of a.\n\nThe third line contains m integers b1, b2, ..., bm. ( - 109 \u2264 bi \u2264 109) \u2014 elements of b.\n\nThen q lines follow describing the queries. Each of them contains three integers li ri xi (1 \u2264 li \u2264 ri \u2264 n, - 109 \u2264 x \u2264 109) \u2014 range to be updated and added value.\n\nOutput\n\nThe first line should contain the minimum value of the function f before any update.\n\nThen output q lines, the i-th of them should contain the minimum value of the function f after performing the i-th update .\n\nExample\n\nInput\n\n5 6 3\n1 2 3 4 5\n1 2 3 4 5 6\n1 1 10\n1 1 -9\n1 5 -1\n\n\nOutput\n\n0\n9\n0\n0\n\nNote\n\nFor the first example before any updates it's optimal to choose j = 0, f(0) = |(1 - 1) - (2 - 2) + (3 - 3) - (4 - 4) + (5 - 5)| = |0| = 0.\n\nAfter the first update a becomes {11, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(11 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6) = |9| = 9.\n\nAfter the second update a becomes {2, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(2 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6)| = |0| = 0.\n\nAfter the third update a becomes {1, 1, 2, 3, 4} and it's optimal to choose j = 0, f(0) = |(1 - 1) - (1 - 2) + (2 - 3) - (3 - 4) + (4 - 5)| = |0| = 0.", "public_tests": { "input": [ "5 6 3\n1 2 3 4 5\n1 2 3 4 5 6\n1 1 10\n1 1 -9\n1 5 -1\n" ], "output": [ "0\n9\n0\n0\n" ] }, "source": 2, "difficulty": 11, "cf_contest_id": 862, "cf_index": "E", "cf_points": 2000.0, "cf_rating": 2100, "cf_tags": [ "binary search", "data structures", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "from bisect import *\nf = lambda: list(map(int, raw_input().split()))\nn, m, q = f()\nk = m - n + 1\na = f()\ns = sum(a[0:n:2]) - sum(a[1:n:2])\nb = [0] + f()\nfor i in range(2, m + 1, 2): b[i] = -b[i]\nfor i in range(m): b[i + 1] += b[i]\nu = [b[j] - b[j + n] for j in range(1, k, 2)]\nv = [b[j + n] - b[j] for j in range(0, k, 2)]\nd = sorted(u + v)\ndef g(s):\n j = bisect_right(d, s)\n print(min(abs(s - d[j % k]), abs(s - d[j - 1])))\ng(s)\nfor i in range(q):\n l, r, x = f()\n s += x * (r % 2 + l % 2 - 1)\n g(s)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/862/problem/E", "anno_source": "usaco_guide", "anno_tag": [ "Binary Search||" ] }, "1117c": { "name": "1117_C. Magic Ship", "description": "You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). \n\nYou know the weather forecast \u2014 the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day \u2014 s_2, the n-th day \u2014 s_n and (n+1)-th day \u2014 s_1 again and so on. \n\nShip coordinates change the following way:\n\n * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); \n * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); \n * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); \n * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). \n\n\n\nThe ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2).\n\nYou task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2).\n\nInput\n\nThe first line contains two integers x_1, y_1 (0 \u2264 x_1, y_1 \u2264 10^9) \u2014 the initial coordinates of the ship.\n\nThe second line contains two integers x_2, y_2 (0 \u2264 x_2, y_2 \u2264 10^9) \u2014 the coordinates of the destination point.\n\nIt is guaranteed that the initial coordinates and destination point coordinates are different.\n\nThe third line contains a single integer n (1 \u2264 n \u2264 10^5) \u2014 the length of the string s.\n\nThe fourth line contains the string s itself, consisting only of letters U, D, L and R.\n\nOutput\n\nThe only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2).\n\nIf it's impossible then print \"-1\".\n\nExamples\n\nInput\n\n\n0 0\n4 6\n3\nUUU\n\n\nOutput\n\n\n5\n\n\nInput\n\n\n0 3\n0 0\n3\nUDD\n\n\nOutput\n\n\n3\n\n\nInput\n\n\n0 0\n0 1\n1\nL\n\n\nOutput\n\n\n-1\n\nNote\n\nIn the first example the ship should perform the following sequence of moves: \"RRRRU\". Then its coordinates will change accordingly: (0, 0) \u2192 (1, 1) \u2192 (2, 2) \u2192 (3, 3) \u2192 (4, 4) \u2192 (4, 6).\n\nIn the second example the ship should perform the following sequence of moves: \"DD\" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) \u2192 (0, 3) \u2192 (0, 1) \u2192 (0, 0).\n\nIn the third example the ship can never reach the point (0, 1).", "public_tests": { "input": [ "0 3\n0 0\n3\nUDD\n", "0 0\n4 6\n3\nUUU\n", "0 0\n0 1\n1\nL\n" ], "output": [ "3\n", "5\n", "-1\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1117, "cf_index": "C", "cf_points": 0.0, "cf_rating": 1900, "cf_tags": [ "binary search" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "x1,y1=map(int,input().split())\nx2,y2=map(int,input().split())\nn=int(input())\ns=input()\nx,y,dx,dy=0,0,[0],[0]\nfor c in s:\n if c=='U':\n y+=1\n elif c=='D':\n y-=1\n elif c=='L':\n x-=1\n else:\n x+=1\n dx.append(x)\n dy.append(y)\nans,L,R=-1,0,10**15\nwhile L<=R:\n M=(L+R)//2\n x=M//n*dx[n]+dx[M%n]\n y=M//n*dy[n]+dy[M%n]\n if abs(x-(x2-x1))+abs(y-(y2-y1))<=M:\n ans=M\n R=M-1\n else:\n L=M+1\nprint(ans)\n", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1117/C", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||", "Binary Search||" ] }, "847b": { "name": "847_B. Preparing for Merge Sort", "description": "Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.\n\nIvan represent his array with increasing sequences with help of the following algorithm.\n\nWhile there is at least one unused number in array Ivan repeats the following procedure:\n\n * iterate through array from the left to the right; \n * Ivan only looks at unused numbers on current iteration; \n * if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down. \n\n\n\nFor example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one \u2014 [2, 4].\n\nWrite a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.\n\nInput\n\nThe first line contains a single integer n (1 \u2264 n \u2264 2\u00b7105) \u2014 the number of elements in Ivan's array.\n\nThe second line contains a sequence consisting of distinct integers a1, a2, ..., an (1 \u2264 ai \u2264 109) \u2014 Ivan's array.\n\nOutput\n\nPrint representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.\n\nExamples\n\nInput\n\n5\n1 3 2 5 4\n\n\nOutput\n\n1 3 5 \n2 4 \n\n\nInput\n\n4\n4 3 2 1\n\n\nOutput\n\n4 \n3 \n2 \n1 \n\n\nInput\n\n4\n10 30 50 101\n\n\nOutput\n\n10 30 50 101 ", "public_tests": { "input": [ "4\n4 3 2 1\n", "5\n1 3 2 5 4\n", "4\n10 30 50 101\n" ], "output": [ "4\n3\n2\n1\n", "1 3 5\n2 4\n", "10 30 50 101\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 847, "cf_index": "B", "cf_points": 0.0, "cf_rating": 1600, "cf_tags": [ "binary search", "data structures" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "import bisect\nn=int(input())\na=list(map(int,input().split()))\nd=[]\nms=[]\nfor i in range(n):\n idx=bisect.bisect_left(ms,-a[i])\n if idx==len(ms):\n d.append([a[i]])\n ms.append(-a[i])\n else:\n ms[idx]=-a[i]\n d[idx].append(a[i])\nfor x in d:\n print(*x)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/847/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Binary Search||" ] }, "1244e": { "name": "1244_E. Minimizing Difference", "description": "You are given a sequence a_1, a_2, ..., a_n consisting of n integers.\n\nYou may perform the following operation on this sequence: choose any element and either increase or decrease it by one.\n\nCalculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.\n\nInput\n\nThe first line contains two integers n and k (2 \u2264 n \u2264 10^{5}, 1 \u2264 k \u2264 10^{14}) \u2014 the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.\n\nThe second line contains a sequence of integers a_1, a_2, ..., a_n (1 \u2264 a_i \u2264 10^{9}).\n\nOutput\n\nPrint the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.\n\nExamples\n\nInput\n\n\n4 5\n3 1 7 5\n\n\nOutput\n\n\n2\n\n\nInput\n\n\n3 10\n100 100 100\n\n\nOutput\n\n\n0\n\n\nInput\n\n\n10 9\n4 5 5 7 5 4 5 2 4 3\n\n\nOutput\n\n\n1\n\nNote\n\nIn the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2.\n\nIn the second example all elements are already equal, so you may get 0 as the answer even without applying any operations.", "public_tests": { "input": [ "10 9\n4 5 5 7 5 4 5 2 4 3\n", "4 5\n3 1 7 5\n", "3 10\n100 100 100\n" ], "output": [ "1\n", "2\n", "0\n" ] }, "source": 2, "difficulty": 11, "cf_contest_id": 1244, "cf_index": "E", "cf_points": 2500.0, "cf_rating": 2000, "cf_tags": [ "binary search", "constructive algorithms", "greedy", "sortings", "ternary search", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "g, f = map(int, input().split()); a = sorted(map(int, input().split()))\nl,j =0,g-1; b= False\nwhile(j-l > 0 and f > 0):\n x = (a[l+1]-a[l])*(l+1)+(a[j]-a[j-1])*(g-j)\n if x>=f:\n ans = max(a[j]-a[l]-f//(l+1),0);print(ans);b = True\n f-=x;l+=1;j-=1\nif(b==False):\n print(0)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1244/problem/E", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||", "Greedy||", "Binary Search||" ] }, "handshake149": { "name": "p02821 AtCoder Beginner Contest 149 - Handshake", "description": "Takahashi has come to a party as a special guest. There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.\n\nTakahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0). A handshake will be performed as follows:\n\n* Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same).\n* Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y.\n\n\n\nHowever, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold:\n\n* Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \\leq p < q \\leq M) such that (x_p,y_p)=(x_q,y_q).\n\n\n\nWhat is the maximum possible happiness after M handshakes?\n\nConstraints\n\n* 1 \\leq N \\leq 10^5\n* 1 \\leq M \\leq N^2\n* 1 \\leq A_i \\leq 10^5\n* All values in input are integers.\n\nInput\n\nInput is given from Standard Input in the following format:\n\n\nN M\nA_1 A_2 ... A_N\n\n\nOutput\n\nPrint the maximum possible happiness after M handshakes.\n\nExamples\n\nInput\n\n5 3\n10 14 19 34 33\n\n\nOutput\n\n202\n\n\nInput\n\n9 14\n1 3 5 110 24 21 34 5 3\n\n\nOutput\n\n1837\n\n\nInput\n\n9 73\n67597 52981 5828 66249 75177 64141 40773 79105 16076\n\n\nOutput\n\n8128170", "public_tests": { "input": [ "5 3\n10 14 19 34 33", "9 14\n1 3 5 110 24 21 34 5 3", "9 73\n67597 52981 5828 66249 75177 64141 40773 79105 16076" ], "output": [ "202", "1837", "8128170" ] }, "source": 5, "difficulty": 0, "cf_contest_id": 0, "cf_index": "", "cf_points": 0.0, "cf_rating": 0, "cf_tags": [ "" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 1073741824, "solution": "from bisect import bisect as B\nLI=lambda:map(int,input().split())\nA=0\nn,m=LI()\na=sorted(LI())\nR=a[::-1]\ndef Q(x,M):\n w=0\n for i in range(n):\n y=x-R[i]\n c=B(a,y-1)\n w+=n-c\n if w>=M:return 1\n return 0\nN=a[-1]*3\nO=-1\nwhile N-O>1:\n f=(O+N)//2\n if Q(f,m):O=f\n else:N=f\nP=0\nfor i in range(n):\n e=n-B(a,O-a[i]-1)\n P+=e\n A+=e*a[i]*2\nprint(A-O*(P-m))\n", "prob_source": "atcoder", "url": "https://atcoder.jp/contests/abc149/tasks/abc149_e", "anno_source": "usaco_guide", "anno_tag": [ "Prefix Sums||", "Binary Search||", "Sorting||" ] }, "1486d": { "name": "1486_D. Max Median", "description": "You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median.\n\nA median in an array of length n is an element which occupies position number \u230a (n + 1)/(2) \u230b after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1.\n\nSubarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},\u2026,a_r for some 1 \u2264 l \u2264 r \u2264 n, its length is r - l + 1.\n\nInput\n\nThe first line contains two integers n and k (1 \u2264 k \u2264 n \u2264 2 \u22c5 10^5).\n\nThe second line contains n integers a_1, a_2, \u2026, a_n (1 \u2264 a_i \u2264 n).\n\nOutput\n\nOutput one integer m \u2014 the maximum median you can get.\n\nExamples\n\nInput\n\n\n5 3\n1 2 3 2 1\n\n\nOutput\n\n\n2\n\nInput\n\n\n4 2\n1 2 3 4\n\n\nOutput\n\n\n3\n\nNote\n\nIn the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too.\n\nIn the second example median([3..4]) = 3.", "public_tests": { "input": [ "5 3\n1 2 3 2 1\n", "4 2\n1 2 3 4\n" ], "output": [ "\n2", "\n3" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1486, "cf_index": "D", "cf_points": 1750.0, "cf_rating": 2100, "cf_tags": [ "binary search", "data structures", "dp" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "N,K=map(int,input().split())\nA=list(map(int,input().split()))\nL,R=1,N\nwhile L>1\n B=[0]*(N+1)\n for i in range(N):\n if A[i]>=M:\n B[i+1]=1\n else:\n B[i+1]=-1\n B[i+1]+=B[i]\n X=0\n F=0\n for i in range(K,N+1):\n X=min(X,B[i-K])\n if Xfood\npacman->food->food :hmmge:\nlarges smaller val\nsmallest larger val\n'''\ndef check(mid,p,f):\n\tptr=0\n\tfor x in p:\n\t\tFrom=x\n\t\tTo=x\n\t\twhile ptrmid:\n\t\t\t\tbreak\n\t\t\tptr+=1\n\t\tif ptr==len(f):\n\t\t\treturn 1\n\treturn 0\ndef f(s,n):\n\tp=[]\n\tf=[]\n\tfor i in range(n):\n\t\tif s[i]==\"*\":\n\t\t\tf.append(i)\n\t\tif s[i]==\"P\":\n\t\t\tp.append(i)\n\tlo=0\n\thi=10**9\n\twhile lo<=hi:\n\t\tmid=(lo+hi)//2\n\t\tif check(mid,p,f):\n\t\t\thi=mid-1\n\t\telse:\n\t\t\tlo=mid+1\n\treturn lo\n\nn=int(input())\ns=list(input().strip())\nprint(f(s,n))", "prob_source": "codeforces", "url": "https://codeforces.com/contest/847/problem/E", "anno_source": "usaco_guide", "anno_tag": [ "Binary Search||" ] }, "818f": { "name": "818_F. Level Generation", "description": "Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.\n\nIvan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.\n\nSo the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.\n\nInput\n\nThe first line of input file contains a positive integer q (1 \u2264 q \u2264 100 000) \u2014 the number of graphs Ivan needs to construct.\n\nThen q lines follow, i-th line contains one positive integer ni (1 \u2264 ni \u2264 2\u00b7109) \u2014 the number of vertices in i-th graph.\n\nNote that in hacks you have to use q = 1.\n\nOutput\n\nOutput q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.\n\nExample\n\nInput\n\n3\n3\n4\n6\n\n\nOutput\n\n2\n3\n6\n\nNote\n\nIn the first example it is possible to construct these graphs:\n\n 1. 1 - 2, 1 - 3; \n 2. 1 - 2, 1 - 3, 2 - 4; \n 3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6. ", "public_tests": { "input": [ "3\n3\n4\n6\n" ], "output": [ "2\n3\n6\n" ] }, "source": 2, "difficulty": 12, "cf_contest_id": 818, "cf_index": "F", "cf_points": 0.0, "cf_rating": 2100, "cf_tags": [ "binary search", "math", "ternary search" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "#include \nusing namespace std;\nint main() {\n long long t, n, x;\n cin >> t;\n while (t--) {\n cin >> n;\n x = sqrt(n << 1);\n if (x * (x + 1) <= 2 * n) x++;\n cout << n + max(n, x * (x - 1) / 2 + 2) - 2 * x << endl;\n }\n return 0;\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/818/F", "anno_source": "usaco_guide", "anno_tag": [ "Binary Search||" ] }, "1365d": { "name": "1365_D. Solve The Maze", "description": "Vivek has encountered a problem. He has a maze that can be represented as an n \u00d7 m grid. Each of the grid cells may represent the following:\n\n * Empty \u2014 '.' \n * Wall \u2014 '#' \n * Good person \u2014 'G' \n * Bad person \u2014 'B' \n\n\n\nThe only escape from the maze is at cell (n, m).\n\nA person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.\n\nHelp him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.\n\nIt is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.\n\nInput\n\nThe first line contains one integer t (1 \u2264 t \u2264 100) \u2014 the number of test cases. The description of the test cases follows.\n\nThe first line of each test case contains two integers n, m (1 \u2264 n, m \u2264 50) \u2014 the number of rows and columns in the maze.\n\nEach of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.\n\nOutput\n\nFor each test case, print \"Yes\" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print \"No\"\n\nYou may print every letter in any case (upper or lower).\n\nExample\n\nInput\n\n\n6\n1 1\n.\n1 2\nG.\n2 2\n#B\nG.\n2 3\nG.#\nB#.\n3 3\n#B.\n#..\nGG.\n2 2\n#B\nB.\n\n\nOutput\n\n\nYes\nYes\nNo\nNo\nYes\nYes\n\nNote\n\nFor the first and second test cases, all conditions are already satisfied.\n\nFor the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.\n\nFor the fourth test case, the good person at (1,1) cannot escape.\n\nFor the fifth test case, Vivek can block the cells (2,3) and (2,2).\n\nFor the last test case, Vivek can block the destination cell (2, 2).", "public_tests": { "input": [ "6\n1 1\n.\n1 2\nG.\n2 2\n#B\nG.\n2 3\nG.#\nB#.\n3 3\n#B.\n#..\nGG.\n2 2\n#B\nB.\n" ], "output": [ "Yes\nYes\nNo\nNo\nYes\nYes\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1365, "cf_index": "D", "cf_points": 1500.0, "cf_rating": 1700, "cf_tags": [ "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "implementation", "shortest paths" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "from math import *\n\ndef r1(t):\n\treturn t(input())\n\ndef r2(t):\n\treturn [t(i) for i in input().split()]\n\ndef r3(t):\n\treturn [t(i) for i in input()]\n\ng=[]\n\ndef dfs(i,j,n,m):\n\tif g[i][j]=='#':\n\t\treturn 0\n\n\tans=0\n\tif g[i][j]=='G':\n\t\tans+=1\n\tif g[i][j]=='B':\n\t\treturn -100000\n\tg[i][j]='#'\n\n\tif (i>0):\n\t\tans+=dfs(i-1,j,n,m)\n\tif (i0):\n\t\tans+=dfs(i,j-1,n,m)\n\tif (j0) and g[i-1][j]=='.':\n\t\t\t\t\tg[i-1][j]='#'\n\t\t\t\tif (i0) and g[i][j-1]=='.':\n\t\t\t\t\tg[i][j-1]='#'\n\t\t\t\tif (jt:s-=a[u];u+=1\n z=max(z,v-u+1)\nprint z", "prob_source": "codeforces", "url": "https://codeforces.com/contest/279/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Two Pointers||" ] }, "702c": { "name": "702_C. Cellular Network", "description": "You are given n points on the straight line \u2014 the positions (x-coordinates) of the cities and m points on the same line \u2014 the positions (x-coordinates) of the cellular towers. All towers work in the same way \u2014 they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.\n\nYour task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.\n\nIf r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.\n\nInput\n\nThe first line contains two positive integers n and m (1 \u2264 n, m \u2264 105) \u2014 the number of cities and the number of cellular towers.\n\nThe second line contains a sequence of n integers a1, a2, ..., an ( - 109 \u2264 ai \u2264 109) \u2014 the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.\n\nThe third line contains a sequence of m integers b1, b2, ..., bm ( - 109 \u2264 bj \u2264 109) \u2014 the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.\n\nOutput\n\nPrint minimal r so that each city will be covered by cellular network.\n\nExamples\n\nInput\n\n3 2\n-2 2 4\n-3 0\n\n\nOutput\n\n4\n\n\nInput\n\n5 3\n1 5 10 14 17\n4 11 15\n\n\nOutput\n\n3", "public_tests": { "input": [ "3 2\n-2 2 4\n-3 0\n", "5 3\n1 5 10 14 17\n4 11 15\n" ], "output": [ "4\n", "3\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 702, "cf_index": "C", "cf_points": 0.0, "cf_rating": 1500, "cf_tags": [ "binary search", "implementation", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 3, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "R=lambda:map(int,raw_input().split())\nn,m=R()\na=R()\nb=[-1e20]+R()+[1e20]\ni=0\nt=0\nfor x in a:\n while b[i+1]<=x:\n i+=1\n t=max(t,min(x-b[i],b[i+1]-x))\nprint t\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/702/problem/C", "anno_source": "usaco_guide", "anno_tag": [ "Binary Search Sorted Array||", "Binary Search||", "Two Pointers||" ] }, "701c": { "name": "701_C. They Are Everywhere", "description": "Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.\n\nThere is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. \n\nSergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit. \n\nInput\n\nThe first line contains the integer n (1 \u2264 n \u2264 100 000) \u2014 the number of flats in the house.\n\nThe second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i. \n\nOutput\n\nPrint the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house. \n\nExamples\n\nInput\n\n3\nAaA\n\n\nOutput\n\n2\n\n\nInput\n\n7\nbcAAcbc\n\n\nOutput\n\n3\n\n\nInput\n\n6\naaBCCe\n\n\nOutput\n\n5\n\nNote\n\nIn the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.\n\nIn the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6. \n\nIn the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.", "public_tests": { "input": [ "6\naaBCCe\n", "7\nbcAAcbc\n", "3\nAaA\n" ], "output": [ "5", "3", "2" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 701, "cf_index": "C", "cf_points": 1000.0, "cf_rating": 1500, "cf_tags": [ "binary search", "strings", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n,s=int(input()),input()\np,q,r=len(set(s)),{},10**6\nfor i in range(n):\n q[s[i]]=i\n if len(q)==p:r=min(r,max(q.values())-min(q.values()))\nprint(r+1)", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/701/C", "anno_source": "usaco_guide", "anno_tag": [ "Two Pointers||" ] }, "814c": { "name": "814_C. An impassioned circulation of affection", "description": "Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!\n\nStill unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c \u2014 Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.\n\nFor instance, let's say the garland is represented by \"kooomo\", and Brother Koyomi's favourite colour is \"o\". Among all subsegments containing pieces of \"o\" only, \"ooo\" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.\n\nBut problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.\n\nInput\n\nThe first line of input contains a positive integer n (1 \u2264 n \u2264 1 500) \u2014 the length of the garland.\n\nThe second line contains n lowercase English letters s1s2... sn as a string \u2014 the initial colours of paper pieces on the garland.\n\nThe third line contains a positive integer q (1 \u2264 q \u2264 200 000) \u2014 the number of plans Nadeko has.\n\nThe next q lines describe one plan each: the i-th among them contains an integer mi (1 \u2264 mi \u2264 n) \u2014 the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci \u2014 Koyomi's possible favourite colour.\n\nOutput\n\nOutput q lines: for each work plan, output one line containing an integer \u2014 the largest Koyomity achievable after repainting the garland according to it.\n\nExamples\n\nInput\n\n6\nkoyomi\n3\n1 o\n4 o\n4 m\n\n\nOutput\n\n3\n6\n5\n\n\nInput\n\n15\nyamatonadeshiko\n10\n1 a\n2 a\n3 a\n4 a\n5 a\n1 b\n2 b\n3 b\n4 b\n5 b\n\n\nOutput\n\n3\n4\n5\n7\n8\n1\n2\n3\n4\n5\n\n\nInput\n\n10\naaaaaaaaaa\n2\n10 b\n10 z\n\n\nOutput\n\n10\n10\n\nNote\n\nIn the first sample, there are three plans: \n\n * In the first plan, at most 1 piece can be repainted. Repainting the \"y\" piece to become \"o\" results in \"kooomi\", whose Koyomity of 3 is the best achievable; \n * In the second plan, at most 4 pieces can be repainted, and \"oooooo\" results in a Koyomity of 6; \n * In the third plan, at most 4 pieces can be repainted, and \"mmmmmi\" and \"kmmmmm\" both result in a Koyomity of 5. ", "public_tests": { "input": [ "15\nyamatonadeshiko\n10\n1 a\n2 a\n3 a\n4 a\n5 a\n1 b\n2 b\n3 b\n4 b\n5 b\n", "6\nkoyomi\n3\n1 o\n4 o\n4 m\n", "10\naaaaaaaaaa\n2\n10 b\n10 z\n" ], "output": [ "3\n4\n5\n7\n8\n1\n2\n3\n4\n5\n", "3\n6\n5\n", "10\n10\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 814, "cf_index": "C", "cf_points": 1750.0, "cf_rating": 1600, "cf_tags": [ "brute force", "dp", "strings", "two pointers" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "#include \nusing namespace std;\nchar s[1501], c[1];\nint main() {\n int n, q;\n scanf(\"%d%s%d\", &n, s + 1, &q);\n while (q--) {\n int m, l = 0, ans = 0, cnt = 0;\n scanf(\"%d %s\", &m, c);\n for (int r = 1; r <= n; r++) {\n cnt += s[r] == c[0];\n while (r - l - cnt > m) cnt -= s[++l] == c[0];\n ans = max(ans, r - l);\n }\n printf(\"%d\\n\", ans);\n }\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/814/C", "anno_source": "usaco_guide", "anno_tag": [ "Two Pointers||" ] }, "1359c": { "name": "1359_C. Mixing Water", "description": "There are two infinite sources of water:\n\n * hot water of temperature h; \n * cold water of temperature c (c < h). \n\n\n\nYou perform the following procedure of alternating moves:\n\n 1. take one cup of the hot water and pour it into an infinitely deep barrel; \n 2. take one cup of the cold water and pour it into an infinitely deep barrel; \n 3. take one cup of the hot water ... \n 4. and so on ... \n\n\n\nNote that you always start with the cup of hot water.\n\nThe barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.\n\nYou want to achieve a temperature as close as possible to t. So if the temperature in the barrel is t_b, then the absolute difference of t_b and t (|t_b - t|) should be as small as possible.\n\nHow many cups should you pour into the barrel, so that the temperature in it is as close as possible to t? If there are multiple answers with the minimum absolute difference, then print the smallest of them.\n\nInput\n\nThe first line contains a single integer T (1 \u2264 T \u2264 3 \u22c5 10^4) \u2014 the number of testcases.\n\nEach of the next T lines contains three integers h, c and t (1 \u2264 c < h \u2264 10^6; c \u2264 t \u2264 h) \u2014 the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.\n\nOutput\n\nFor each testcase print a single positive integer \u2014 the minimum number of cups required to be poured into the barrel to achieve the closest temperature to t.\n\nExample\n\nInput\n\n\n3\n30 10 20\n41 15 30\n18 13 18\n\n\nOutput\n\n\n2\n7\n1\n\nNote\n\nIn the first testcase the temperature after 2 poured cups: 1 hot and 1 cold is exactly 20. So that is the closest we can achieve.\n\nIn the second testcase the temperature after 7 poured cups: 4 hot and 3 cold is about 29.857. Pouring more water won't get us closer to t than that.\n\nIn the third testcase the temperature after 1 poured cup: 1 hot is 18. That's exactly equal to t.", "public_tests": { "input": [ "3\n30 10 20\n41 15 30\n18 13 18\n" ], "output": [ "2\n7\n1\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1359, "cf_index": "C", "cf_points": 0.0, "cf_rating": 1700, "cf_tags": [ "binary search", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "for _ in range(int(input())):\n h,c,t=map(int,input().split())\n if t<=(h+c)/2:print(2)\n else:\n k=(h-t)//(2*t-h-c)\n if abs((2*k+3)*t-k*h-2*h-k*c-c)*(2*k+1)mid:\n cur = s[i]\n cnt += 1\n else:\n cur += s[i]\n if cnt > k:\n lo = mid+1\n else:\n hi = mid\nprint lo", "prob_source": "codeforces", "url": "https://codeforces.com/contest/803/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "Greedy||", "Binary Search||", "Two Pointers||" ] }, "1077d": { "name": "1077_D. Cutting Out", "description": "You are given an array s consisting of n integers.\n\nYou have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.\n\nCutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find such element in s, then you cannot cut out one more copy of t. The both arrays can contain duplicate elements.\n\nFor example, if s = [1, 2, 3, 2, 4, 3, 1] and k = 3 then one of the possible answers is t = [1, 2, 3]. This array t can be cut out 2 times. \n\n * To cut out the first copy of t you can use the elements [1, \\underline{2}, 3, 2, 4, \\underline{3}, \\underline{1}] (use the highlighted elements). After cutting out the first copy of t the array s can look like [1, 3, 2, 4]. \n * To cut out the second copy of t you can use the elements [\\underline{1}, \\underline{3}, \\underline{2}, 4]. After cutting out the second copy of t the array s will be [4]. \n\n\n\nYour task is to find such array t that you can cut out the copy of t from s maximum number of times. If there are multiple answers, you may choose any of them.\n\nInput\n\nThe first line of the input contains two integers n and k (1 \u2264 k \u2264 n \u2264 2 \u22c5 10^5) \u2014 the number of elements in s and the desired number of elements in t, respectively.\n\nThe second line of the input contains exactly n integers s_1, s_2, ..., s_n (1 \u2264 s_i \u2264 2 \u22c5 10^5).\n\nOutput\n\nPrint k integers \u2014 the elements of array t such that you can cut out maximum possible number of copies of this array from s. If there are multiple answers, print any of them. The required array t can contain duplicate elements. All the elements of t (t_1, t_2, ..., t_k) should satisfy the following condition: 1 \u2264 t_i \u2264 2 \u22c5 10^5.\n\nExamples\n\nInput\n\n\n7 3\n1 2 3 2 4 3 1\n\n\nOutput\n\n\n1 2 3 \n\n\nInput\n\n\n10 4\n1 3 1 3 10 3 7 7 12 3\n\n\nOutput\n\n\n7 3 1 3\n\n\nInput\n\n\n15 2\n1 2 1 1 1 2 1 1 2 1 2 1 1 1 1\n\n\nOutput\n\n\n1 1 \n\nNote\n\nThe first example is described in the problem statement.\n\nIn the second example the only answer is [7, 3, 1, 3] and any its permutations. It can be shown that you cannot choose any other array such that the maximum number of copies you can cut out would be equal to 2.\n\nIn the third example the array t can be cut out 5 times.", "public_tests": { "input": [ "7 3\n1 2 3 2 4 3 1\n", "15 2\n1 2 1 1 1 2 1 1 2 1 2 1 1 1 1\n", "10 4\n1 3 1 3 10 3 7 7 12 3\n" ], "output": [ "1 2 3\n", "1 1\n", "1 3 3 7 " ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1077, "cf_index": "D", "cf_points": 0.0, "cf_rating": 1600, "cf_tags": [ "binary search", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 3, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "from collections import*\nR=lambda:map(int,input().split())\nn,k=R()\nprint(*(x for _,x in sorted((m//i,l)for\nl,m in Counter(R()).items()for i in range(1,m+1))[-k:]))", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1077/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "Binary Search||" ] }, "1223c": { "name": "1223_C. Save the Nature", "description": "You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!\n\nYou have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose:\n\n * The x\\% of the price of each the a-th sold ticket (a-th, 2a-th, 3a-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources. \n * The y\\% of the price of each the b-th sold ticket (b-th, 2b-th, 3b-th and so on) in the order you chose is aimed for pollution abatement. \n\n\n\nIf the ticket is in both programs then the (x + y) \\% are used for environmental activities. Also, it's known that all prices are multiples of 100, so there is no need in any rounding.\n\nFor example, if you'd like to sell tickets with prices [400, 100, 300, 200] and the cinema pays 10\\% of each 2-nd sold ticket and 20\\% of each 3-rd sold ticket, then arranging them in order [100, 200, 300, 400] will lead to contribution equal to 100 \u22c5 0 + 200 \u22c5 0.1 + 300 \u22c5 0.2 + 400 \u22c5 0.1 = 120. But arranging them in order [100, 300, 400, 200] will lead to 100 \u22c5 0 + 300 \u22c5 0.1 + 400 \u22c5 0.2 + 200 \u22c5 0.1 = 130.\n\nNature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least k in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least k.\n\nInput\n\nThe first line contains a single integer q (1 \u2264 q \u2264 100) \u2014 the number of independent queries. Each query consists of 5 lines.\n\nThe first line of each query contains a single integer n (1 \u2264 n \u2264 2 \u22c5 10^5) \u2014 the number of tickets.\n\nThe second line contains n integers p_1, p_2, ..., p_n (100 \u2264 p_i \u2264 10^9, p_i mod 100 = 0) \u2014 the corresponding prices of tickets.\n\nThe third line contains two integers x and a (1 \u2264 x \u2264 100, x + y \u2264 100, 1 \u2264 a \u2264 n) \u2014 the parameters of the first program.\n\nThe fourth line contains two integers y and b (1 \u2264 y \u2264 100, x + y \u2264 100, 1 \u2264 b \u2264 n) \u2014 the parameters of the second program.\n\nThe fifth line contains single integer k (1 \u2264 k \u2264 10^{14}) \u2014 the required total contribution.\n\nIt's guaranteed that the total number of tickets per test doesn't exceed 2 \u22c5 10^5.\n\nOutput\n\nPrint q integers \u2014 one per query. \n\nFor each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least k if you can sell tickets in any order.\n\nIf the total contribution can not be achieved selling all the tickets, print -1.\n\nExample\n\nInput\n\n\n4\n1\n100\n50 1\n49 1\n100\n8\n100 200 100 200 100 200 100 100\n10 2\n15 3\n107\n3\n1000000000 1000000000 1000000000\n50 1\n50 1\n3000000000\n5\n200 100 100 100 100\n69 5\n31 2\n90\n\n\nOutput\n\n\n-1\n6\n3\n4\n\nNote\n\nIn the first query the total contribution is equal to 50 + 49 = 99 < 100, so it's impossible to gather enough money.\n\nIn the second query you can rearrange tickets in a following way: [100, 100, 200, 200, 100, 200, 100, 100] and the total contribution from the first 6 tickets is equal to 100 \u22c5 0 + 100 \u22c5 0.1 + 200 \u22c5 0.15 + 200 \u22c5 0.1 + 100 \u22c5 0 + 200 \u22c5 0.25 = 10 + 30 + 20 + 50 = 110.\n\nIn the third query the full price of each ticket goes to the environmental activities.\n\nIn the fourth query you can rearrange tickets as [100, 200, 100, 100, 100] and the total contribution from the first 4 tickets is 100 \u22c5 0 + 200 \u22c5 0.31 + 100 \u22c5 0 + 100 \u22c5 0.31 = 62 + 31 = 93.", "public_tests": { "input": [ "4\n1\n100\n50 1\n49 1\n100\n8\n100 200 100 200 100 200 100 100\n10 2\n15 3\n107\n3\n1000000000 1000000000 1000000000\n50 1\n50 1\n3000000000\n5\n200 100 100 100 100\n69 5\n31 2\n90\n" ], "output": [ "-1\n6\n3\n4\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 1223, "cf_index": "C", "cf_points": 1500.0, "cf_rating": 1600, "cf_tags": [ "binary search", "greedy" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "import math\nR=lambda:[*map(int,input().split())]\nf=lambda m:p[m//b]*(y-x)+(p[m//c]+p[m//b+m//a-m//c])*x<100*k\nq,=R()\nfor _ in[0]*q:\n l=R()+[0];p=[0]+sorted(R())[::-1]\n for i in range(l[0]):p[i+1]+=p[i]\n (x,a),(y,b)=sorted((R(),R()));c=a*b//math.gcd(a,b);k,=R()\n while l[0]-l[1]>1:m=sum(l)//2;l[f(m)]=m\n print((l[0],-1)[f(l[0])])", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1223/C", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "Binary Search||", "Sorting||" ] }, "1468d": { "name": "1468_D. Firecrackers", "description": "Consider a long corridor which can be divided into n square cells of size 1 \u00d7 1. These cells are numbered from 1 to n from left to right.\n\nThere are two people in this corridor, a hooligan and a security guard. Initially, the hooligan is in the a-th cell, the guard is in the b-th cell (a \u2260 b). \n\n One of the possible situations. The corridor consists of 7 cells, the hooligan is in the 3-rd cell, the guard is in the 6-th (n = 7, a = 3, b = 6).\n\nThere are m firecrackers in the hooligan's pocket, the i-th firecracker explodes in s_i seconds after being lit.\n\nThe following events happen each second (sequentially, exactly in the following order):\n\n 1. firstly, the hooligan either moves into an adjacent cell (from the cell i, he can move to the cell (i + 1) or to the cell (i - 1), and he cannot leave the corridor) or stays in the cell he is currently. If the hooligan doesn't move, he can light one of his firecrackers and drop it. The hooligan can't move into the cell where the guard is; \n 2. secondly, some firecrackers that were already dropped may explode. Formally, if the firecracker j is dropped on the T-th second, then it will explode on the (T + s_j)-th second (for example, if a firecracker with s_j = 2 is dropped on the 4-th second, it explodes on the 6-th second); \n 3. finally, the guard moves one cell closer to the hooligan. If the guard moves to the cell where the hooligan is, the hooligan is caught. \n\n\n\nObviously, the hooligan will be caught sooner or later, since the corridor is finite. His goal is to see the maximum number of firecrackers explode before he is caught; that is, he will act in order to maximize the number of firecrackers that explodes before he is caught.\n\nYour task is to calculate the number of such firecrackers, if the hooligan acts optimally.\n\nInput\n\nThe first line contains one integer t (1 \u2264 t \u2264 1000) \u2014 the number of test cases.\n\nEach test case consists of two lines. The first line contains four integers n, m, a and b (2 \u2264 n \u2264 10^9; 1 \u2264 m \u2264 2 \u22c5 10^5; 1 \u2264 a, b \u2264 n; a \u2260 b) \u2014 the size of the corridor, the number of firecrackers, the initial location of the hooligan and the initial location of the guard, respectively.\n\nThe second line contains m integers s_1, s_2, ..., s_m (1 \u2264 s_i \u2264 10^9), where s_i is the time it takes the i-th firecracker to explode after it is lit.\n\nIt is guaranteed that the sum of m over all test cases does not exceed 2 \u22c5 10^5.\n\nOutput\n\nFor each test case, print one integer \u2014 the maximum number of firecrackers that the hooligan can explode before he is caught.\n\nExample\n\nInput\n\n\n3\n7 2 3 6\n1 4\n7 2 3 6\n5 1\n7 2 3 6\n4 4\n\n\nOutput\n\n\n2\n1\n1\n\nNote\n\nIn the first test case, the hooligan should act, for example, as follows:\n\n * second 1: drop the second firecracker, so it will explode on the 5-th second. The guard moves to the cell 5; \n * second 2: move to the cell 2. The guard moves to the cell 4; \n * second 3: drop the first firecracker, so it will explode on the 4-th second. The guard moves to the cell 3; \n * second 4: move to the cell 1. The first firecracker explodes. The guard moves to the cell 2; \n * second 5: stay in the cell 1. The second firecracker explodes. The guard moves to the cell 1 and catches the hooligan. ", "public_tests": { "input": [ "3\n7 2 3 6\n1 4\n7 2 3 6\n5 1\n7 2 3 6\n4 4\n" ], "output": [ "\n2\n1\n1\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1468, "cf_index": "D", "cf_points": 0.0, "cf_rating": 1700, "cf_tags": [ "binary search", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 4, "nanos": 0 }, "memory_limit_bytes": 512000000, "solution": "for _ in range(int(input())):\n l1,l2 = (list(map(int,input().split(' '))) for i in range(2))\n l2 = sorted(l2)[::-1]\n if l1[2]>l1[3]:r=l1[0]-l1[2]\n else:r=l1[2]-1 \n j,k,i,ans = abs(l1[2]-l1[3])-1,0,0,0\n while k", "public_tests": { "input": [ "9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8\n", "7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6\n" ], "output": [ "9\n", "6\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 700, "cf_index": "B", "cf_points": 1000.0, "cf_rating": 1800, "cf_tags": [ "dfs and similar", "dp", "graphs", "trees" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 3, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "#include \nusing namespace std;\nconst int MAX = 2e5 + 9;\nvector g[MAX];\nlong long b[MAX], n, m, ans;\nvoid dfs(int v, int p = -1) {\n for (auto u : g[v])\n if (u != p) dfs(u, v), b[v] += b[u];\n ans += min(b[v], 2 * m - b[v]);\n}\nint main() {\n cin >> n >> m;\n for (int i = 0, x; i < 2 * m; i++) cin >> x, b[x] = 1;\n for (int i = 1, v, u; i < n; i++)\n cin >> v >> u, g[v].push_back(u), g[u].push_back(v);\n dfs(1);\n cout << ans;\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/700/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "DFS||" ] }, "1288d": { "name": "1288_D. Minimax Problem", "description": "You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.\n\nYou have to choose two arrays a_i and a_j (1 \u2264 i, j \u2264 n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k \u2208 [1, m] b_k = max(a_{i, k}, a_{j, k}).\n\nYour goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.\n\nInput\n\nThe first line contains two integers n and m (1 \u2264 n \u2264 3 \u22c5 10^5, 1 \u2264 m \u2264 8) \u2014 the number of arrays and the number of elements in each array, respectively.\n\nThen n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 \u2264 a_{x, y} \u2264 10^9).\n\nOutput\n\nPrint two integers i and j (1 \u2264 i, j \u2264 n, it is possible that i = j) \u2014 the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.\n\nExample\n\nInput\n\n\n6 5\n5 0 3 1 2\n1 8 9 1 3\n1 2 3 4 5\n9 1 0 3 7\n2 3 0 6 3\n6 4 1 7 0\n\n\nOutput\n\n\n1 5", "public_tests": { "input": [ "6 5\n5 0 3 1 2\n1 8 9 1 3\n1 2 3 4 5\n9 1 0 3 7\n2 3 0 6 3\n6 4 1 7 0\n" ], "output": [ "1 5\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1288, "cf_index": "D", "cf_points": 0.0, "cf_rating": 2000, "cf_tags": [ "binary search", "bitmasks", "dp" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 5, "nanos": 0 }, "memory_limit_bytes": 512000000, "solution": "import math as mt\nimport sys\ninput=sys.stdin.readline\nI=lambda:list(map(int,input().split()))\nn,m=I()\na=[I() for i in range(n)]\nans=[]\nlo=0\nhi=10**9\ndef vanguda(mid: int) -> bool:\n global ans\n f={}\n for i in range(n):\n bi=0\n for j in range(m):\n if a[i][j]>=mid:\n bi+=1\n bi<<=1\n f[bi>>1]=i\n for aa,bb in f.items():\n for cc,dd in f.items():\n if aa|cc==(2**m-1):\n ans =bb+1,dd+1\n return True\n return False\n\nwhile lo<=hi:\n\tmid=(lo+hi)//2\n\tif vanguda(mid):\n\t\tlo=mid+1\n\telse:\n\t\thi=mid-1\nprint(*ans)\n\n\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1288/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "Binary Search||", "Bitmasks||" ] }, "fennec vs. snuke078": { "name": "p03662 AtCoder Regular Contest 078 - Fennec VS. Snuke", "description": "Fennec and Snuke are playing a board game.\n\nOn the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.\n\nInitially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored. Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell. More specifically, each player performs the following action in her/his turn:\n\n* Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.\n* Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.\n\n\n\nA player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.\n\nConstraints\n\n* 2 \\leq N \\leq 10^5\n* 1 \\leq a_i, b_i \\leq N\n* The given graph is a tree.\n\nInput\n\nInput is given from Standard Input in the following format:\n\n\nN\na_1 b_1\n:\na_{N-1} b_{N-1}\n\n\nOutput\n\nIf Fennec wins, print `Fennec`; if Snuke wins, print `Snuke`.\n\nExamples\n\nInput\n\n7\n3 6\n1 2\n3 1\n7 4\n5 7\n1 4\n\n\nOutput\n\nFennec\n\n\nInput\n\n4\n1 4\n4 2\n2 3\n\n\nOutput\n\nSnuke", "public_tests": { "input": [ "4\n1 4\n4 2\n2 3", "7\n3 6\n1 2\n3 1\n7 4\n5 7\n1 4" ], "output": [ "Snuke", "Fennec" ] }, "source": 5, "difficulty": 0, "cf_contest_id": 0, "cf_index": "", "cf_points": 0.0, "cf_rating": 0, "cf_tags": [ "" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 268435456, "solution": "from collections import*\nn=input();G=[[]for d in[deque([1,n])]*-~n]\nfor C in[[0,1]+[0]*(n-2)+[2]]*~-n:a,b=map(int,raw_input().split());G[a]+=b,;G[b]+=a,\nwhile d:\n v=d.popleft()\n for t in G[v]:\n if C[t]<1:C[t]=C[v];d+=t,\nprint[\"Snuke\",\"Fennec\"][n<2*C.count(1)]", "prob_source": "atcoder", "url": "https://atcoder.jp/contests/arc078/tasks/arc078_b", "anno_source": "usaco_guide", "anno_tag": [ "Trees||", "Conclusion||", "Games||" ] }, "412d": { "name": "412_D. Giving Awards", "description": "The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.\n\nToday is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.\n\nHowever, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.\n\nInput\n\nThe first line contains space-separated integers n and m \u2014 the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1 \u2264 ai, bi \u2264 n; ai \u2260 bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n.\n\nIt is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.\n\nOutput\n\nPrint -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on.\n\nIf there are multiple correct orders, you are allowed to print any of them.\n\nExamples\n\nInput\n\n2 1\n1 2\n\n\nOutput\n\n2 1 \n\n\nInput\n\n3 3\n1 2\n2 3\n3 1\n\n\nOutput\n\n2 1 3 ", "public_tests": { "input": [ "2 1\n1 2\n", "3 3\n1 2\n2 3\n3 1\n" ], "output": [ "2 1 ", "3 2 1 " ] }, "source": 2, "difficulty": 10, "cf_contest_id": 412, "cf_index": "D", "cf_points": 2000.0, "cf_rating": 2000, "cf_tags": [ "dfs and similar" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n,m = map(int,input().split())\ng = [set() for i in range(n)]\nfor i in range(m):\n a,b = map(int,input().split())\n g[a-1].add(b-1)\nc = [0]*n\nfor i in range(n):\n c[i]=i\nfor i in range(n):\n j=i\n while j>0 and c[j] in g[c[j-1]]:\n c[j],c[j-1]=c[j-1],c[j]\n j-=1\nfor i in c:\n print(i+1,end=' ')", "prob_source": "codeforces", "url": "https://codeforces.com/contest/412/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "DFS||" ] }, "1428e": { "name": "1428_E. Carrots for Rabbits", "description": "There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, \u2026, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers.\n\nBig carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2.\n\nHelp Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.\n\nInput\n\nThe first line contains two integers n and k (1 \u2264 n \u2264 k \u2264 10^5): the initial number of carrots and the number of rabbits.\n\nThe next line contains n integers a_1, a_2, \u2026, a_n (1 \u2264 a_i \u2264 10^6): lengths of carrots.\n\nIt is guaranteed that the sum of a_i is at least k.\n\nOutput\n\nOutput one integer: the minimum sum of time taken for rabbits to eat carrots.\n\nExamples\n\nInput\n\n\n3 6\n5 3 1\n\n\nOutput\n\n\n15\n\n\nInput\n\n\n1 4\n19\n\n\nOutput\n\n\n91\n\nNote\n\nFor the first test, the optimal sizes of carrots are \\{1,1,1,2,2,2\\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15\n\nFor the second test, the optimal sizes of carrots are \\{4,5,5,5\\}. The time taken is 4^2+5^2+5^2+5^2=91.", "public_tests": { "input": [ "1 4\n19\n", "3 6\n5 3 1\n" ], "output": [ "91\n", "15\n" ] }, "source": 2, "difficulty": 11, "cf_contest_id": 1428, "cf_index": "E", "cf_points": 1750.0, "cf_rating": 2200, "cf_tags": [ "binary search", "data structures", "greedy", "math", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "from heapq import *\nZ=lambda:map(int,input().split())\nV=lambda n,k:(n%k)*(n//k+1)**2+(k-n%k)*(n//k)**2\nD=lambda n,k:V(n,k)-V(n,k+1)\nn,k=Z();w=k-n+1;N=n*w;a=[*Z()];s=sum(i*i for i in a);d=0\nb=[-D(a[i],1)*N-i for i in range(n)];heapify(b)\nfor i in range(w-1):\n v=-heappop(b);d+=v//N;i=v%n;l=(v//n)%w\n heappush(b,-D(a[i],l+2)*N-(l+1)*n-i)\nprint(s-d)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1428/problem/E", "anno_source": "usaco_guide", "anno_tag": [ "Conclusion||", "math||", "Priority queue||" ] }, "920e": { "name": "920_E. Connected Components?", "description": "You are given an undirected graph consisting of n vertices and edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.\n\nYou have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule.\n\nInput\n\nThe first line contains two integers n and m (1 \u2264 n \u2264 200000, ).\n\nThen m lines follow, each containing a pair of integers x and y (1 \u2264 x, y \u2264 n, x \u2260 y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. \n\nOutput\n\nFirstly print k \u2014 the number of connected components in this graph.\n\nThen print k integers \u2014 the sizes of components. You should output these integers in non-descending order.\n\nExample\n\nInput\n\n5 5\n1 2\n3 4\n3 2\n4 2\n2 5\n\n\nOutput\n\n2\n1 4 ", "public_tests": { "input": [ "5 5\n1 2\n3 4\n3 2\n4 2\n2 5\n" ], "output": [ "2\n1 4 \n" ] }, "source": 2, "difficulty": 11, "cf_contest_id": 920, "cf_index": "E", "cf_points": 0.0, "cf_rating": 2100, "cf_tags": [ "data structures", "dfs and similar", "dsu", "graphs" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n, m = map(int, input().split())\n\nbar = [{i} for i in range(n)]\nfor i in range(m):\n\tu, v = map(int, input().split())\n\tu, v = u - 1, v - 1\n\tbar[u].add(v)\n\tbar[v].add(u)\n\nnodes = set(range(n))\nans = []\n\nwhile (nodes):\n\tu = next(iter(nodes))\n\tnodes.remove(u)\n\tstk = [u]\n\tcnt = 1\n\twhile (stk):\n\t\tv = stk.pop()\n\t\ts = nodes - bar[v]\n\t\tcnt += len(s)\n\t\tstk.extend(s)\n\t\tnodes &= bar[v]\n\tans.append(cnt)\n\nans.sort()\nprint(len(ans))\nprint(' '.join(map(str, ans)))", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/920/E", "anno_source": "usaco_guide", "anno_tag": [ "Sorted Set||", "Graph Traversal||", "DFS||" ] }, "862b": { "name": "862_B. Mahmoud and Ehab and the bipartiteness", "description": "Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.\n\nA tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.\n\nDr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?\n\nA loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .\n\nInput\n\nThe first line of input contains an integer n \u2014 the number of nodes in the tree (1 \u2264 n \u2264 105).\n\nThe next n - 1 lines contain integers u and v (1 \u2264 u, v \u2264 n, u \u2260 v) \u2014 the description of the edges of the tree.\n\nIt's guaranteed that the given graph is a tree. \n\nOutput\n\nOutput one integer \u2014 the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.\n\nExamples\n\nInput\n\n3\n1 2\n1 3\n\n\nOutput\n\n0\n\n\nInput\n\n5\n1 2\n2 3\n3 4\n4 5\n\n\nOutput\n\n2\n\nNote\n\nTree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)\n\nBipartite graph definition: \n\nIn the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.\n\nIn the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5). ", "public_tests": { "input": [ "3\n1 2\n1 3\n", "5\n1 2\n2 3\n3 4\n4 5\n" ], "output": [ "0\n", "2\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 862, "cf_index": "B", "cf_points": 1000.0, "cf_rating": 1300, "cf_tags": [ "dfs and similar", "graphs", "trees" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "n=input();l=[1]+[0]*n;d=[[]for _ in range(n)];c=[0]\nfor _ in range(n-1):\n a,b=map(int,raw_input().split());d[a-1]+=[b-1];d[b-1]+=[a-1]\nwhile c:\n x=c.pop()\n for y in d[x]:\n if not l[y]:\n c+=[y];l[y]=-l[x]\nr=l.count(1);print(r*(n-r)-n+1)", "prob_source": "codeforces", "url": "https://codeforces.com/contest/862/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "Bipartite Graph||", "Graph Traversal||" ] }, "1176e": { "name": "1176_E. Cover it!", "description": "You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.\n\nYour task is to choose at most \u230an/2\u230b vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.\n\nIt is guaranteed that the answer exists. If there are multiple answers, you can print any.\n\nYou will be given multiple independent queries to answer.\n\nInput\n\nThe first line contains a single integer t (1 \u2264 t \u2264 2 \u22c5 10^5) \u2014 the number of queries.\n\nThen t queries follow.\n\nThe first line of each query contains two integers n and m (2 \u2264 n \u2264 2 \u22c5 10^5, n - 1 \u2264 m \u2264 min(2 \u22c5 10^5, (n(n-1))/(2))) \u2014 the number of vertices and the number of edges, respectively.\n\nThe following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 \u2264 v_i, u_i \u2264 n, u_i \u2260 v_i), which are the indices of vertices connected by the edge.\n\nThere are no self-loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i \u2260 u_i is satisfied. It is guaranteed that the given graph is connected.\n\nIt is guaranteed that \u2211 m \u2264 2 \u22c5 10^5 over all queries.\n\nOutput\n\nFor each query print two lines.\n\nIn the first line print k (1 \u2264 \u230an/2\u230b) \u2014 the number of chosen vertices.\n\nIn the second line print k distinct integers c_1, c_2, ..., c_k in any order, where c_i is the index of the i-th chosen vertex.\n\nIt is guaranteed that the answer exists. If there are multiple answers, you can print any.\n\nExample\n\nInput\n\n\n2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6\n\n\nOutput\n\n\n2\n1 3\n3\n4 3 6\n\nNote\n\nIn the first query any vertex or any pair of vertices will suffice.\n\n\n\nNote that you don't have to minimize the number of chosen vertices. In the second query two vertices can be enough (vertices 2 and 4) but three is also ok.\n\n", "public_tests": { "input": [ "2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6\n" ], "output": [ "1\n1 \n3\n3 4 6 \n" ] }, "source": 2, "difficulty": 11, "cf_contest_id": 1176, "cf_index": "E", "cf_points": 0.0, "cf_rating": 1700, "cf_tags": [ "dfs and similar", "dsu", "graphs", "shortest paths", "trees" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "kk=lambda:map(int,input().split())\nk2=lambda:map(lambda x:int(x)-1, input().split())\nll=lambda:list(kk())\nn,m=kk()\nneighs=[[] for _ in range(n)]\nfor _ in range(m):\n\tu,v=k2()\n\tneighs[u].append(v)\n\tneighs[v].append(u)\nm=v = 0\nfor i,ls in enumerate(neighs):\n\tif len(ls) > m: m,v = len(ls),i\nseen = {v}\nnex = [v]\nwhile nex:\n\tnewn = []\n\tfor no in nex:\n\t\tfor nei in neighs[no]:\n\t\t\tif nei not in seen:\n\t\t\t\tseen.add(nei)\n\t\t\t\tprint(nei+1, no+1)\n\t\t\t\tnewn.append(nei)\n\tnex = newn", "prob_source": "codeforces", "url": "https://codeforces.com/problemset/problem/1176/E", "anno_source": "usaco_guide", "anno_tag": [ "Bipartite Graph||", "Graph Traversal||" ] }, "1387a": { "name": "1387_A. Graph", "description": "You are given an undirected graph where each edge has one of two colors: black or red.\n\nYour task is to assign a real number to each node so that: \n\n * for each black edge the sum of values at its endpoints is 1; \n * for each red edge the sum of values at its endpoints is 2; \n * the sum of the absolute values of all assigned numbers is the smallest possible. \n\n\n\nOtherwise, if it is not possible, report that there is no feasible assignment of the numbers.\n\nInput\n\nThe first line contains two integers N (1 \u2264 N \u2264 100 000) and M (0 \u2264 M \u2264 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, \u2026, N.\n\nThe next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 \u2264 a, b \u2264 N) with color c (1 denotes black, 2 denotes red).\n\nOutput\n\nIf there is a solution, the first line should contain the word \"YES\" and the second line should contain N space-separated numbers. For each i (1 \u2264 i \u2264 N), the i-th number should be the number assigned to the node i.\n\nOutput should be such that: \n\n * the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6}; \n * the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}. \n\n\n\nIf there are several valid solutions, output any of them.\n\nIf there is no solution, the only line should contain the word \"NO\".\n\nScoring\n\nSubtasks: \n\n 1. (5 points) N \u2264 5, M \u2264 14 \n 2. (12 points) N \u2264 100 \n 3. (17 points) N \u2264 1000 \n 4. (24 points) N \u2264 10 000 \n 5. (42 points) No further constraints \n\nExamples\n\nInput\n\n\n4 4\n1 2 1\n2 3 2\n1 3 2\n3 4 1\n\n\nOutput\n\n\nYES\n0.5 0.5 1.5 -0.5\n\n\nInput\n\n\n2 1\n1 2 1\n\n\nOutput\n\n\nYES\n0.3 0.7\n\nInput\n\n\n3 2\n1 2 2\n2 3 2\n\n\nOutput\n\n\nYES\n0 2 0\n\n\nInput\n\n\n3 4\n1 2 2\n2 2 1\n2 1 1\n1 2 2\n\n\nOutput\n\n\nNO\n\nNote\n\nNote that in the second example the solution is not unique.", "public_tests": { "input": [ "2 1\n1 2 1\n", "3 4\n1 2 2\n2 2 1\n2 1 1\n1 2 2\n", "4 4\n1 2 1\n2 3 2\n1 3 2\n3 4 1\n", "3 2\n1 2 2\n2 3 2\n" ], "output": [ "YES\n1 0 \n", "NO", "YES\n0.50 0.50 1.50 -0.50 ", "YES\n0.00 2.00 0.00 " ] }, "source": 2, "difficulty": 7, "cf_contest_id": 1387, "cf_index": "A", "cf_points": 0.0, "cf_rating": 2100, "cf_tags": [ "*special", "binary search", "dfs and similar", "dp", "math", "ternary search" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "#include \nusing namespace std;\nconst int N = 1e5 + 5;\nint n, m, tag, x, k[N], b[N], as[N];\nvector> G[N];\nvector cc;\nvoid dfs(int u) {\n cc.push_back(u);\n for (auto [v, w] : G[u]) {\n if (!k[v])\n k[v] = -k[u], b[v] = w - b[u], dfs(v);\n else if (k[u] == k[v]) {\n if (!tag)\n x = (w - b[u] - b[v]) / (k[u] + k[v]), tag = 1;\n else if ((k[u] + k[v]) * x + b[u] + b[v] != w)\n tag = -1;\n } else if (b[u] + b[v] != w)\n tag = -1;\n if (!~tag) return;\n }\n}\nint main() {\n cin >> n >> m;\n int u, v, w;\n for (int i = (1); i <= (m); i++) {\n scanf(\"%d%d%d\", &u, &v, &w), w *= 2;\n G[u].push_back({v, w}), G[v].push_back({u, w});\n }\n for (int i = (1); i <= (n); i++)\n if (!k[i]) {\n k[i] = 1, tag = 0, cc.clear(), dfs(i);\n if (tag == -1)\n puts(\"NO\"), exit(0);\n else {\n if (!tag) {\n vector t;\n for (int u : cc) t.push_back(-b[u] / k[u]);\n nth_element(t.begin(), t.begin() + t.size() / 2, t.end());\n x = t[t.size() / 2];\n }\n for (int u : cc) as[u] = k[u] * x + b[u];\n }\n }\n puts(\"YES\");\n for (int i = (1); i <= (n); i++) printf(\"%.1lf \", as[i] / 2.0);\n return 0;\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1387/problem/A", "anno_source": "usaco_guide", "anno_tag": [ "Graph Traversal||", "Median||", "DFS||" ] }, "295a": { "name": "295_A. Greg and Array", "description": "Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 \u2264 li \u2264 ri \u2264 n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.\n\nGreg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 \u2264 xi \u2264 yi \u2264 m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.\n\nNow Greg is wondering, what the array a will be after all the queries are executed. Help Greg.\n\nInput\n\nThe first line contains integers n, m, k (1 \u2264 n, m, k \u2264 105). The second line contains n integers: a1, a2, ..., an (0 \u2264 ai \u2264 105) \u2014 the initial array.\n\nNext m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 \u2264 li \u2264 ri \u2264 n), (0 \u2264 di \u2264 105).\n\nNext k lines contain the queries, the query number i is written as two integers: xi, yi, (1 \u2264 xi \u2264 yi \u2264 m).\n\nThe numbers in the lines are separated by single spaces.\n\nOutput\n\nOn a single line print n integers a1, a2, ..., an \u2014 the array after executing all the queries. Separate the printed numbers by spaces.\n\nPlease, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.\n\nExamples\n\nInput\n\n3 3 3\n1 2 3\n1 2 1\n1 3 2\n2 3 4\n1 2\n1 3\n2 3\n\n\nOutput\n\n9 18 17\n\n\nInput\n\n1 1 1\n1\n1 1 1\n1 1\n\n\nOutput\n\n2\n\n\nInput\n\n4 3 6\n1 2 3 4\n1 2 1\n2 3 2\n3 4 4\n1 2\n1 3\n2 3\n1 2\n1 3\n2 3\n\n\nOutput\n\n5 18 31 20", "public_tests": { "input": [ "3 3 3\n1 2 3\n1 2 1\n1 3 2\n2 3 4\n1 2\n1 3\n2 3\n", "1 1 1\n1\n1 1 1\n1 1\n", "4 3 6\n1 2 3 4\n1 2 1\n2 3 2\n3 4 4\n1 2\n1 3\n2 3\n1 2\n1 3\n2 3\n" ], "output": [ "9 18 17 \n", "2 \n", "5 18 31 20 \n" ] }, "source": 2, "difficulty": 7, "cf_contest_id": 295, "cf_index": "A", "cf_points": 500.0, "cf_rating": 1400, "cf_tags": [ "data structures", "implementation" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 500000000 }, "memory_limit_bytes": 256000000, "solution": "r=lambda:map(int,raw_input().split())\nn,m,k=r()\na=r()\nb=[0]*(n+1)\nB=[0]*(m+1)\nq=[r() for i in range(m)]\n\n\nfor i in range(k):\n x,y=r()\n B[x-1]+=1\n B[y]-=1\nC=0\nfor i,(x,y,d) in enumerate(q):\n C+=B[i]\n b[x-1]+=d*C\n b[y]-=d*C\nc=0\nfor i in range(n):\n c+=b[i]\n print a[i]+c,", "prob_source": "codeforces", "url": "https://codeforces.com/contest/295/problem/A", "anno_source": "usaco_guide", "anno_tag": [ "More Prefix Sums||", "Difference Array||" ] }, "816b": { "name": "816_B. Karen and Coffee", "description": "To stay woke and attentive during classes, Karen needs some coffee!\n\n\n\nKaren, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed \"The Art of the Covfefe\".\n\nShe knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between li and ri degrees, inclusive, to achieve the optimal taste.\n\nKaren thinks that a temperature is admissible if at least k recipes recommend it.\n\nKaren has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?\n\nInput\n\nThe first line of input contains three integers, n, k (1 \u2264 k \u2264 n \u2264 200000), and q (1 \u2264 q \u2264 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively.\n\nThe next n lines describe the recipes. Specifically, the i-th line among these contains two integers li and ri (1 \u2264 li \u2264 ri \u2264 200000), describing that the i-th recipe suggests that the coffee be brewed between li and ri degrees, inclusive.\n\nThe next q lines describe the questions. Each of these lines contains a and b, (1 \u2264 a \u2264 b \u2264 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.\n\nOutput\n\nFor each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.\n\nExamples\n\nInput\n\n3 2 4\n91 94\n92 97\n97 99\n92 94\n93 97\n95 96\n90 100\n\n\nOutput\n\n3\n3\n0\n4\n\n\nInput\n\n2 1 1\n1 1\n200000 200000\n90 100\n\n\nOutput\n\n0\n\nNote\n\nIn the first test case, Karen knows 3 recipes.\n\n 1. The first one recommends brewing the coffee between 91 and 94 degrees, inclusive. \n 2. The second one recommends brewing the coffee between 92 and 97 degrees, inclusive. \n 3. The third one recommends brewing the coffee between 97 and 99 degrees, inclusive. \n\n\n\nA temperature is admissible if at least 2 recipes recommend it.\n\nShe asks 4 questions.\n\nIn her first question, she wants to know the number of admissible integer temperatures between 92 and 94 degrees, inclusive. There are 3: 92, 93 and 94 degrees are all admissible.\n\nIn her second question, she wants to know the number of admissible integer temperatures between 93 and 97 degrees, inclusive. There are 3: 93, 94 and 97 degrees are all admissible.\n\nIn her third question, she wants to know the number of admissible integer temperatures between 95 and 96 degrees, inclusive. There are none.\n\nIn her final question, she wants to know the number of admissible integer temperatures between 90 and 100 degrees, inclusive. There are 4: 92, 93, 94 and 97 degrees are all admissible.\n\nIn the second test case, Karen knows 2 recipes.\n\n 1. The first one, \"wikiHow to make Cold Brew Coffee\", recommends brewing the coffee at exactly 1 degree. \n 2. The second one, \"What good is coffee that isn't brewed at at least 36.3306 times the temperature of the surface of the sun?\", recommends brewing the coffee at exactly 200000 degrees. \n\n\n\nA temperature is admissible if at least 1 recipe recommends it.\n\nIn her first and only question, she wants to know the number of admissible integer temperatures that are actually reasonable. There are none.", "public_tests": { "input": [ "3 2 4\n91 94\n92 97\n97 99\n92 94\n93 97\n95 96\n90 100\n", "2 1 1\n1 1\n200000 200000\n90 100\n" ], "output": [ "3\n3\n0\n4\n", "0\n" ] }, "source": 2, "difficulty": 8, "cf_contest_id": 816, "cf_index": "B", "cf_points": 1000.0, "cf_rating": 1400, "cf_tags": [ "binary search", "data structures", "implementation" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 500000000 }, "memory_limit_bytes": 512000000, "solution": "l=lambda:map(int,raw_input().split())\nn, k, q=l()\nf=[0]*200003\nfor x in range(n):\n t1,t2=l()\n f[t1]+=1\n f[t2+1]-=1\ns=[0]*200003\ncur,cnt=0,0\nfor i,v in enumerate(f):\n cur+=v\n if cur>=k:\n cnt+=1\n s[i]=cnt\nfor _ in range(q):\n a,b=l()\n print s[b]-s[a-1]", "prob_source": "codeforces", "url": "https://codeforces.com/contest/816/problem/B", "anno_source": "usaco_guide", "anno_tag": [ "More Prefix Sums||", "Difference Array||" ] }, "276c": { "name": "276_C. Little Girl and Maximum Sum", "description": "The little girl loves the problems on array queries very much.\n\nOne day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 \u2264 l_i \u2264 r_i \u2264 n). You need to find for each query the sum of elements of the array with indexes from l_i to r_i, inclusive.\n\nThe little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.\n\nInput\n\nThe first line contains two space-separated integers n (1 \u2264 n \u2264 2\u22c510^5) and q (1 \u2264 q \u2264 2\u22c510^5) \u2014 the number of elements in the array and the number of queries, correspondingly.\n\nThe next line contains n space-separated integers a_i (1 \u2264 a_i \u2264 2\u22c510^5) \u2014 the array elements.\n\nEach of the following q lines contains two space-separated integers l_i and r_i (1 \u2264 l_i \u2264 r_i \u2264 n) \u2014 the i-th query.\n\nOutput\n\nIn a single line print, a single integer \u2014 the maximum sum of query replies after the array elements are reordered.\n\nPlease, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.\n\nExamples\n\nInput\n\n3 3\n5 3 2\n1 2\n2 3\n1 3\n\n\nOutput\n\n25\n\n\nInput\n\n5 3\n5 2 4 1 3\n1 5\n2 3\n2 3\n\n\nOutput\n\n33", "public_tests": { "input": [ "5 3\n5 2 4 1 3\n1 5\n2 3\n2 3\n", "3 3\n5 3 2\n1 2\n2 3\n1 3\n" ], "output": [ "33\n", "25\n" ] }, "source": 2, "difficulty": 9, "cf_contest_id": 276, "cf_index": "C", "cf_points": 1500.0, "cf_rating": 1500, "cf_tags": [ "data structures", "greedy", "implementation", "sortings" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "R=lambda:map(int,raw_input().split());n,q=R();a=sorted(R());b=[0]*n\nfor i in range(q):\n\tx,y=R();b[x-1]+=1\n\tif y\n\nThis is an interactive task\n\nWilliam has a certain sequence of integers a_1, a_2, ..., a_n in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than 2 \u22c5 n of the following questions:\n\n * What is the result of a [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of two items with indices i and j (i \u2260 j) \n * What is the result of a [bitwise OR](https://en.wikipedia.org/wiki/Bitwise_operation#OR) of two items with indices i and j (i \u2260 j) \n\n\n\nYou can ask William these questions and you need to find the k-th smallest number of the sequence.\n\nFormally the k-th smallest number is equal to the number at the k-th place in a 1-indexed array sorted in non-decreasing order. For example in array [5, 3, 3, 10, 1] 4th smallest number is equal to 5, and 2nd and 3rd are 3.\n\nInput\n\nIt is guaranteed that for each element in a sequence the condition 0 \u2264 a_i \u2264 10^9 is satisfied.\n\nInteraction\n\nIn the first line you will be given two integers n and k (3 \u2264 n \u2264 10^4, 1 \u2264 k \u2264 n), which are the number of items in the sequence a and the number k.\n\nAfter that, you can ask no more than 2 \u22c5 n questions (not including the \"finish\" operation).\n\nEach line of your output may be of one of the following types: \n\n * \"or i j\" (1 \u2264 i, j \u2264 n, i \u2260 j), where i and j are indices of items for which you want to calculate the bitwise OR. \n * \"and i j\" (1 \u2264 i, j \u2264 n, i \u2260 j), where i and j are indices of items for which you want to calculate the bitwise AND. \n * \"finish res\", where res is the kth smallest number in the sequence. After outputting this line the program execution must conclude. \n\n\n\nIn response to the first two types of queries, you will get an integer x, the result of the operation for the numbers you have selected.\n\nAfter outputting a line do not forget to output a new line character and flush the output buffer. Otherwise you will get the \"Idleness limit exceeded\". To flush the buffer use:\n\n * fflush(stdout) in C++ \n * System.out.flush() in Java \n * stdout.flush() in Python \n * flush(output) in Pascal \n * for other languages refer to documentation \n\n\n\nIf you perform an incorrect query the response will be -1. After receiving response -1 you must immediately halt your program in order to receive an \"Incorrect answer\" verdict.\n\nHacking\n\nTo perform a hack you will need to use the following format:\n\nThe first line must contain two integers n and k (3 \u2264 n \u2264 10^4, 1 \u2264 k \u2264 n), which are the number of items in the sequence a and the number k.\n\nThe second line must contain n integers a_1, a_2, ..., a_n (0 \u2264 a_i \u2264 10^9), the sequence a.\n\nExample\n\nInput\n\n\n7 6\n\n2\n\n7\n\nOutput\n\n\nand 2 5\n\nor 5 6\n\nfinish 5\n\nNote\n\nIn the example, the hidden sequence is [1, 6, 4, 2, 3, 5, 4].\n\nBelow is the interaction in the example.\n\nQuery (contestant's program)| Response (interactor)| Notes \n---|---|--- \nand 2 5| 2| a_2=6, a_5=3. Interactor returns bitwise AND of the given numbers. \nor 5 6| 7| a_5=3, a_6=5. Interactor returns bitwise OR of the given numbers. \nfinish 5| | 5 is the correct answer. Note that you must find the value and not the index of the kth smallest number.", "public_tests": { "input": [ "7 6\n\n2\n\n7" ], "output": [ "and 1 2\nor 1 2\nand 1 3\nor 1 3\nand 2 3\nor 2 3\nand 1 4\nor 1 4\nand 1 5\nor 1 5\nand 1 6\nor 1 6\nand 1 7\nor 1 7\nfinish 7\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1556, "cf_index": "D", "cf_points": 1500.0, "cf_rating": 1800, "cf_tags": [ "bitmasks", "constructive algorithms", "interactive", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "#include \nusing namespace std;\nlong long a[10005];\nlong long getsum(long long q, long long r) {\n cout << \"and \" << q << \" \" << r << endl;\n long long p, t;\n cin >> p;\n cout << \"or \" << q << \" \" << r << endl;\n cin >> t;\n return p + t;\n}\nsigned main() {\n long long n, k;\n cin >> n >> k;\n long long x = getsum(1, 2), y = getsum(2, 3), z = getsum(1, 3);\n long long s = (x + y + z) / 2;\n a[1] = s - y, a[2] = s - z, a[3] = s - x;\n for (long long i = 4; i <= n; i++) {\n a[i] = getsum(1, i) - a[1];\n }\n sort(a + 1, a + n + 1);\n cout << \"finish \" << a[k];\n return 0;\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1556/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Bitwise||" ] }, "1338a": { "name": "1338_A. Powered Addition", "description": "You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:\n\n * Select some distinct indices i_{1}, i_{2}, \u2026, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{x-1} for j = 1, 2, \u2026, k. Note that you are allowed to not select any indices at all.\n\n\n\nYou have to make a nondecreasing as fast as possible. Find the smallest number T such that you can make the array nondecreasing after at most T seconds.\n\nArray a is nondecreasing if and only if a_{1} \u2264 a_{2} \u2264 \u2026 \u2264 a_{n}.\n\nYou have to answer t independent test cases.\n\nInput\n\nThe first line contains a single integer t (1 \u2264 t \u2264 10^{4}) \u2014 the number of test cases.\n\nThe first line of each test case contains single integer n (1 \u2264 n \u2264 10^{5}) \u2014 the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}.\n\nThe second line of each test case contains n integers a_{1}, a_{2}, \u2026, a_{n} (-10^{9} \u2264 a_{i} \u2264 10^{9}).\n\nOutput\n\nFor each test case, print the minimum number of seconds in which you can make a nondecreasing.\n\nExample\n\nInput\n\n\n3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4\n\n\nOutput\n\n\n2\n0\n3\n\nNote\n\nIn the first test case, if you select indices 3, 4 at the 1-st second and 4 at the 2-nd second, then a will become [1, 7, 7, 8]. There are some other possible ways to make a nondecreasing in 2 seconds, but you can't do it faster.\n\nIn the second test case, a is already nondecreasing, so answer is 0.\n\nIn the third test case, if you do nothing at first 2 seconds and select index 2 at the 3-rd second, a will become [0, 0].", "public_tests": { "input": [ "3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4\n" ], "output": [ "2\n0\n3\n" ] }, "source": 2, "difficulty": 7, "cf_contest_id": 1338, "cf_index": "A", "cf_points": 500.0, "cf_rating": 1500, "cf_tags": [ "greedy", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 1, "nanos": 0 }, "memory_limit_bytes": 256000000, "solution": "from math import log2\nfor _ in range(int(input())):\n\tn=int(input())\n\tl=list(map(int,input().split()))\n\tc=0\n\tfor i in range(1,len(l)):\n\t\tif(l[i]\nusing namespace std;\nint c[5005], a[13], p[5005][1205], n, m, q, k, i;\nbitset<12> t;\nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n cin >> n >> m >> q;\n for (i = 0; i < n; cin >> a[n - ++i])\n ;\n for (; m--; ++c[t.to_ulong()]) cin >> t;\n for (int x = 0, sum, j; x < 1 << n; ++x)\n for (i = 0; i < 1 << n; p[x][sum] += c[i++])\n for (sum = j = 0; j < n; ++j) sum += a[j] * !bitset<12>(i ^ x)[j];\n for (; q--;\n cout << accumulate(p[t.to_ulong()], p[t.to_ulong()] + k + 1, 0) << '\\n')\n cin >> t >> k;\n}\n", "prob_source": "codeforces", "url": "https://codeforces.com/contest/1017/problem/D", "anno_source": "usaco_guide", "anno_tag": [ "Complete Search||", "Binary Search||", "Bitwise||" ] }, "1368d": { "name": "1368_D. AND, OR and square sum", "description": "Gottfried learned about binary number representation. He then came up with this task and presented it to you.\n\nYou are given a collection of n non-negative integers a_1, \u2026, a_n. You are allowed to perform the following operation: choose two distinct indices 1 \u2264 i, j \u2264 n. If before the operation a_i = x, a_j = y, then after the operation a_i = x~AND~y, a_j = x~OR~y, where AND and OR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).\n\nAfter all operations are done, compute \u2211_{i=1}^n a_i^2 \u2014 the sum of squares of all a_i. What is the largest sum of squares you can achieve?\n\nInput\n\nThe first line contains a single integer n (1 \u2264 n \u2264 2 \u22c5 10^5).\n\nThe second line contains n integers a_1, \u2026, a_n (0 \u2264 a_i < 2^{20}).\n\nOutput\n\nPrint a single integer \u2014 the largest possible sum of squares that can be achieved after several (possibly zero) operations.\n\nExamples\n\nInput\n\n\n1\n123\n\n\nOutput\n\n\n15129\n\n\nInput\n\n\n3\n1 3 5\n\n\nOutput\n\n\n51\n\n\nInput\n\n\n2\n349525 699050\n\n\nOutput\n\n\n1099509530625\n\nNote\n\nIn the first sample no operation can be made, thus the answer is 123^2.\n\nIn the second sample we can obtain the collection 1, 1, 7, and 1^2 + 1^2 + 7^2 = 51.\n\nIf x and y are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x~AND~y is set to 1 if and only if both corresponding bits of x and y are set to 1. Similarly, each bit of x~OR~y is set to 1 if and only if at least one of the corresponding bits of x and y are set to 1. For example, x = 3 and y = 5 are represented as 011_2 and 101_2 (highest bit first). Then, x~AND~y = 001_2 = 1, and x~OR~y = 111_2 = 7.", "public_tests": { "input": [ "1\n123\n", "3\n1 3 5\n", "2\n349525 699050\n" ], "output": [ "15129\n", "51\n", "1099509530625\n" ] }, "source": 2, "difficulty": 10, "cf_contest_id": 1368, "cf_index": "D", "cf_points": 1750.0, "cf_rating": 1700, "cf_tags": [ "bitmasks", "greedy", "math" ], "is_description_translated": false, "untranslated_description": "", "time_limit": { "seconds": 2, "nanos": 0 }, "memory_limit_bytes": 512000000, "solution": "a=*map(int,[*open(0)][1].split()),;l=[0]*len(a)\nfor i in range(20):\n\tfor j in range(sum([n>>i&1for n in a])):l[j]|=1<