problem_id
stringlengths
3
7
contestId
stringclasses
660 values
problem_index
stringclasses
27 values
programmingLanguage
stringclasses
3 values
testset
stringclasses
5 values
incorrect_passedTestCount
float64
0
146
incorrect_timeConsumedMillis
float64
15
4.26k
incorrect_memoryConsumedBytes
float64
0
271M
incorrect_submission_id
stringlengths
7
9
incorrect_source
stringlengths
10
27.7k
correct_passedTestCount
float64
2
360
correct_timeConsumedMillis
int64
30
8.06k
correct_memoryConsumedBytes
int64
0
475M
correct_submission_id
stringlengths
7
9
correct_source
stringlengths
28
21.2k
contest_name
stringclasses
664 values
contest_type
stringclasses
3 values
contest_start_year
int64
2.01k
2.02k
time_limit
float64
0.5
15
memory_limit
float64
64
1.02k
title
stringlengths
2
54
description
stringlengths
35
3.16k
input_format
stringlengths
67
1.76k
output_format
stringlengths
18
1.06k
interaction_format
null
note
stringclasses
840 values
examples
stringlengths
34
1.16k
rating
int64
800
3.4k
tags
stringclasses
533 values
testset_size
int64
2
360
official_tests
stringlengths
44
19.7M
official_tests_complete
bool
1 class
input_mode
stringclasses
1 value
generated_checker
stringclasses
231 values
executable
bool
1 class
51/B
51
B
PyPy 3-64
TESTS
3
92
0
214317185
open_tag_count = -1 close_tag_count = -2 text = '' while open_tag_count != close_tag_count: text += input() open_tag_count = text.count('<table>') close_tag_count = text.count('</table>') result = [] cnt = 0 for element in text.split('<'): if element == 'table>' or element == '/table>': if cnt != 0: result.append(cnt) cnt = 0 if element == 'td>': cnt += 1 result.sort() number_strings = [str(num) for num in result] print(' '.join(number_strings))
19
124
1,740,800
214326668
input_str = str(input()) while input_str.count("<table>") > input_str.count("</table>") or input_str.count("<table>") == 0: input_str += str(input()) split_list = list(map(str, input_str.split("<"))) result = [] stack = [] for i in range(1, len(split_list)): if split_list[i] == "table>": stack += [0] elif split_list[i] == "td>": stack[-1] += 1 elif split_list[i] == "/table>": result += [stack[-1]] del stack[-1] result.sort() print(" ".join(map(str, result)))# 1689673002.1702056
Codeforces Beta Round 48
CF
2,010
2
256
bHTML Tables Analisys
In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully. A string is a bHTML table, if it satisfies the grammar: Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables. As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.
For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.
Print the sizes of all the tables in the non-decreasing order.
null
null
[{"input": "<table><tr><td></td></tr></table>", "output": "1"}, {"input": "<table>\n<tr>\n<td>\n<table><tr><td></td></tr><tr><td></\ntd\n></tr><tr\n><td></td></tr><tr><td></td></tr></table>\n</td>\n</tr>\n</table>", "output": "1 4"}, {"input": "<table><tr><td>\n<table><tr><td>\n<table><tr><td>\n<table><tr><td></td><td></td>\n</tr><tr><td></td></tr></table>\n</td></tr></table>\n</td></tr></table>\n</td></tr></table>", "output": "1 1 1 3"}]
1,700
["expression parsing"]
19
[{"input": "<table><tr><td></td></tr></table>\r\n", "output": "1 "}, {"input": "<table>\r\n<tr>\r\n<td>\r\n<table><tr><td></td></tr><tr><td></\r\ntd\r\n></tr><tr\r\n><td></td></tr><tr><td></td></tr></table>\r\n</td>\r\n</tr>\r\n</table>\r\n", "output": "1 4 "}, {"input": "<table><tr><td>\r\n<table><tr><td>\r\n<table><tr><td>\r\n<table><tr><td></td><td></td>\r\n</tr><tr><td></td></tr></table>\r\n</td></tr></table>\r\n</td></tr></table>\r\n</td></tr></table>\r\n", "output": "1 1 1 3 "}, {"input": "<\r\nt\r\na\r\nble><tr><td></td>\r\n</\r\ntr>\r\n</\r\nt\r\nab\r\nle>\r\n", "output": "1 "}, {"input": "<table><tr><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 1 "}, {"input": "<table><tr><td><table><tr><td><table><tr><td></td></tr></table></td></tr></table></td></tr></table>\r\n", "output": "1 1 1 "}, {"input": "<table><tr><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 1 "}, {"input": "<table><tr><td><table><tr><td><table><tr><td></td></tr></table></td></tr></table></td></tr></table>\r\n", "output": "1 1 1 "}, {"input": "<table><tr><td><table><tr><td></td><td></td></tr></table></td><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 2 2 "}, {"input": "<table><tr><td><table><tr><td></td><td></td></tr></table></td><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 2 2 "}, {"input": "<table><tr><td><table><tr><td></td></tr></table></td></tr><tr><td><table><tr><td><table><tr><td></td></tr></table></td></tr></table></td></tr></table>\r\n", "output": "1 1 1 2 "}]
false
stdio
null
true
865/D
865
D
PyPy 3
TESTS
8
467
26,931,200
228870237
import heapq n = int(input()) prices = [int(i) for i in input().split()] #print(prices) sells = [-prices[-1]] bought = set() profit = 0 for i in range(len(prices) - 2,-1,-1): sell = -sells[0] buy = prices[i] if buy < sell: heapq.heappop(sells) profit += sell - buy bought.add(buy) if sell in bought: heapq.heappush(sells,-sell) bought.remove(sell) heapq.heappush(sells,-buy) print(profit) #print(sells)
29
280
33,792,000
203975181
import sys import heapq from collections import deque input = sys.stdin.readline def fgh(): return [int(xx) for xx in input().split()] def fg(): return int(input()) n = fg() a = fgh() ans = 0 h = [a[0]] for i in range(1, n): if h[0] < a[i]: ans += a[i] - heapq.heappop(h) heapq.heappush(h, a[i]) heapq.heappush(h, a[i]) else: heapq.heappush(h, a[i]) print(ans)
MemSQL Start[c]UP 3.0 - Round 2 (onsite finalists)
CF
2,017
2
256
Buy Low Sell High
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.
Input begins with an integer N (2 ≤ N ≤ 3·105), the number of days. Following this is a line with exactly N integers p1, p2, ..., pN (1 ≤ pi ≤ 106). The price of one share of stock on the i-th day is given by pi.
Print the maximum amount of money you can end up with at the end of N days.
null
In the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is - 5 - 4 + 9 + 12 - 2 + 10 = 20.
[{"input": "9\n10 5 4 7 9 12 6 2 10", "output": "20"}, {"input": "20\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4", "output": "41"}]
2,400
["constructive algorithms", "data structures", "greedy"]
29
[{"input": "9\r\n10 5 4 7 9 12 6 2 10\r\n", "output": "20\r\n"}, {"input": "20\r\n3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4\r\n", "output": "41\r\n"}, {"input": "20\r\n9 29 8 9 13 4 14 27 16 11 27 14 4 29 23 17 3 9 30 19\r\n", "output": "147\r\n"}, {"input": "100\r\n411 642 560 340 276 440 515 519 182 314 35 227 390 136 97 5 502 584 567 79 543 444 413 463 455 316 545 329 437 443 9 435 291 384 328 501 603 234 285 297 453 587 550 72 130 163 282 298 605 349 270 198 24 179 243 92 115 56 83 26 3 456 622 325 366 360 299 153 140 552 216 117 61 307 278 189 496 562 38 527 566 503 303 16 36 286 632 196 395 452 194 77 321 615 356 250 381 174 139 123\r\n", "output": "13765\r\n"}, {"input": "20\r\n499559 302871 194704 903169 447219 409938 42087 753609 589270 719332 855199 609182 315644 980473 966759 851389 900793 905536 258772 453222\r\n", "output": "4620235\r\n"}, {"input": "47\r\n403136 169462 358897 935260 150614 688938 111490 148144 462915 753991 551831 303917 772190 188564 854800 7094 491120 997932 271873 236736 797113 427200 681780 911765 217707 339475 313125 56785 749677 313468 902148 993064 747609 387815 768631 41886 68862 707668 32853 653517 941150 858711 562604 867235 840369 337814 129019\r\n", "output": "12525965\r\n"}, {"input": "2\r\n4 77\r\n", "output": "73\r\n"}]
false
stdio
null
true
724/D
724
D
Python 3
PRETESTS
4
62
4,608,000
21291011
if __name__ == '__main__': m = int(input()) s = str(input()) symbol_index = set() ans = [] for i in range(len(s) - m + 1): subseq = list(s[i:i + m]) lowest_letter = sorted(subseq)[0] new_index = subseq.index(lowest_letter) + i symbol_index.add(new_index) current_symbols = sorted([s[x] for x in symbol_index]) for char in subseq: if ord(char) <= ord(current_symbols[0]): symbol_index.add(subseq.index(char) + i) for i in symbol_index: ans.append(s[i]) ans.sort() print("".join(ans))
71
327
29,286,400
21293752
abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] m = int(input()) string = input() good = False toCheck = [] lenS = len(string) holes = [(-1, lenS)] have = {'s': 0, 'i': 0, 'y': 0, 'h': 0, 'r': 0, 'f': 0, 'd': 0, 'z': 0, 'q': 0, 't': 0, 'n': 0, 'g': 0, 'l': 0, 'k': 0, 'o': 0, 'c': 0, 'w': 0, 'm': 0, 'b': 0, 'u': 0, 'a': 0, 'v': 0, 'e': 0, 'p': 0, 'j': 0, 'x': 0} for sym in range(26): if not good: good = True for hole in holes: i = hole[0] + 1 end = hole[1] while i < end: fill = string[i:min(end, i + m)].rfind(abc[sym]) if fill == -1: good = False break else: have[abc[sym]] += 1 i = i + fill + 1 if end - i < m: break if not good: break holes = [] if not good: have = {'s': 0, 'i': 0, 'y': 0, 'h': 0, 'r': 0, 'f': 0, 'd': 0, 'z': 0, 'q': 0, 't': 0, 'n': 0, 'g': 0, 'l': 0, 'k': 0, 'o': 0, 'c': 0, 'w': 0, 'm': 0, 'b': 0, 'u': 0, 'a': 0, 'v': 0, 'e': 0, 'p': 0, 'j': 0, 'x': 0} toCheck.append(abc[sym]) good = True lastSeen = -1 for i in range(lenS): if string[i] in toCheck: have[string[i]] += 1 if i - lastSeen > m: holes.append((lastSeen, i)) good = False lastSeen = i if lenS - lastSeen > m: holes.append((lastSeen, lenS)) good = False almost = [have[i] * i for i in abc] print(''.join(almost))
Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined)
CF
2,016
2
256
Dense Subsequence
You are given a string s, consisting of lowercase English letters, and the integer m. One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order. Formally, we choose a subsequence of indices 1 ≤ i1 < i2 < ... < it ≤ |s|. The selected sequence must meet the following condition: for every j such that 1 ≤ j ≤ |s| - m + 1, there must be at least one selected index that belongs to the segment [j,  j + m - 1], i.e. there should exist a k from 1 to t, such that j ≤ ik ≤ j + m - 1. Then we take any permutation p of the selected indices and form a new string sip1sip2... sipt. Find the lexicographically smallest string, that can be obtained using this procedure.
The first line of the input contains a single integer m (1 ≤ m ≤ 100 000). The second line contains the string s consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100 000. It is also guaranteed that the number m doesn't exceed the length of the string s.
Print the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.
null
In the first sample, one can choose the subsequence {3} and form a string "a". In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab".
[{"input": "3\ncbabc", "output": "a"}, {"input": "2\nabcab", "output": "aab"}, {"input": "3\nbcabcbaccba", "output": "aaabb"}]
1,900
["data structures", "greedy", "strings"]
71
[{"input": "3\r\ncbabc\r\n", "output": "a\r\n"}, {"input": "2\r\nabcab\r\n", "output": "aab\r\n"}, {"input": "3\r\nbcabcbaccba\r\n", "output": "aaabb\r\n"}, {"input": "5\r\nimmaydobun\r\n", "output": "ab\r\n"}, {"input": "5\r\nwjjdqawypvtgrncmqvcsergermprauyevcegjtcrrblkwiugrcjfpjyxngyryxntauxlouvwgjzpsuxyxvhavgezwtuzknetdibv\r\n", "output": "aaaabbcccccddeeeeeefggggggghiijjjjjjkkllmmnnnnoppppqqrrrrrrrrsstttttu\r\n"}, {"input": "10\r\nefispvmzuutsrpxzfrykhabznxiyquwvhwhrksrgzodtuepfvamilfdynapzhzyhncorhzuewrrkcduvuhwsrprjrmgctnvrdtpj\r\n", "output": "aaabcccddddeeeffffgghhhhhhhiiijjkkklm\r\n"}, {"input": "20\r\nhlicqhxayiodyephxlfoetfketnaabpfegqcrjzlshkxfzjssvpvzhzylgowwovgxznzowvpklbwbzhwtkkaomjkenhpedmbmjic\r\n", "output": "aaaabbbbcccddeeeeeeffffg\r\n"}, {"input": "50\r\ntyhjolxuexoffdkdwimsjujorgeksyiyvvqecvhpjsuayqnibijtipuqhkulxpysotlmtrsgygpkdhkrtntwqzrpfckiscaphyhv\r\n", "output": "aab\r\n"}, {"input": "1\r\nbaaa\r\n", "output": "aaab\r\n"}, {"input": "5\r\nbbbbba\r\n", "output": "ab\r\n"}, {"input": "10\r\nbbabcbbaabcbcbcbaabbccaacccbbbcaaacabbbbaaaccbcccacbbccaccbbaacaccbabcaaaacaccacbaaccaaccbaacabbbaac\r\n", "output": "aaaaaaaaaaa\r\n"}]
false
stdio
null
true
441/A
441
A
Python 3
TESTS
2
30
0
182723660
n, v = [int(i) for i in input().split()] x = [] for i in range(n): m = [int(i) for i in input().split()] for i in m[1:]: if v > i: x.append(m[0]) print(len(x)) print(*x)
26
46
0
137350227
#!/usr/bin/env python # coding=utf-8 ''' Author: Deean Date: 2021-11-29 22:52:48 LastEditTime: 2021-11-29 22:57:43 Description: Valera and Antique Items FilePath: CF441A.py ''' def func(): n, v = map(int, input().strip().split()) deal = [] for i in range(n): k, *s = map(int, input().strip().split()) if v > min(s): deal.append(str(i + 1)) print(len(deal)) print(" ".join(deal)) if __name__ == '__main__': func()
Codeforces Round 252 (Div. 2)
CF
2,014
1
256
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.
In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
null
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller. In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
[{"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "output": "3\n1 2 3"}, {"input": "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000", "output": "0"}]
1,000
["implementation"]
26
[{"input": "3 50000\r\n1 40000\r\n2 20000 60000\r\n3 10000 70000 190000\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "3 50000\r\n1 50000\r\n3 100000 120000 110000\r\n3 120000 110000 120000\r\n", "output": "0\r\n\r\n"}, {"input": "2 100001\r\n1 895737\r\n1 541571\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 561774\r\n", "output": "1\r\n1\r\n"}, {"input": "3 1000000\r\n5 1000000 568832 1000000 1000000 1000000\r\n13 1000000 1000000 1000000 596527 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n20 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n", "output": "2\r\n1 2\r\n"}, {"input": "3 999999\r\n7 1000000 1000000 1000000 999999 1000000 999999 1000000\r\n6 999999 1000000 999999 1000000 999999 999999\r\n7 999999 1000000 1000000 999999 1000000 1000000 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "3 999999\r\n22 1000000 1000000 999999 999999 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 999999 1000000 1000000 999999 1000000 1000000 1000000 352800 999999 1000000\r\n14 999999 999999 999999 999999 999999 1000000 999999 999999 999999 999999 702638 999999 1000000 999999\r\n5 999999 1000000 1000000 999999 363236\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "1 50001\r\n1 50000\r\n", "output": "1\r\n1\r\n"}]
false
stdio
null
true
441/A
441
A
Python 3
TESTS
2
31
0
224256782
n, purse = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(n)] res = [] for seller in arr: for j in range(1, len(seller)): if seller[j] < purse: if seller[0] not in res: res.append(seller[0]) break print(len(res)) if len(res) > 0: res.sort() print(*res)
26
46
0
137609281
def solve(n, v, arr): res = [] for j in range(n): for i in range(len(arr[j])-1): if arr[j][i+1] < v: res.append(str(j+1)) break return res, len(res) n, v = map(int, input().split()) arr = [] for i in range(n): temp = list(map(int, input().split())) arr.append(temp) res, l = solve(n, v, arr) print(l) if len(res) != 0: for i in range(l): print(res[i], end=" ")
Codeforces Round 252 (Div. 2)
CF
2,014
1
256
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.
In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
null
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller. In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
[{"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "output": "3\n1 2 3"}, {"input": "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000", "output": "0"}]
1,000
["implementation"]
26
[{"input": "3 50000\r\n1 40000\r\n2 20000 60000\r\n3 10000 70000 190000\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "3 50000\r\n1 50000\r\n3 100000 120000 110000\r\n3 120000 110000 120000\r\n", "output": "0\r\n\r\n"}, {"input": "2 100001\r\n1 895737\r\n1 541571\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 561774\r\n", "output": "1\r\n1\r\n"}, {"input": "3 1000000\r\n5 1000000 568832 1000000 1000000 1000000\r\n13 1000000 1000000 1000000 596527 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n20 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n", "output": "2\r\n1 2\r\n"}, {"input": "3 999999\r\n7 1000000 1000000 1000000 999999 1000000 999999 1000000\r\n6 999999 1000000 999999 1000000 999999 999999\r\n7 999999 1000000 1000000 999999 1000000 1000000 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "3 999999\r\n22 1000000 1000000 999999 999999 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 999999 1000000 1000000 999999 1000000 1000000 1000000 352800 999999 1000000\r\n14 999999 999999 999999 999999 999999 1000000 999999 999999 999999 999999 702638 999999 1000000 999999\r\n5 999999 1000000 1000000 999999 363236\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "1 50001\r\n1 50000\r\n", "output": "1\r\n1\r\n"}]
false
stdio
null
true
441/A
441
A
Python 3
TESTS
2
30
0
172499330
x,y = list(map(int , input().split())) l = [] for i in range(x): l.append(list(map(int , input().split()))) conter =0 sellers =[] for i in l: for j in i: if j<1000: continue elif j<y: conter +=1 sellers.append(i[0]) break print(conter) if len(sellers) == 0: print(' ') exit for i in sellers: print(i , end=" ")
26
46
0
140583065
s = input().split() (n,v) = (int(i) for i in s) res = [] cs = 0 for i in range(n): s = input().split() s = [int(j) for j in s] for j in range(1,s[0]+1): if(s[j] < v): cs += 1 res.append(i+1) break print(cs) for i in range(cs): print(res[i],end = ' ')
Codeforces Round 252 (Div. 2)
CF
2,014
1
256
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.
In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
null
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller. In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
[{"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "output": "3\n1 2 3"}, {"input": "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000", "output": "0"}]
1,000
["implementation"]
26
[{"input": "3 50000\r\n1 40000\r\n2 20000 60000\r\n3 10000 70000 190000\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "3 50000\r\n1 50000\r\n3 100000 120000 110000\r\n3 120000 110000 120000\r\n", "output": "0\r\n\r\n"}, {"input": "2 100001\r\n1 895737\r\n1 541571\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 561774\r\n", "output": "1\r\n1\r\n"}, {"input": "3 1000000\r\n5 1000000 568832 1000000 1000000 1000000\r\n13 1000000 1000000 1000000 596527 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n20 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n", "output": "2\r\n1 2\r\n"}, {"input": "3 999999\r\n7 1000000 1000000 1000000 999999 1000000 999999 1000000\r\n6 999999 1000000 999999 1000000 999999 999999\r\n7 999999 1000000 1000000 999999 1000000 1000000 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "3 999999\r\n22 1000000 1000000 999999 999999 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 999999 1000000 1000000 999999 1000000 1000000 1000000 352800 999999 1000000\r\n14 999999 999999 999999 999999 999999 1000000 999999 999999 999999 999999 702638 999999 1000000 999999\r\n5 999999 1000000 1000000 999999 363236\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "1 50001\r\n1 50000\r\n", "output": "1\r\n1\r\n"}]
false
stdio
null
true
441/A
441
A
Python 3
TESTS
4
46
0
27624335
n,v = input().split() n,v = int(n),int(v) A = [] for i in range(0,n): C = [] a = input() for j in a.split(): C.append(int(j)) d = C[0] del C[0] C.sort() if v >C[0]: A.append(d) A= list(set(A)) A.sort() s = '' for k in A: s = s+str(k)+' ' if n == 50 and v == 100000: print(18) print('2 7 10 12 14 15 17 18 21 22 26 27 29 30 31 32 45 48') elif n == 25 and v == 900000: print(23) print('1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25') elif len(A) >0: print(len(A)) print(s) else: print(0)
26
46
0
140739875
NUMBER_OR_SELLERS, VALERA_BUDGET = [int(x) for x in str(input()).split()] result = {} for i in range(NUMBER_OR_SELLERS): input_items = input().split() for x in input_items[1:]: if int(x) < VALERA_BUDGET: result[i + 1] = 1 print(len(result)) for i in result: print(i, end=" ")
Codeforces Round 252 (Div. 2)
CF
2,014
1
256
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.
In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
null
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller. In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
[{"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "output": "3\n1 2 3"}, {"input": "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000", "output": "0"}]
1,000
["implementation"]
26
[{"input": "3 50000\r\n1 40000\r\n2 20000 60000\r\n3 10000 70000 190000\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "3 50000\r\n1 50000\r\n3 100000 120000 110000\r\n3 120000 110000 120000\r\n", "output": "0\r\n\r\n"}, {"input": "2 100001\r\n1 895737\r\n1 541571\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 561774\r\n", "output": "1\r\n1\r\n"}, {"input": "3 1000000\r\n5 1000000 568832 1000000 1000000 1000000\r\n13 1000000 1000000 1000000 596527 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n20 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n", "output": "2\r\n1 2\r\n"}, {"input": "3 999999\r\n7 1000000 1000000 1000000 999999 1000000 999999 1000000\r\n6 999999 1000000 999999 1000000 999999 999999\r\n7 999999 1000000 1000000 999999 1000000 1000000 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "3 999999\r\n22 1000000 1000000 999999 999999 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 999999 1000000 1000000 999999 1000000 1000000 1000000 352800 999999 1000000\r\n14 999999 999999 999999 999999 999999 1000000 999999 999999 999999 999999 702638 999999 1000000 999999\r\n5 999999 1000000 1000000 999999 363236\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "1 50001\r\n1 50000\r\n", "output": "1\r\n1\r\n"}]
false
stdio
null
true
441/A
441
A
Python 3
TESTS
2
30
0
166763385
n,v=list(map(int,input().split())) f=[] for pratyush in range(n): a=list(map(int,input().split())) x=a[1:] x.sort() if x[0]<v: f.append(a[0]) f.sort() print(len(f)) print(*f)
26
46
0
141232799
x,y=map(int,input().split()) s=0 list=[] for i in range(1,x+1): z=[int(k) for k in input().split()] for j in range(1,len(z),1): if (z[j]<y): s=s+1 list.append(i) break print(s) for i in list: print(i)
Codeforces Round 252 (Div. 2)
CF
2,014
1
256
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.
In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
null
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller. In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
[{"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "output": "3\n1 2 3"}, {"input": "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000", "output": "0"}]
1,000
["implementation"]
26
[{"input": "3 50000\r\n1 40000\r\n2 20000 60000\r\n3 10000 70000 190000\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "3 50000\r\n1 50000\r\n3 100000 120000 110000\r\n3 120000 110000 120000\r\n", "output": "0\r\n\r\n"}, {"input": "2 100001\r\n1 895737\r\n1 541571\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 561774\r\n", "output": "1\r\n1\r\n"}, {"input": "3 1000000\r\n5 1000000 568832 1000000 1000000 1000000\r\n13 1000000 1000000 1000000 596527 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n20 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n", "output": "2\r\n1 2\r\n"}, {"input": "3 999999\r\n7 1000000 1000000 1000000 999999 1000000 999999 1000000\r\n6 999999 1000000 999999 1000000 999999 999999\r\n7 999999 1000000 1000000 999999 1000000 1000000 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "3 999999\r\n22 1000000 1000000 999999 999999 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 999999 1000000 1000000 999999 1000000 1000000 1000000 352800 999999 1000000\r\n14 999999 999999 999999 999999 999999 1000000 999999 999999 999999 999999 702638 999999 1000000 999999\r\n5 999999 1000000 1000000 999999 363236\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "1 50001\r\n1 50000\r\n", "output": "1\r\n1\r\n"}]
false
stdio
null
true
441/A
441
A
Python 3
TESTS
3
31
0
186336283
n, v = [int(i) for i in input().split()] x = [] if n == 50 and v == 100000: print(18) print("2 7 10 12 14 15 17 18 21 22 26 27 29 30 31 32 45 48") exit() for i in range(n): m = [int(i) for i in input().split()] for j in m[1:]: if v > j: x.append(m[0]) break x = sorted(x) print(len(x)) print(*x)
26
46
0
146016264
n,v=[int(x) for x in input().split()] count=0 ans=[] for i in range(n): price=[int(x) for x in input().split()] for j in range(1,price[0]+1): if price[j]<v: count+=1 ans.append(i+1) break print(count) for i in ans: print(i,end=" ")
Codeforces Round 252 (Div. 2)
CF
2,014
1
256
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.
In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
null
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller. In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
[{"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "output": "3\n1 2 3"}, {"input": "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000", "output": "0"}]
1,000
["implementation"]
26
[{"input": "3 50000\r\n1 40000\r\n2 20000 60000\r\n3 10000 70000 190000\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "3 50000\r\n1 50000\r\n3 100000 120000 110000\r\n3 120000 110000 120000\r\n", "output": "0\r\n\r\n"}, {"input": "2 100001\r\n1 895737\r\n1 541571\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 561774\r\n", "output": "1\r\n1\r\n"}, {"input": "3 1000000\r\n5 1000000 568832 1000000 1000000 1000000\r\n13 1000000 1000000 1000000 596527 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n20 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n", "output": "2\r\n1 2\r\n"}, {"input": "3 999999\r\n7 1000000 1000000 1000000 999999 1000000 999999 1000000\r\n6 999999 1000000 999999 1000000 999999 999999\r\n7 999999 1000000 1000000 999999 1000000 1000000 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "3 999999\r\n22 1000000 1000000 999999 999999 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 999999 1000000 1000000 999999 1000000 1000000 1000000 352800 999999 1000000\r\n14 999999 999999 999999 999999 999999 1000000 999999 999999 999999 999999 702638 999999 1000000 999999\r\n5 999999 1000000 1000000 999999 363236\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "1 50001\r\n1 50000\r\n", "output": "1\r\n1\r\n"}]
false
stdio
null
true
441/A
441
A
Python 3
TESTS
2
30
0
224259046
n, m = map(int, input().split()) data = {} for _ in range(n): s = list(map(int, input().split())) data[s[0]] = s[1:] count = 0 result = [] for i in data: for j in data[i]: if m > j: count += 1 if i not in result: result.append(i) print(count) result.sort() result = map(str, result) print(' '.join(result))
26
46
0
147678089
n, v = map(int, input().split()) count = 0 slist = [] for i in range(n): _, *l = map(int, input().split()) for j in l: if v > j: slist.append(i+1) count += 1 break print(count) for x in slist: print(x, end=' ')
Codeforces Round 252 (Div. 2)
CF
2,014
1
256
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.
The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.
In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.
null
In the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller. In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.
[{"input": "3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "output": "3\n1 2 3"}, {"input": "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000", "output": "0"}]
1,000
["implementation"]
26
[{"input": "3 50000\r\n1 40000\r\n2 20000 60000\r\n3 10000 70000 190000\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "3 50000\r\n1 50000\r\n3 100000 120000 110000\r\n3 120000 110000 120000\r\n", "output": "0\r\n\r\n"}, {"input": "2 100001\r\n1 895737\r\n1 541571\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "1 1000000\r\n1 561774\r\n", "output": "1\r\n1\r\n"}, {"input": "3 1000000\r\n5 1000000 568832 1000000 1000000 1000000\r\n13 1000000 1000000 1000000 596527 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n20 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000\r\n", "output": "2\r\n1 2\r\n"}, {"input": "3 999999\r\n7 1000000 1000000 1000000 999999 1000000 999999 1000000\r\n6 999999 1000000 999999 1000000 999999 999999\r\n7 999999 1000000 1000000 999999 1000000 1000000 1000000\r\n", "output": "0\r\n\r\n"}, {"input": "3 999999\r\n22 1000000 1000000 999999 999999 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 999999 1000000 1000000 999999 1000000 1000000 1000000 352800 999999 1000000\r\n14 999999 999999 999999 999999 999999 1000000 999999 999999 999999 999999 702638 999999 1000000 999999\r\n5 999999 1000000 1000000 999999 363236\r\n", "output": "3\r\n1 2 3\r\n"}, {"input": "1 50001\r\n1 50000\r\n", "output": "1\r\n1\r\n"}]
false
stdio
null
true
149/D
149
D
PyPy 3-64
TESTS
5
154
0
203626521
import sys input = lambda: sys.stdin.readline().strip() arr = list(input()) n = len(arr) MOD = 1000000007 # lc * 3 + rc, 0 no 1 red 2 blue color = [4, 3, 3, 3, 2, 2, 3, 2, 2] # left pos, right pos, left color, right color def dp(l, r, lc, rc): if l == r - 1: return color[lc * 3 + rc] if match[l] == r: if lc == 0 and rc == 0: return (2 * dp(l + 1, r - 1, 0, 1) + 2 * dp(l + 1, r - 1, 1, 0)) % MOD elif lc == 0: return (dp(l + 1, r - 1, 0, 1) + 2 * dp(l + 1, r - 1, 1, 0)) % MOD elif lc == 1 and rc == 0: return (2 * dp(l + 1, r - 1, 0, 1) + dp(l + 1, r - 1, 1, 0)) % MOD else: return (dp(l + 1, r - 1, 1, 0) + dp(l + 1, r - 1, 0, 1)) % MOD else: if lc == 0: if l == match[l] - 1: return 2 * (dp(match[r], r, 0, rc) + dp(match[r], r, 1, rc)) % MOD else: return 2 * (dp(l + 1, match[l] - 1, 1, 0) * dp(match[r], r, 0, rc) + dp(l + 1, match[l] - 1, 0, 1) * dp(match[r], r, 1, rc)) % MOD else: if l == match[l] - 1: return (dp(match[r], r, 0, rc) + 2 * dp(match[r], r, 1, rc)) % MOD else: return (dp(l + 1, match[l] - 1, 1, 0) * dp(match[r], r, 0, rc) + 2 * dp(l + 1, match[l] - 1, 0, 1) * dp(match[r], r, 1, rc)) % MOD match = [0] * n st = [] for i in range(n): if arr[i] == '(': st.append(i) else: tmp = st.pop() match[tmp] = i match[i] = tmp print(dp(0, n-1, 0, 0))
38
310
4,300,800
203629614
Mod = 10 ** 9 + 7 s = input() n = len(s) from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc # 拆括号 # 0 1 2 3 4 5 6 7 8 # 左无右无 左无右红 左无右蓝 左红右无 左红右红 左红右蓝 左蓝右无 左蓝右红 左蓝右蓝 # 无 红 蓝 0 1 2 @bootstrap def dfs(l, r): if r - l == 1: yield 0, 1, 1, 1, 0, 0, 1, 0, 0 count = 0 for i in range(l, r): if s[i] == '(': count += 1 else: count -= 1 # 并联关系 if count == 0: a1 = yield dfs(l, i) a2 = yield dfs(i + 1, r) res = [0] * 9 for i in range(3): for j in range(3): for k in range(3): for l in range(3): if k == l and k > 0: continue res[i * 3 + j] += a1[i * 3 + k] * a2[l * 3 + j] res[i * 3 + j] %= Mod yield res # 串联关系 a1 = yield dfs(l + 1, r - 1) total = sum(a1) yield 0, total - a1[1] - a1[4] - a1[7], total - a1[2] - a1[5] - a1[8], total - a1[3] - a1[4] - a1[5], 0, 0, total - \ a1[6] - a1[7] - a1[8], 0, 0 print(sum(dfs(0, n - 1)) % Mod)
Codeforces Round 106 (Div. 2)
CF
2,012
2
256
Coloring Brackets
Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it. You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not. In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one. You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled: - Each bracket is either not colored any color, or is colored red, or is colored blue. - For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored. - No two neighboring colored brackets have the same color. Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).
The first line contains the single string s (2 ≤ |s| ≤ 700) which represents a correct bracket sequence.
Print the only number — the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).
null
Let's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below. The two ways of coloring shown below are incorrect.
[{"input": "(())", "output": "12"}, {"input": "(()())", "output": "40"}, {"input": "()", "output": "4"}]
1,900
["dp"]
38
[{"input": "(())\r\n", "output": "12\r\n"}, {"input": "(()())\r\n", "output": "40\r\n"}, {"input": "()\r\n", "output": "4\r\n"}, {"input": "((()))\r\n", "output": "36\r\n"}, {"input": "()(())\r\n", "output": "42\r\n"}, {"input": "()()()\r\n", "output": "48\r\n"}, {"input": "(())(())\r\n", "output": "126\r\n"}, {"input": "()()()()()()()()()()()(())\r\n", "output": "9085632\r\n"}, {"input": "()(())()((()))\r\n", "output": "4428\r\n"}, {"input": "()()(())()(())\r\n", "output": "5040\r\n"}, {"input": "()()()()()()()()()()()()()()()()\r\n", "output": "411525376\r\n"}, {"input": "(()()())\r\n", "output": "136\r\n"}, {"input": "()(()())()\r\n", "output": "480\r\n"}, {"input": "(())()(())()\r\n", "output": "1476\r\n"}, {"input": "()()(()())(())()()()\r\n", "output": "195840\r\n"}, {"input": "()()()((((())))())()()()()()((()))()()(())()(((())))()(()())((())())((()())(((((()()()())()()())))))\r\n", "output": "932124942\r\n"}, {"input": "((()(((((()(()(())))()((((((((())))()(((((())()((((())())(()(()(())())((()))()((()))))))))))))))))))))\r\n", "output": "90824888\r\n"}, {"input": "((()))((())())((()()))()(())(()())(())()()()((()(((()())))()())()((((()((()((())))(())(()(())())))((()())()()()((())()))()(())(())))()(((((()())))))))\r\n", "output": "100627207\r\n"}, {"input": "()(((()((((()())))())(())(((((()(()()))))()()))((())))()())((())))(())()((()())())()(()(()())())(()())()(()(((((()))()((()()(())()(())(()((()((()))))()(())()()(()()()((((()())()))))()(((()(((((()()((((())(())))()())(()))(((())((()())(()))())(((()()()(()(())())())(()()()))))())))()((()(()()(()))())((())(()()()(())()))()()(((())))((()))(()((()(((()))((((()())))())(((())()(()((())))))))))))))))))))))\r\n", "output": "306199947\r\n"}, {"input": "(())(((((()()()()())(())))(()()((()(()(((((())(()())))())(()()(()((())()(()()))))))(())()())))()((()()())))()()(()(())())()())()(())(((((()(()()(((()())()))((())((((()()()))())(((())(((())))))))))))))\r\n", "output": "270087235\r\n"}, {"input": "()()()((()))(())(((())()(())(())))()()(((()((()()()))(()()(())(())))(()()((()((())(()()(()(())))))))(((())()((((()())))()(((()()())))()))()())))()(()(()())((()((()))))())(((((()())()((((()))(((((()())()))(((()()()((((((()()(())(()))((()(()(()((()((((()(((()(()()(()()((((()))()()()(()((((()(((())(((()()()(())()))((()()()(()))))())()))))(((((((()))())))(((()(()())(())))())))((((())(())())(((()()()))((()()))())(()))(())((()(()))(()()((()(()((()(())(()))()()))))))))))))))))))))))))))))))))))))))))))\r\n", "output": "461776571\r\n"}, {"input": "()()(((((()((()(())()(()))(()(()(()(()(())(())(())(()(()((())))()))())((()((()(()(((()(()))()(()())(()()()()(((((()(((()))((((())())(((()((((()((((((())())))()))))))))(())())))(((()((()))))((())(()()))()(()(()((()())())()))))((()))))()((())())(()())()())))())())())())()((()((())((()()())()())())()(())()))(()(()))())))(()()()())()())))))))((((()())))((((()()()))())((()(())))))()((()(((())()()()(()()()()()))))(((()())()))()()(((())(()())(()()))))))\r\n", "output": "66338682\r\n"}, {"input": "(()())()()()((((()(()()(())()((())(((()((()()(()))()))()()))))()(()(())(()))))))\r\n", "output": "639345575\r\n"}, {"input": "()((()))((((()((())((()()((((()))()()((())((()(((((()(()))((())()))((((())()(()(()))()))))))))))))))))))\r\n", "output": "391997323\r\n"}, {"input": "(((((()())))))()()()()()(())()()()((()()))()()()()()(((()(())))())(((()())))\r\n", "output": "422789312\r\n"}, {"input": "((()((()))()((()(()))())))()((()())())()(()())((()))(()())(())()(())()(())(())((()()))((()))()()()()(())()\r\n", "output": "140121189\r\n"}, {"input": "()()\r\n", "output": "14\r\n"}]
false
stdio
null
true
347/B
347
B
Python 3
TESTS
10
280
7,065,600
32104701
n=int(input()) s=input() l=s.split() p=0 verif=True l=[int(l[i]) for i in range(len(l))] for i in range (len(l)): if (i==l[i]): p=p+1 elif((l[l[i]]==i)and (verif==True)): verif=False p=p+2 if (verif==True): p=p+1 print(p)
19
156
6,963,200
148057708
n = int(input()) l = list(map(int,input().split())) counter = 0 x1 = 0 x2 = 0 for i in range(len(l)): if l[i] == i: counter+=1 else: if i == l[l[i]]: x1 = 2 if x1 == 0: for j in range(len(l)): if j!=l[j] and j in l: x1 = 1 break print(counter+x1+x2)
Codeforces Round 201 (Div. 2)
CF
2,013
2
256
Fixed Points
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
null
null
[{"input": "5\n0 1 3 4 2", "output": "3"}]
1,100
["brute force", "implementation", "math"]
19
[{"input": "5\r\n0 1 3 4 2\r\n", "output": "3\r\n"}, {"input": "10\r\n6 9 4 7 8 2 3 5 0 1\r\n", "output": "2\r\n"}, {"input": "100\r\n99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67\r\n", "output": "3\r\n"}, {"input": "3\r\n0 1 2\r\n", "output": "3\r\n"}, {"input": "3\r\n2 1 0\r\n", "output": "3\r\n"}, {"input": "3\r\n1 2 0\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}, {"input": "5\r\n0 1 2 3 4\r\n", "output": "5\r\n"}, {"input": "4\r\n0 1 2 3\r\n", "output": "4\r\n"}, {"input": "7\r\n0 1 2 4 3 6 5\r\n", "output": "5\r\n"}, {"input": "6\r\n0 1 2 3 5 4\r\n", "output": "6\r\n"}]
false
stdio
null
true
347/B
347
B
Python 3
TESTS
10
248
6,758,400
32083775
n=int(input()) tab=list(map(int,input().split(" "))) b=False cnt=0 for i in range(n): if (tab[i]==i): cnt+=1 elif (tab[tab[i]]==i): b=True if (b): print(cnt+2) else: print(cnt+1)
19
156
13,004,800
164476786
def fixed_points(): list_length = int(input()) points = list(map(int, input().split(" "))) fix_points = 0 swaps = True for i in range(list_length): if points[i] == i: fix_points += 1 elif swaps is True and points[points[i]] == i: swaps = False fix_points += 2 if swaps is True and fix_points != list_length: fix_points += 1 print(fix_points) fixed_points()
Codeforces Round 201 (Div. 2)
CF
2,013
2
256
Fixed Points
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
null
null
[{"input": "5\n0 1 3 4 2", "output": "3"}]
1,100
["brute force", "implementation", "math"]
19
[{"input": "5\r\n0 1 3 4 2\r\n", "output": "3\r\n"}, {"input": "10\r\n6 9 4 7 8 2 3 5 0 1\r\n", "output": "2\r\n"}, {"input": "100\r\n99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67\r\n", "output": "3\r\n"}, {"input": "3\r\n0 1 2\r\n", "output": "3\r\n"}, {"input": "3\r\n2 1 0\r\n", "output": "3\r\n"}, {"input": "3\r\n1 2 0\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}, {"input": "5\r\n0 1 2 3 4\r\n", "output": "5\r\n"}, {"input": "4\r\n0 1 2 3\r\n", "output": "4\r\n"}, {"input": "7\r\n0 1 2 4 3 6 5\r\n", "output": "5\r\n"}, {"input": "6\r\n0 1 2 3 5 4\r\n", "output": "6\r\n"}]
false
stdio
null
true
2/A
2
A
Python 3
TESTS
13
62
0
147959585
n=int(input()) a={} s='' scor=int(0) max=-1001 maxs='' if n==600 : for _ in range(10) : for _ in range(60) : s,scor=input().split() print(s,scor,end=' ') print('|') else: for i in range(n) : s,scor=input().split() scor=int(scor) if not(s in a) : a[s]=int(scor) else : a[s]=a[s]+int(scor) if int(a[s])>int(max): max=a[s] maxs=s if a[maxs]<int(max): max=a[s] maxs=s print(maxs)
20
62
0
158343764
''' ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬ ▓▓█████▓▓ ╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ########################### // •︿• \\ /\\ //\ /\\ //\ /\\//\ ########################### ''' import sys input = lambda : sys.stdin.readline().strip() import math as mt from math import ceil as cl from math import log2 as l2 mod = 10**9 + 7 def ii(): return int(input()) def lii(): return list(map(int, input().split())) def ss(): return input() def lss(): return list(map(str, input().split())) def yes(): print("YES") def no(): print("NO") ''' ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ''' rounds = list() scores = dict() for i in range(ii()): name, score = ss().split() scores[name] = scores.get(name, 0)+int(score) rounds.append(name+' '+str(scores[name])) maxscr = max(scores.values()) for r in rounds: name, score = r.split() if int(score)>=maxscr and scores[name]>=maxscr: print (name); break
Codeforces Beta Round 2
ICPC
2,010
1
64
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Print the name of the winner.
null
null
[{"input": "3\nmike 3\nandrew 5\nmike 2", "output": "andrew"}, {"input": "3\nandrew 3\nandrew 2\nmike 5", "output": "andrew"}]
1,500
["hashing", "implementation"]
20
[{"input": "3\r\nmike 3\r\nandrew 5\r\nmike 2\r\n", "output": "andrew\r\n"}, {"input": "3\r\nandrew 3\r\nandrew 2\r\nmike 5\r\n", "output": "andrew\r\n"}, {"input": "5\r\nkaxqybeultn -352\r\nmgochgrmeyieyskhuourfg -910\r\nkaxqybeultn 691\r\nmgochgrmeyieyskhuourfg -76\r\nkaxqybeultn -303\r\n", "output": "kaxqybeultn\r\n"}, {"input": "7\r\nksjuuerbnlklcfdjeyq 312\r\ndthjlkrvvbyahttifpdewvyslsh -983\r\nksjuuerbnlklcfdjeyq 268\r\ndthjlkrvvbyahttifpdewvyslsh 788\r\nksjuuerbnlklcfdjeyq -79\r\nksjuuerbnlklcfdjeyq -593\r\nksjuuerbnlklcfdjeyq 734\r\n", "output": "ksjuuerbnlklcfdjeyq\r\n"}, {"input": "12\r\natrtthfpcvishmqbakprquvnejr 185\r\natrtthfpcvishmqbakprquvnejr -699\r\natrtthfpcvishmqbakprquvnejr -911\r\natrtthfpcvishmqbakprquvnejr -220\r\nfcgslzkicjrpbqaifgweyzreajjfdo 132\r\nfcgslzkicjrpbqaifgweyzreajjfdo -242\r\nm 177\r\nm -549\r\natrtthfpcvishmqbakprquvnejr -242\r\nm 38\r\natrtthfpcvishmqbakprquvnejr -761\r\nfcgslzkicjrpbqaifgweyzreajjfdo 879\r\n", "output": "fcgslzkicjrpbqaifgweyzreajjfdo\r\n"}, {"input": "15\r\naawtvezfntstrcpgbzjbf 681\r\nzhahpvqiptvksnbjkdvmknb -74\r\naawtvezfntstrcpgbzjbf 661\r\njpdwmyke 474\r\naawtvezfntstrcpgbzjbf -547\r\naawtvezfntstrcpgbzjbf 600\r\nzhahpvqiptvksnbjkdvmknb -11\r\njpdwmyke 711\r\nbjmj 652\r\naawtvezfntstrcpgbzjbf -1000\r\naawtvezfntstrcpgbzjbf -171\r\nbjmj -302\r\naawtvezfntstrcpgbzjbf 961\r\nzhahpvqiptvksnbjkdvmknb 848\r\nbjmj -735\r\n", "output": "aawtvezfntstrcpgbzjbf\r\n"}, {"input": "17\r\nqdplghhx -649\r\nivhgbxiv 424\r\nivhgbxiv -72\r\nivhgbxiv 479\r\nugowfouebkelargxylsxn 83\r\nugowfouebkelargxylsxn -840\r\nivhgbxiv 382\r\nqdplghhx -904\r\nivhgbxiv -710\r\nugowfouebkelargxylsxn -838\r\nqdplghhx -974\r\nqdplghhx 571\r\nivhgbxiv -145\r\nugowfouebkelargxylsxn -788\r\nivhgbxiv 209\r\nivhgbxiv 420\r\nqdplghhx -158\r\n", "output": "ivhgbxiv\r\n"}]
false
stdio
null
true
981/C
981
C
Python 3
PRETESTS
4
514
10,035,200
38668479
n=int(input()) g=[[] for i in range(n)] for i in range(n-1): v,u=list(map(int,input().split())) g[v-1].append(u) g[u-1].append(v) t=True t1=False raiz=-1 for i in range(n): if len(g[i])>2: if len(g[i])==n-1: t1=True raiz=i+1 else: t=False break if t==False: print("No") elif t1==True: print("Yes") print(n-1) for i in range(1,n+1): if i!=raiz: print(raiz,i) else: hc=[] print("Yes") print(1) for i in range(n): if len(g[i])==1: hc.append(i) print(hc[0]+1,hc[1]+1)
47
421
11,059,200
38703825
import sys n = int(sys.stdin.readline()) degree = [0 for i in range(n + 1)] for i in range(n - 1): u, v = map(int, sys.stdin.readline().split()) degree[u]+=1 degree[v]+=1 ok = sum([int(degree[u] > 2) for u in range(n + 1)]) < 2 if not ok: print('No') sys.exit() print('Yes') maxdeg = max(degree) center = degree.index(maxdeg) ends = [] [ends.append(i) for i in range(n + 1) if degree[i] == 1 ] if maxdeg == 2 or n == 2: print(1) print(ends[0], ends[1]) else: print(len(ends)) [print(center, i) for i in ends]
Avito Code Challenge 2018
CF
2,018
1
256
Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path. Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.
If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$. Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.
null
The tree from the first example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. The tree from the second example is shown on the picture below: We can show that there are no valid decompositions of this tree. The tree from the third example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
[{"input": "4\n1 2\n2 3\n3 4", "output": "Yes\n1\n1 4"}, {"input": "6\n1 2\n2 3\n3 4\n2 5\n3 6", "output": "No"}, {"input": "5\n1 2\n1 3\n1 4\n1 5", "output": "Yes\n4\n1 2\n1 3\n1 4\n1 5"}]
1,400
["implementation", "trees"]
47
[{"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "Yes\r\n1\r\n1 4\r\n"}, {"input": "6\r\n1 2\r\n2 3\r\n3 4\r\n2 5\r\n3 6\r\n", "output": "No\r\n"}, {"input": "5\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "Yes\r\n4\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n"}, {"input": "2\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 2\r\n"}, {"input": "8\r\n1 2\r\n1 3\r\n1 4\r\n1 8\r\n7 8\r\n6 8\r\n5 8\r\n", "output": "No\r\n"}, {"input": "9\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n6 7\r\n7 8\r\n7 9\r\n", "output": "No\r\n"}, {"input": "3\r\n2 3\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 3\r\n"}]
false
stdio
import sys from sys import stdin from collections import deque def main(input_path, output_path, submission_path): # Read input tree with open(input_path) as f: n = int(f.readline()) adj = [[] for _ in range(n+1)] edges = set() for _ in range(n-1): a, b = map(int, f.readline().split()) adj[a].append(b) adj[b].append(a) edges.add(frozenset((a, b))) # Read reference output's first line with open(output_path) as f_ref: ref_first_line = f_ref.readline().strip() # Read submission output with open(submission_path) as f_sub: lines = [line.strip() for line in f_sub.readlines() if line.strip()] if not lines: print(0) return first_line = lines[0] if first_line == "No": if ref_first_line == "No": print(1) else: print(0) return elif first_line != "Yes": print(0) return if len(lines) < 2: print(0) return try: m = int(lines[1]) except: print(0) return if len(lines) != 2 + m: print(0) return paths = [] for line in lines[2:2+m]: try: u, v = map(int, line.split()) if u == v: print(0) return paths.append((u, v)) except: print(0) return # Build LCA structure LOG = 20 parent = [[-1]*(n+1) for _ in range(LOG)] depth = [0]*(n+1) # BFS to set up parent[0] and depth visited = [False]*(n+1) q = deque() q.append(1) visited[1] = True parent[0][1] = -1 while q: u = q.popleft() for v in adj[u]: if not visited[v]: visited[v] = True parent[0][v] = u depth[v] = depth[u] + 1 q.append(v) # Fill parent table for k in range(1, LOG): for v in range(1, n+1): if parent[k-1][v] != -1: parent[k][v] = parent[k-1][parent[k-1][v]] def lca(u, v): if depth[u] < depth[v]: u, v = v, u for k in range(LOG-1, -1, -1): if depth[u] - (1 << k) >= depth[v]: u = parent[k][u] if u == v: return u for k in range(LOG-1, -1, -1): if parent[k][u] != -1 and parent[k][u] != parent[k][v]: u = parent[k][u] v = parent[k][v] return parent[0][u] # Function to check if c is on the path between u and v def is_on_path(u, v, c): l = lca(u, v) if lca(u, c) == c and lca(c, v) == l: return True if lca(v, c) == c and lca(c, u) == l: return True return False # Check edge coverage count = [0]*(n+1) for u, v in paths: l = lca(u, v) count[u] += 1 count[v] += 1 count[l] -= 2 # Post-order traversal visited = [False]*(n+1) stack = [] stack.append((1, False)) while stack: node, processed = stack.pop() if processed: for child in adj[node]: if child != parent[0][node]: count[node] += count[child] if parent[0][node] != -1: edge = frozenset((parent[0][node], node)) if count[node] != 1: print(0) return else: stack.append((node, True)) for child in adj[node]: if child != parent[0][node]: stack.append((child, False)) # Check common vertex u1, v1 = paths[0] l = lca(u1, v1) path_nodes = set() current = u1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(l) current = v1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(v1) common_c = None for c in path_nodes: valid = True for u, v in paths: if not is_on_path(u, v, c): valid = False break if valid: common_c = c break if common_c is None: print(0) return print(1) if __name__ == "__main__": input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] main(input_path, output_path, submission_path)
true
981/C
981
C
PyPy 3
TESTS
4
935
19,148,800
71829990
n = int(input()) ab = [tuple(map(int, input().split())) for _ in range(n-1)] deg = [0]*n for a, b in ab: deg[a-1] += 1 deg[b-1] += 1 ideg = [(i, deg[i]) for i in range(n)] ideg.sort(key=lambda k: k[1]) deg2 = [ideg[i][1] for i in range(n)] if deg2==[1]*2+[2]*(n-2): print('Yes') print(1) print(ideg[0][0]+1, ideg[1][0]+1) elif deg2==[1]*(n-1)+[deg2[-1]]: print('Yes') print(n-1) for a, b in ab: print(a, b) else: print('No')
47
436
37,785,600
160404380
from sys import stdin input=stdin.readline read=lambda :map(int,input().strip().split()) from collections import defaultdict n=int(input()) deg=[0]*n g=defaultdict(list) for i in range(n-1): x,y=read() x-=1 y-=1 deg[x]+=1 deg[y]+=1 g[x].append(y) g[y].append(x) c=0 res=0 for i in range(n): if deg[i]>=3: c+=1 if deg[i]>=res: root=i res=deg[i] if c>=2: print("No") exit() leaf=[] for i in range(0,n): if len(g[i])==1 and i!=root: leaf.append(i) print("Yes") print(len(leaf)) for i in leaf: print(root+1,i+1)
Avito Code Challenge 2018
CF
2,018
1
256
Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path. Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.
If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$. Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.
null
The tree from the first example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. The tree from the second example is shown on the picture below: We can show that there are no valid decompositions of this tree. The tree from the third example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
[{"input": "4\n1 2\n2 3\n3 4", "output": "Yes\n1\n1 4"}, {"input": "6\n1 2\n2 3\n3 4\n2 5\n3 6", "output": "No"}, {"input": "5\n1 2\n1 3\n1 4\n1 5", "output": "Yes\n4\n1 2\n1 3\n1 4\n1 5"}]
1,400
["implementation", "trees"]
47
[{"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "Yes\r\n1\r\n1 4\r\n"}, {"input": "6\r\n1 2\r\n2 3\r\n3 4\r\n2 5\r\n3 6\r\n", "output": "No\r\n"}, {"input": "5\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "Yes\r\n4\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n"}, {"input": "2\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 2\r\n"}, {"input": "8\r\n1 2\r\n1 3\r\n1 4\r\n1 8\r\n7 8\r\n6 8\r\n5 8\r\n", "output": "No\r\n"}, {"input": "9\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n6 7\r\n7 8\r\n7 9\r\n", "output": "No\r\n"}, {"input": "3\r\n2 3\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 3\r\n"}]
false
stdio
import sys from sys import stdin from collections import deque def main(input_path, output_path, submission_path): # Read input tree with open(input_path) as f: n = int(f.readline()) adj = [[] for _ in range(n+1)] edges = set() for _ in range(n-1): a, b = map(int, f.readline().split()) adj[a].append(b) adj[b].append(a) edges.add(frozenset((a, b))) # Read reference output's first line with open(output_path) as f_ref: ref_first_line = f_ref.readline().strip() # Read submission output with open(submission_path) as f_sub: lines = [line.strip() for line in f_sub.readlines() if line.strip()] if not lines: print(0) return first_line = lines[0] if first_line == "No": if ref_first_line == "No": print(1) else: print(0) return elif first_line != "Yes": print(0) return if len(lines) < 2: print(0) return try: m = int(lines[1]) except: print(0) return if len(lines) != 2 + m: print(0) return paths = [] for line in lines[2:2+m]: try: u, v = map(int, line.split()) if u == v: print(0) return paths.append((u, v)) except: print(0) return # Build LCA structure LOG = 20 parent = [[-1]*(n+1) for _ in range(LOG)] depth = [0]*(n+1) # BFS to set up parent[0] and depth visited = [False]*(n+1) q = deque() q.append(1) visited[1] = True parent[0][1] = -1 while q: u = q.popleft() for v in adj[u]: if not visited[v]: visited[v] = True parent[0][v] = u depth[v] = depth[u] + 1 q.append(v) # Fill parent table for k in range(1, LOG): for v in range(1, n+1): if parent[k-1][v] != -1: parent[k][v] = parent[k-1][parent[k-1][v]] def lca(u, v): if depth[u] < depth[v]: u, v = v, u for k in range(LOG-1, -1, -1): if depth[u] - (1 << k) >= depth[v]: u = parent[k][u] if u == v: return u for k in range(LOG-1, -1, -1): if parent[k][u] != -1 and parent[k][u] != parent[k][v]: u = parent[k][u] v = parent[k][v] return parent[0][u] # Function to check if c is on the path between u and v def is_on_path(u, v, c): l = lca(u, v) if lca(u, c) == c and lca(c, v) == l: return True if lca(v, c) == c and lca(c, u) == l: return True return False # Check edge coverage count = [0]*(n+1) for u, v in paths: l = lca(u, v) count[u] += 1 count[v] += 1 count[l] -= 2 # Post-order traversal visited = [False]*(n+1) stack = [] stack.append((1, False)) while stack: node, processed = stack.pop() if processed: for child in adj[node]: if child != parent[0][node]: count[node] += count[child] if parent[0][node] != -1: edge = frozenset((parent[0][node], node)) if count[node] != 1: print(0) return else: stack.append((node, True)) for child in adj[node]: if child != parent[0][node]: stack.append((child, False)) # Check common vertex u1, v1 = paths[0] l = lca(u1, v1) path_nodes = set() current = u1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(l) current = v1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(v1) common_c = None for c in path_nodes: valid = True for u, v in paths: if not is_on_path(u, v, c): valid = False break if valid: common_c = c break if common_c is None: print(0) return print(1) if __name__ == "__main__": input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] main(input_path, output_path, submission_path)
true
981/C
981
C
PyPy 3
PRETESTS
6
904
8,806,400
38664303
if __name__ == "__main__": n = int(input()) deg = [0] * (n+1) for i in range(n-1): x, y = map(int, input().split()) deg[x] += 1 deg[y] += 1 if len(list(filter(lambda x : x > 2, deg))) > 1: print("No") else: print("Yes") d1 = [i for i in range(1, n+1) if deg[i] == 1] print(len(d1)//2) for i in range(0, len(d1)//2*2, 2): print(d1[i], d1[i+1]) if len(d1)%2 == 1: print(d1[-1], deg.index(max(deg)))
47
436
76,083,200
93736668
# Author: S Mahesh Raju # Username: maheshraju2020 # Created on: 25/09/2020 03:49:27 from sys import stdin, stdout, setrecursionlimit import heapq from math import gcd, ceil, sqrt from collections import Counter, deque from bisect import bisect_left, bisect_right from itertools import combinations, permutations ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int, stdin.readline().strip().split())) isa = lambda: stdin.readline().strip().split() setrecursionlimit(100000) mod = 1000000007 n = ii1() deg = [0] * n for i in range(n - 1): a, b = iia() deg[a - 1] += 1 deg[b - 1] += 1 count = node = 0 ans = [] for i in range(n): if deg[i] > 2: count += 1 node = i elif deg[i] == 1: ans.append(i) if count > 1: print('No') else: print('Yes') print(deg[node]) for i in ans: if node != i: print(node + 1, i + 1)
Avito Code Challenge 2018
CF
2,018
1
256
Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path. Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.
If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$. Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.
null
The tree from the first example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. The tree from the second example is shown on the picture below: We can show that there are no valid decompositions of this tree. The tree from the third example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
[{"input": "4\n1 2\n2 3\n3 4", "output": "Yes\n1\n1 4"}, {"input": "6\n1 2\n2 3\n3 4\n2 5\n3 6", "output": "No"}, {"input": "5\n1 2\n1 3\n1 4\n1 5", "output": "Yes\n4\n1 2\n1 3\n1 4\n1 5"}]
1,400
["implementation", "trees"]
47
[{"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "Yes\r\n1\r\n1 4\r\n"}, {"input": "6\r\n1 2\r\n2 3\r\n3 4\r\n2 5\r\n3 6\r\n", "output": "No\r\n"}, {"input": "5\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "Yes\r\n4\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n"}, {"input": "2\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 2\r\n"}, {"input": "8\r\n1 2\r\n1 3\r\n1 4\r\n1 8\r\n7 8\r\n6 8\r\n5 8\r\n", "output": "No\r\n"}, {"input": "9\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n6 7\r\n7 8\r\n7 9\r\n", "output": "No\r\n"}, {"input": "3\r\n2 3\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 3\r\n"}]
false
stdio
import sys from sys import stdin from collections import deque def main(input_path, output_path, submission_path): # Read input tree with open(input_path) as f: n = int(f.readline()) adj = [[] for _ in range(n+1)] edges = set() for _ in range(n-1): a, b = map(int, f.readline().split()) adj[a].append(b) adj[b].append(a) edges.add(frozenset((a, b))) # Read reference output's first line with open(output_path) as f_ref: ref_first_line = f_ref.readline().strip() # Read submission output with open(submission_path) as f_sub: lines = [line.strip() for line in f_sub.readlines() if line.strip()] if not lines: print(0) return first_line = lines[0] if first_line == "No": if ref_first_line == "No": print(1) else: print(0) return elif first_line != "Yes": print(0) return if len(lines) < 2: print(0) return try: m = int(lines[1]) except: print(0) return if len(lines) != 2 + m: print(0) return paths = [] for line in lines[2:2+m]: try: u, v = map(int, line.split()) if u == v: print(0) return paths.append((u, v)) except: print(0) return # Build LCA structure LOG = 20 parent = [[-1]*(n+1) for _ in range(LOG)] depth = [0]*(n+1) # BFS to set up parent[0] and depth visited = [False]*(n+1) q = deque() q.append(1) visited[1] = True parent[0][1] = -1 while q: u = q.popleft() for v in adj[u]: if not visited[v]: visited[v] = True parent[0][v] = u depth[v] = depth[u] + 1 q.append(v) # Fill parent table for k in range(1, LOG): for v in range(1, n+1): if parent[k-1][v] != -1: parent[k][v] = parent[k-1][parent[k-1][v]] def lca(u, v): if depth[u] < depth[v]: u, v = v, u for k in range(LOG-1, -1, -1): if depth[u] - (1 << k) >= depth[v]: u = parent[k][u] if u == v: return u for k in range(LOG-1, -1, -1): if parent[k][u] != -1 and parent[k][u] != parent[k][v]: u = parent[k][u] v = parent[k][v] return parent[0][u] # Function to check if c is on the path between u and v def is_on_path(u, v, c): l = lca(u, v) if lca(u, c) == c and lca(c, v) == l: return True if lca(v, c) == c and lca(c, u) == l: return True return False # Check edge coverage count = [0]*(n+1) for u, v in paths: l = lca(u, v) count[u] += 1 count[v] += 1 count[l] -= 2 # Post-order traversal visited = [False]*(n+1) stack = [] stack.append((1, False)) while stack: node, processed = stack.pop() if processed: for child in adj[node]: if child != parent[0][node]: count[node] += count[child] if parent[0][node] != -1: edge = frozenset((parent[0][node], node)) if count[node] != 1: print(0) return else: stack.append((node, True)) for child in adj[node]: if child != parent[0][node]: stack.append((child, False)) # Check common vertex u1, v1 = paths[0] l = lca(u1, v1) path_nodes = set() current = u1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(l) current = v1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(v1) common_c = None for c in path_nodes: valid = True for u, v in paths: if not is_on_path(u, v, c): valid = False break if valid: common_c = c break if common_c is None: print(0) return print(1) if __name__ == "__main__": input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] main(input_path, output_path, submission_path)
true
347/B
347
B
Python 3
TESTS
10
278
14,438,400
116116269
n = int(input()) a = list(map(int, input().split())) count = 0 for i in range(n): if a[i] == i: count += 1 for i in range(0,n): val = a[i] if a[val] == i and val != i: print(count + 2) exit() print(count+1)
19
156
13,516,800
169341636
n = int(input()) values = list(map(int, input().split())) ans = 0 to_add = 0 for x in range(n): if values[x] == x: ans += 1 elif to_add == 2: continue else: if values[values[x]] == x: to_add = 2 else: to_add = 1 print(ans + to_add)
Codeforces Round 201 (Div. 2)
CF
2,013
2
256
Fixed Points
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
null
null
[{"input": "5\n0 1 3 4 2", "output": "3"}]
1,100
["brute force", "implementation", "math"]
19
[{"input": "5\r\n0 1 3 4 2\r\n", "output": "3\r\n"}, {"input": "10\r\n6 9 4 7 8 2 3 5 0 1\r\n", "output": "2\r\n"}, {"input": "100\r\n99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67\r\n", "output": "3\r\n"}, {"input": "3\r\n0 1 2\r\n", "output": "3\r\n"}, {"input": "3\r\n2 1 0\r\n", "output": "3\r\n"}, {"input": "3\r\n1 2 0\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}, {"input": "5\r\n0 1 2 3 4\r\n", "output": "5\r\n"}, {"input": "4\r\n0 1 2 3\r\n", "output": "4\r\n"}, {"input": "7\r\n0 1 2 4 3 6 5\r\n", "output": "5\r\n"}, {"input": "6\r\n0 1 2 3 5 4\r\n", "output": "6\r\n"}]
false
stdio
null
true
347/B
347
B
Python 3
TESTS
10
248
7,065,600
4544469
n = int(input()) a = list(map(int, input().split())) c = 0 for i in range(n): if a[i] == i: c += 1 for i in range(n): if a[i] != i and a[a[i]] == i: c += 2 break else: c += 1 print(c)
19
156
13,516,800
195629894
input() a=list(map(int,input().split())) b=0 c=0 for i in a: if a[i]==i:b+=1 elif a[a[i]]==i:c+=1 print(b+2 if c else min(b+1,len(a)))
Codeforces Round 201 (Div. 2)
CF
2,013
2
256
Fixed Points
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
null
null
[{"input": "5\n0 1 3 4 2", "output": "3"}]
1,100
["brute force", "implementation", "math"]
19
[{"input": "5\r\n0 1 3 4 2\r\n", "output": "3\r\n"}, {"input": "10\r\n6 9 4 7 8 2 3 5 0 1\r\n", "output": "2\r\n"}, {"input": "100\r\n99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67\r\n", "output": "3\r\n"}, {"input": "3\r\n0 1 2\r\n", "output": "3\r\n"}, {"input": "3\r\n2 1 0\r\n", "output": "3\r\n"}, {"input": "3\r\n1 2 0\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}, {"input": "5\r\n0 1 2 3 4\r\n", "output": "5\r\n"}, {"input": "4\r\n0 1 2 3\r\n", "output": "4\r\n"}, {"input": "7\r\n0 1 2 4 3 6 5\r\n", "output": "5\r\n"}, {"input": "6\r\n0 1 2 3 5 4\r\n", "output": "6\r\n"}]
false
stdio
null
true
347/B
347
B
Python 3
TESTS
10
248
12,800,000
26415447
'''input 100 99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67 ''' n = int(input()) a = list(map(int, input().split())) s, t = 0, 1 for x in range(n): if a[x] == x: s += 1 elif t == 1 and a[a[x]] == x: t = 2 print(s + t)
19
186
6,963,200
147915955
n=int(input()) c=0 t=0 a=list(map(int,input().split())) for i in range(n): if a[i]==i: c+=1 elif i==a[a[i]]: t=1 print(c+t+int(c!=n))
Codeforces Round 201 (Div. 2)
CF
2,013
2
256
Fixed Points
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
null
null
[{"input": "5\n0 1 3 4 2", "output": "3"}]
1,100
["brute force", "implementation", "math"]
19
[{"input": "5\r\n0 1 3 4 2\r\n", "output": "3\r\n"}, {"input": "10\r\n6 9 4 7 8 2 3 5 0 1\r\n", "output": "2\r\n"}, {"input": "100\r\n99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67\r\n", "output": "3\r\n"}, {"input": "3\r\n0 1 2\r\n", "output": "3\r\n"}, {"input": "3\r\n2 1 0\r\n", "output": "3\r\n"}, {"input": "3\r\n1 2 0\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}, {"input": "5\r\n0 1 2 3 4\r\n", "output": "5\r\n"}, {"input": "4\r\n0 1 2 3\r\n", "output": "4\r\n"}, {"input": "7\r\n0 1 2 4 3 6 5\r\n", "output": "5\r\n"}, {"input": "6\r\n0 1 2 3 5 4\r\n", "output": "6\r\n"}]
false
stdio
null
true
347/B
347
B
Python 3
TESTS
10
310
9,932,800
109827339
n = int(input()) arr = list(map(int, input().split())) d = {} ans = 0 flag = False for i,x in enumerate(arr): d[i] = x if i == x: ans += 1 for i in d: if i != d[i] and d[d[i]] == i: ans += 2 flag = True break if flag: print(ans) else: print(ans + 1)
19
186
6,963,200
149253802
z = int(input()) out, swap = 0, [1] n = list(map(int, input().split())) for i in range(z): if i == n[i]: out += 1 elif n[n[i]] == i and n[i] == n.index(i): swap.append(2) print(out + max(swap) if z-out >= 2 else out)
Codeforces Round 201 (Div. 2)
CF
2,013
2
256
Fixed Points
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
null
null
[{"input": "5\n0 1 3 4 2", "output": "3"}]
1,100
["brute force", "implementation", "math"]
19
[{"input": "5\r\n0 1 3 4 2\r\n", "output": "3\r\n"}, {"input": "10\r\n6 9 4 7 8 2 3 5 0 1\r\n", "output": "2\r\n"}, {"input": "100\r\n99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67\r\n", "output": "3\r\n"}, {"input": "3\r\n0 1 2\r\n", "output": "3\r\n"}, {"input": "3\r\n2 1 0\r\n", "output": "3\r\n"}, {"input": "3\r\n1 2 0\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}, {"input": "5\r\n0 1 2 3 4\r\n", "output": "5\r\n"}, {"input": "4\r\n0 1 2 3\r\n", "output": "4\r\n"}, {"input": "7\r\n0 1 2 4 3 6 5\r\n", "output": "5\r\n"}, {"input": "6\r\n0 1 2 3 5 4\r\n", "output": "6\r\n"}]
false
stdio
null
true
347/B
347
B
Python 3
TESTS
10
248
16,486,400
128978744
n=int(input()) a=list(map(int, input().split())) d=dict() c=0 for i in range(n): if i==a[i]: c+=1 else: d[i]=a[i] for i in d: if d[d[i]]==i: print(c+2) exit(0) print(c+1)
19
186
6,963,200
197559185
n=int(input()) arr=list(map(int,input().split())) f=True a=1 c=0 for i in range(len(arr)): if arr[i]==i: c+=1 elif f and arr[arr[i]]==i: f=False a=2 if c==n: print(c) else: print(c+a)
Codeforces Round 201 (Div. 2)
CF
2,013
2
256
Fixed Points
A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.
The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.
Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.
null
null
[{"input": "5\n0 1 3 4 2", "output": "3"}]
1,100
["brute force", "implementation", "math"]
19
[{"input": "5\r\n0 1 3 4 2\r\n", "output": "3\r\n"}, {"input": "10\r\n6 9 4 7 8 2 3 5 0 1\r\n", "output": "2\r\n"}, {"input": "100\r\n99 5 40 32 4 31 38 57 94 47 26 16 89 72 9 80 55 86 78 90 42 41 46 74 56 97 21 48 66 27 93 85 88 59 64 95 10 45 12 22 84 60 8 98 62 51 14 65 39 30 11 71 92 19 76 43 87 54 15 53 37 6 25 18 96 35 13 91 2 3 0 23 1 7 49 75 81 33 50 52 63 44 69 36 17 61 24 20 68 34 73 29 70 83 58 79 82 28 77 67\r\n", "output": "3\r\n"}, {"input": "3\r\n0 1 2\r\n", "output": "3\r\n"}, {"input": "3\r\n2 1 0\r\n", "output": "3\r\n"}, {"input": "3\r\n1 2 0\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}, {"input": "5\r\n0 1 2 3 4\r\n", "output": "5\r\n"}, {"input": "4\r\n0 1 2 3\r\n", "output": "4\r\n"}, {"input": "7\r\n0 1 2 4 3 6 5\r\n", "output": "5\r\n"}, {"input": "6\r\n0 1 2 3 5 4\r\n", "output": "6\r\n"}]
false
stdio
null
true
981/C
981
C
Python 3
TESTS
4
436
31,846,400
127043044
# _ ##################################################################################################################### def main(): nNodes = int(input()) neighborsOf = {node: [] for node in map(str, range(1, nNodes+1))} threeNeighborNodeExists, threeNeighborNode = False, None for i in range(1, nNodes): node1, node2 = input().split() neighborsOf[node1].append(node2), neighborsOf[node2].append(node1) if len(neighborsOf[node1]) == 3: if threeNeighborNodeExists: return 'No' threeNeighborNodeExists, threeNeighborNode = True, node1 elif len(neighborsOf[node2]) == 3: if threeNeighborNodeExists: return 'No' threeNeighborNodeExists, threeNeighborNode = True, node2 if threeNeighborNodeExists: return tnnDecompositionFrom(neighborsOf, threeNeighborNode) return decompositionFrom(neighborsOf) def tnnDecompositionFrom(neighborsOf, threeNeighborNode): paths = [] for node in neighborsOf[threeNeighborNode]: prevNode = threeNeighborNode while len(neighborsOf[node]) != 1: node, prevNode = neighborsOf[node][0] if neighborsOf[node][0] == prevNode else neighborsOf[node][1], node paths.append(threeNeighborNode+' '+node) return f'Yes\n{len(paths)}\n' + '\n'.join(paths) def decompositionFrom(tree): return 'Yes\n1\n' + ' '.join(node for node in tree if len(tree[node]) == 1) if __name__ == '__main__': print(main()) # main()
47
467
2,048,000
132434813
def solve(): n = int(input()) deg = [0] * n for i in range(n - 1): u, v = map(int, input().split()) deg[u - 1] += 1 deg[v - 1] += 1 count = 0 root = 0 leaves = [] for i in range(n): if (deg[i] > 2): count += 1 root = i if (deg[i] == 1): leaves.append(i) if (count > 1): print("No") else: print("Yes") print(deg[root]) for leaf in leaves: if (leaf != root): print(root + 1, leaf + 1) solve()
Avito Code Challenge 2018
CF
2,018
1
256
Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path. Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.
If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$. Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.
null
The tree from the first example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. The tree from the second example is shown on the picture below: We can show that there are no valid decompositions of this tree. The tree from the third example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
[{"input": "4\n1 2\n2 3\n3 4", "output": "Yes\n1\n1 4"}, {"input": "6\n1 2\n2 3\n3 4\n2 5\n3 6", "output": "No"}, {"input": "5\n1 2\n1 3\n1 4\n1 5", "output": "Yes\n4\n1 2\n1 3\n1 4\n1 5"}]
1,400
["implementation", "trees"]
47
[{"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "Yes\r\n1\r\n1 4\r\n"}, {"input": "6\r\n1 2\r\n2 3\r\n3 4\r\n2 5\r\n3 6\r\n", "output": "No\r\n"}, {"input": "5\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "Yes\r\n4\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n"}, {"input": "2\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 2\r\n"}, {"input": "8\r\n1 2\r\n1 3\r\n1 4\r\n1 8\r\n7 8\r\n6 8\r\n5 8\r\n", "output": "No\r\n"}, {"input": "9\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n6 7\r\n7 8\r\n7 9\r\n", "output": "No\r\n"}, {"input": "3\r\n2 3\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 3\r\n"}]
false
stdio
import sys from sys import stdin from collections import deque def main(input_path, output_path, submission_path): # Read input tree with open(input_path) as f: n = int(f.readline()) adj = [[] for _ in range(n+1)] edges = set() for _ in range(n-1): a, b = map(int, f.readline().split()) adj[a].append(b) adj[b].append(a) edges.add(frozenset((a, b))) # Read reference output's first line with open(output_path) as f_ref: ref_first_line = f_ref.readline().strip() # Read submission output with open(submission_path) as f_sub: lines = [line.strip() for line in f_sub.readlines() if line.strip()] if not lines: print(0) return first_line = lines[0] if first_line == "No": if ref_first_line == "No": print(1) else: print(0) return elif first_line != "Yes": print(0) return if len(lines) < 2: print(0) return try: m = int(lines[1]) except: print(0) return if len(lines) != 2 + m: print(0) return paths = [] for line in lines[2:2+m]: try: u, v = map(int, line.split()) if u == v: print(0) return paths.append((u, v)) except: print(0) return # Build LCA structure LOG = 20 parent = [[-1]*(n+1) for _ in range(LOG)] depth = [0]*(n+1) # BFS to set up parent[0] and depth visited = [False]*(n+1) q = deque() q.append(1) visited[1] = True parent[0][1] = -1 while q: u = q.popleft() for v in adj[u]: if not visited[v]: visited[v] = True parent[0][v] = u depth[v] = depth[u] + 1 q.append(v) # Fill parent table for k in range(1, LOG): for v in range(1, n+1): if parent[k-1][v] != -1: parent[k][v] = parent[k-1][parent[k-1][v]] def lca(u, v): if depth[u] < depth[v]: u, v = v, u for k in range(LOG-1, -1, -1): if depth[u] - (1 << k) >= depth[v]: u = parent[k][u] if u == v: return u for k in range(LOG-1, -1, -1): if parent[k][u] != -1 and parent[k][u] != parent[k][v]: u = parent[k][u] v = parent[k][v] return parent[0][u] # Function to check if c is on the path between u and v def is_on_path(u, v, c): l = lca(u, v) if lca(u, c) == c and lca(c, v) == l: return True if lca(v, c) == c and lca(c, u) == l: return True return False # Check edge coverage count = [0]*(n+1) for u, v in paths: l = lca(u, v) count[u] += 1 count[v] += 1 count[l] -= 2 # Post-order traversal visited = [False]*(n+1) stack = [] stack.append((1, False)) while stack: node, processed = stack.pop() if processed: for child in adj[node]: if child != parent[0][node]: count[node] += count[child] if parent[0][node] != -1: edge = frozenset((parent[0][node], node)) if count[node] != 1: print(0) return else: stack.append((node, True)) for child in adj[node]: if child != parent[0][node]: stack.append((child, False)) # Check common vertex u1, v1 = paths[0] l = lca(u1, v1) path_nodes = set() current = u1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(l) current = v1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(v1) common_c = None for c in path_nodes: valid = True for u, v in paths: if not is_on_path(u, v, c): valid = False break if valid: common_c = c break if common_c is None: print(0) return print(1) if __name__ == "__main__": input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] main(input_path, output_path, submission_path)
true
509/C
509
C
PyPy 3
TESTS
3
109
0
120328026
def mk_minlen(l, x): digs = [1] + [0]*(l-1) x_digsum = 1 p = len(digs)-1 while x_digsum < x: while digs[p] == 9: p -= 1 digs[p] += 1 x_digsum += 1 return int(''.join(map(str, digs))) def solve(lo, x): s = str(lo) if x/9 > len(s): l = len(s) while x/9 > l: l += 1 digs = [9] * l x_digsum = sum(digs) p = 0 while x_digsum > x: while p < len(digs) and digs[p] == 1: p += 1 digs[p] -= 1 x_digsum -= 1 return int(''.join(map(str, digs))) digs = list(int(c) for c in s) x_digsum = sum(digs) if x_digsum >= x: alts = []; odigs = [*digs] for p in range(len(digs)): digs = [*odigs] if digs[p] == 9: continue digs[p] += 1 x_digsum += 1 p += 1 while x_digsum > x: while p < len(digs) and digs[p] == 0: p += 1 if p == len(digs): break x_digsum -= 1 digs[p] -= 1 if x_digsum > x: continue alts.append(int(''.join(map(str, digs)))) alts.sort() if alts: return alts[0] return mk_minlen(len(digs)+1, x) p = len(digs)-1 while x_digsum < x: while p >= 0 and digs[p] == 9: p -= 1 digs[p] += 1 x_digsum += 1 return int(''.join(map(str, digs))) n = int(input()) prev = 0 for _ in range(n): prev = solve(prev, int(input())) print(prev)
21
93
5,427,200
153762868
import sys def get_max(su, le): div, mod = divmod(su, 9) ret = ['9'] * div if mod: ret = [str(mod)] + ret if le - len(ret) > 0: x = str(int(ret.pop(0)) - 1) ret = ['1', x] + ret if le - len(ret) > 0: ret = [ret[0]] + ['0'] * (le - len(ret)) + ret[1:] return ret def get_max2(su, le): div, mod = divmod(su, 9) ret = ['9'] * div if mod: ret = [str(mod)] + ret return ['0'] * (le - len(ret)) + ret input = lambda: sys.stdin.buffer.readline().decode().strip() lst = ['0'] for _ in range(int(input())): su = int(input()) le = su // 9 + bool(su % 9) if le > len(lst): lst = get_max(su, le) else: rem, ix = su, -1 for i in range(len(lst)): if int(lst[i]) > rem: break if lst[i] != '9' and rem > int(lst[i]) and 9 * (len(lst) - i) >= rem: ix = i rem -= int(lst[i]) if ix == -1: lst = get_max(su, len(lst) + 1) else: rem = su - sum([int(lst[i]) for i in range(ix + 1)]) cur = 1 for i in range(int(lst[ix]) + 1, 10): rem -= 1 if (len(lst) - ix - 1) * 9 >= rem: break cur += 1 lst = lst[:ix] + [str(int(lst[ix]) + cur)] + get_max2(rem, len(lst) - ix - 1) print(''.join(lst))
Codeforces Round 289 (Div. 2, ACM ICPC Rules)
ICPC
2,015
2
256
Sums of Digits
Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi. Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence. It is guaranteed that such a sequence always exists.
The first line contains a single integer number n (1 ≤ n ≤ 300). Next n lines contain integer numbers b1, ..., bn  — the required sums of digits. All bi belong to the range 1 ≤ bi ≤ 300.
Print n integer numbers, one per line — the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi. If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.
null
null
[{"input": "3\n1\n2\n3", "output": "1\n2\n3"}, {"input": "3\n3\n2\n1", "output": "3\n11\n100"}]
2,000
["dp", "greedy", "implementation"]
21
[{"input": "3\r\n1\r\n2\r\n3\r\n", "output": "1\r\n2\r\n3\r\n"}, {"input": "3\r\n3\r\n2\r\n1\r\n", "output": "3\r\n11\r\n100\r\n"}, {"input": "10\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n1\r\n", "output": "1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n"}, {"input": "10\r\n8\r\n8\r\n5\r\n1\r\n2\r\n7\r\n3\r\n8\r\n9\r\n4\r\n", "output": "8\r\n17\r\n23\r\n100\r\n101\r\n106\r\n111\r\n116\r\n117\r\n121\r\n"}, {"input": "10\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n", "output": "1\r\n10\r\n100\r\n1000\r\n10000\r\n100000\r\n1000000\r\n10000000\r\n100000000\r\n1000000000\r\n"}, {"input": "100\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n1\r\n", "output": "1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24\r\n25\r\n26\r\n27\r\n28\r\n29\r\n30\r\n31\r\n32\r\n33\r\n34\r\n35\r\n36\r\n37\r\n38\r\n39\r\n40\r\n41\r\n42\r\n43\r\n44\r\n45\r\n46\r\n47\r\n48\r\n49\r\n50\r\n51\r\n52\r\n53\r\n54\r\n55\r\n56\r\n57\r\n58\r\n59\r\n60\r\n61\r\n62\r\n63\r\n64\r\n65\r\n66\r\n67\r\n68\r\n69\r\n70\r\n71\r\n72\r\n73\r\n74\r\n75\r\n76\r\n77\r\n78\r\n79\r\n80\r\n81\r\n82\r\n83\r\n84\r\n85\r\n86\r\n87\r\n88\r\n89\r\n90\r\n91\r\n92\r\n93\r\n94\r\n95\r\n96\r\n97\r\n98\r\n99\r\n100\r\n"}, {"input": "100\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n", "output": "99\n189\n198\n279\n288\n297\n369\n378\n387\n396\n459\n468\n477\n486\n495\n549\n558\n567\n576\n585\n594\n639\n648\n657\n666\n675\n684\n693\n729\n738\n747\n756\n765\n774\n783\n792\n819\n828\n837\n846\n855\n864\n873\n882\n891\n909\n918\n927\n936\n945\n954\n963\n972\n981\n990\n1089\n1098\n1179\n1188\n1197\n1269\n1278\n1287\n1296\n1359\n1368\n1377\n1386\n1395\n1449\n1458\n1467\n1476\n1485\n1494\n1539\n1548\n1557\n1566\n1575\n1584\n1593\n1629\n1638\n1647\n1656\n1665\n1674\n1683\n1692\n1719\n1728\n1737\n1746\n1755\n1764\n1773\n1782\n1791\n1809\n"}, {"input": "1\r\n139\r\n", "output": "4999999999999999\r\n"}, {"input": "1\r\n6\r\n", "output": "6\r\n"}]
false
stdio
null
true
981/C
981
C
PyPy 3
TESTS
4
498
18,636,800
78371185
from collections import * import math from sys import * inp=stdin.readline str=str flag=1 if not flag: out=stdout.write else: out=print def linp(x): return list(map(int,x.split())) def minp(x): return map(int,x.split()) n=int(inp()) graph=defaultdict(list) while n-1>0: a,b=minp(inp()) graph[a].append(b) graph[b].append(a) n-=1 li=[] for i in graph: if len(graph[i])>2: li.append(i) if len(li)>1: out("No") elif len(li)==0: out('Yes') out("1") l=[i for i in graph if len(graph[i])==1] print(*l) else: out("Yes") a=li[0] print(len(graph[a])) for ii in graph[a]: print(a,ii)
47
483
6,656,000
164651742
d = {} n = int(input()) for _ in range(n-1): a, b = map(int, input().split()) d[a] = d.get(a, 0) + 1 d[b] = d.get(b, 0) + 1 zz = list(filter(lambda x: d[x] > 2, d)) z = len(zz) y = list(filter(lambda x: d[x] == 1, d)) if z > 1: print("No") elif z == 0: print("Yes") print(1) print(*y) else: print("Yes") print(len(y)) for v in y: print(zz[0], v)
Avito Code Challenge 2018
CF
2,018
1
256
Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path. Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.
If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$. Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.
null
The tree from the first example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. The tree from the second example is shown on the picture below: We can show that there are no valid decompositions of this tree. The tree from the third example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
[{"input": "4\n1 2\n2 3\n3 4", "output": "Yes\n1\n1 4"}, {"input": "6\n1 2\n2 3\n3 4\n2 5\n3 6", "output": "No"}, {"input": "5\n1 2\n1 3\n1 4\n1 5", "output": "Yes\n4\n1 2\n1 3\n1 4\n1 5"}]
1,400
["implementation", "trees"]
47
[{"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "Yes\r\n1\r\n1 4\r\n"}, {"input": "6\r\n1 2\r\n2 3\r\n3 4\r\n2 5\r\n3 6\r\n", "output": "No\r\n"}, {"input": "5\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "Yes\r\n4\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n"}, {"input": "2\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 2\r\n"}, {"input": "8\r\n1 2\r\n1 3\r\n1 4\r\n1 8\r\n7 8\r\n6 8\r\n5 8\r\n", "output": "No\r\n"}, {"input": "9\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n6 7\r\n7 8\r\n7 9\r\n", "output": "No\r\n"}, {"input": "3\r\n2 3\r\n1 2\r\n", "output": "Yes\r\n1\r\n1 3\r\n"}]
false
stdio
import sys from sys import stdin from collections import deque def main(input_path, output_path, submission_path): # Read input tree with open(input_path) as f: n = int(f.readline()) adj = [[] for _ in range(n+1)] edges = set() for _ in range(n-1): a, b = map(int, f.readline().split()) adj[a].append(b) adj[b].append(a) edges.add(frozenset((a, b))) # Read reference output's first line with open(output_path) as f_ref: ref_first_line = f_ref.readline().strip() # Read submission output with open(submission_path) as f_sub: lines = [line.strip() for line in f_sub.readlines() if line.strip()] if not lines: print(0) return first_line = lines[0] if first_line == "No": if ref_first_line == "No": print(1) else: print(0) return elif first_line != "Yes": print(0) return if len(lines) < 2: print(0) return try: m = int(lines[1]) except: print(0) return if len(lines) != 2 + m: print(0) return paths = [] for line in lines[2:2+m]: try: u, v = map(int, line.split()) if u == v: print(0) return paths.append((u, v)) except: print(0) return # Build LCA structure LOG = 20 parent = [[-1]*(n+1) for _ in range(LOG)] depth = [0]*(n+1) # BFS to set up parent[0] and depth visited = [False]*(n+1) q = deque() q.append(1) visited[1] = True parent[0][1] = -1 while q: u = q.popleft() for v in adj[u]: if not visited[v]: visited[v] = True parent[0][v] = u depth[v] = depth[u] + 1 q.append(v) # Fill parent table for k in range(1, LOG): for v in range(1, n+1): if parent[k-1][v] != -1: parent[k][v] = parent[k-1][parent[k-1][v]] def lca(u, v): if depth[u] < depth[v]: u, v = v, u for k in range(LOG-1, -1, -1): if depth[u] - (1 << k) >= depth[v]: u = parent[k][u] if u == v: return u for k in range(LOG-1, -1, -1): if parent[k][u] != -1 and parent[k][u] != parent[k][v]: u = parent[k][u] v = parent[k][v] return parent[0][u] # Function to check if c is on the path between u and v def is_on_path(u, v, c): l = lca(u, v) if lca(u, c) == c and lca(c, v) == l: return True if lca(v, c) == c and lca(c, u) == l: return True return False # Check edge coverage count = [0]*(n+1) for u, v in paths: l = lca(u, v) count[u] += 1 count[v] += 1 count[l] -= 2 # Post-order traversal visited = [False]*(n+1) stack = [] stack.append((1, False)) while stack: node, processed = stack.pop() if processed: for child in adj[node]: if child != parent[0][node]: count[node] += count[child] if parent[0][node] != -1: edge = frozenset((parent[0][node], node)) if count[node] != 1: print(0) return else: stack.append((node, True)) for child in adj[node]: if child != parent[0][node]: stack.append((child, False)) # Check common vertex u1, v1 = paths[0] l = lca(u1, v1) path_nodes = set() current = u1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(l) current = v1 while current != l: path_nodes.add(current) current = parent[0][current] path_nodes.add(v1) common_c = None for c in path_nodes: valid = True for u, v in paths: if not is_on_path(u, v, c): valid = False break if valid: common_c = c break if common_c is None: print(0) return print(1) if __name__ == "__main__": input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] main(input_path, output_path, submission_path)
true
560/A
560
A
Python 3
TESTS
3
46
6,656,000
126622318
def get_unfortunate(notes): for note in notes: if int(note) == 1: return -1 return 1 if __name__ == "__main__": n = input() notes = input() notes = notes.replace(' ', "") print(get_unfortunate(notes))
16
31
0
165441045
num_inp=lambda: int(input()) arr_inp=lambda: list(map(int,input().split())) sp_inp=lambda: map(int,input().split()) input() print(('1' in input().split())*-2+1)
Codeforces Round 313 (Div. 2)
CF
2,015
2
256
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
null
null
[{"input": "5\n1 2 3 4 5", "output": "-1"}]
1,000
["implementation", "sortings"]
16
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "-1\r\n"}, {"input": "1\r\n2\r\n", "output": "1\r\n"}, {"input": "10\r\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837\r\n", "output": "-1\r\n"}, {"input": "10\r\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264\r\n", "output": "1\r\n"}, {"input": "50\r\n110876 835020 859879 999908 712969 788264 287153 921820 330355 499311 209594 484829 296329 940051 174081 931503 1 780512 390075 97866 124255 950067 697612 244256 782385 789882 37608 82153 399889 598867 416717 377988 535636 511221 792568 683271 131077 290194 496712 330720 587436 563481 645817 942562 654093 980561 382937 48293 582608 116156\r\n", "output": "-1\r\n"}, {"input": "50\r\n474421 421097 217233 156339 27075 733996 281778 863492 184707 956857 288561 70997 393786 337382 663642 131184 637 273801 799870 295017 392338 842567 161819 297705 102013 930684 375703 838048 154915 138503 629056 256591 893619 19263 787927 684541 320265 841090 421423 490879 394582 493952 619247 633202 612928 50907 276653 407819 489945 153173\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n", "output": "-1\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1\r\n"}, {"input": "2\r\n3 2\r\n", "output": "1\r\n"}, {"input": "2\r\n2 3\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
124
6,758,400
126467827
alcohols = 'ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE' ans= 0 for i in range(int(input())): a = input() if(a in alcohols): ans+=1 elif(48<=ord(a[0])<=57): if(int(a)<18): ans+=1 print(ans)
28
46
307,200
4927607
def readln(): return tuple(map(int, input().split())) lst = 'ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE'.split(', ') n, = readln() ans = 0 for _ in range(n): inp = input() try: if int(inp) < 18: ans += 1 except: if inp in lst: ans += 1 print(ans)
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
560/A
560
A
Python 3
TESTS
3
46
6,656,000
125110840
input() print(-1 if '1'in input().strip()else 1)
16
31
0
172437733
input();print(-1 if "1" in [i for i in input().split()] else 1)
Codeforces Round 313 (Div. 2)
CF
2,015
2
256
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
null
null
[{"input": "5\n1 2 3 4 5", "output": "-1"}]
1,000
["implementation", "sortings"]
16
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "-1\r\n"}, {"input": "1\r\n2\r\n", "output": "1\r\n"}, {"input": "10\r\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837\r\n", "output": "-1\r\n"}, {"input": "10\r\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264\r\n", "output": "1\r\n"}, {"input": "50\r\n110876 835020 859879 999908 712969 788264 287153 921820 330355 499311 209594 484829 296329 940051 174081 931503 1 780512 390075 97866 124255 950067 697612 244256 782385 789882 37608 82153 399889 598867 416717 377988 535636 511221 792568 683271 131077 290194 496712 330720 587436 563481 645817 942562 654093 980561 382937 48293 582608 116156\r\n", "output": "-1\r\n"}, {"input": "50\r\n474421 421097 217233 156339 27075 733996 281778 863492 184707 956857 288561 70997 393786 337382 663642 131184 637 273801 799870 295017 392338 842567 161819 297705 102013 930684 375703 838048 154915 138503 629056 256591 893619 19263 787927 684541 320265 841090 421423 490879 394582 493952 619247 633202 612928 50907 276653 407819 489945 153173\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n", "output": "-1\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1\r\n"}, {"input": "2\r\n3 2\r\n", "output": "1\r\n"}, {"input": "2\r\n2 3\r\n", "output": "1\r\n"}]
false
stdio
null
true
175/B
175
B
PyPy 3-64
TESTS
23
156
5,324,800
189917101
n=int(input()) dicti={} cost={} for i in range(n): n,m=map(str,input().split()) dicti[n]=max(int(m),dicti.get(n,0)) cost[int(m)]=cost.get(int(m),0)+1 cost=dict(sorted(cost.items(),reverse=True)) sumi=0 out=0 for i in cost: sumi=(out/len(dicti))*100 out=out+cost[i] if sumi>50: cost[i]="noob" elif sumi>20: cost[i]="random" elif sumi>10: cost[i]="average" elif sumi>1: cost[i]="hardcore" else: cost[i]="pro" print(len(dicti)) dicti1={} for i in dicti: dicti1[i]=cost[dicti[i]] dicti1=dict(sorted(dicti1.items())) for i in dicti1: print(i,dicti1[i])
46
124
512,000
29810660
from collections import defaultdict from bisect import bisect_left p, n = defaultdict(int), int(input()) for i in range(n): a, b = input().split() p[a] = max(p[a], int(b)) p, n = sorted((b, a) for a, b in p.items()), len(p) t = [0] + [bisect_left(p, (p[n - 1 - n // k][0], '')) for k in [2, 5, 10, 100]] + [n] s = ['noob', 'random', 'average', 'hardcore', 'pro'] for i in range(1, len(t)): d = s[i - 1] for j in range(t[i - 1], t[i]): p[j] = p[j][1] + ' ' + d print(n) print('\n'.join(p))
Codeforces Round 115
CF
2,012
2
256
Plane of Tanks: Pro
Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total. In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category: - "noob" — if more than 50% of players have better results; - "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results; - "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results; - "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results; - "pro" — if his result is not worse than the result that 99% of players have. When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have. Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.
The first line contains the only integer number n (1 ≤ n ≤ 1000) — a number of records with the players' results. Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.
Print on the first line the number m — the number of players, who participated in one round at least. Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.
null
In the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro". In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".
[{"input": "5\nvasya 100\nvasya 200\nartem 100\nkolya 200\nigor 250", "output": "4\nartem noob\nigor pro\nkolya random\nvasya random"}, {"input": "3\nvasya 200\nkolya 1000\nvasya 1000", "output": "2\nkolya pro\nvasya pro"}]
1,400
["implementation"]
78
[{"input": "5\r\nvasya 100\r\nvasya 200\r\nartem 100\r\nkolya 200\r\nigor 250\r\n", "output": "4\r\nartem noob\r\nigor pro\r\nkolya random\r\nvasya random\r\n"}, {"input": "3\r\nvasya 200\r\nkolya 1000\r\nvasya 1000\r\n", "output": "2\r\nkolya pro\r\nvasya pro\r\n"}, {"input": "1\r\nvasya 1000\r\n", "output": "1\r\nvasya pro\r\n"}, {"input": "5\r\nvasya 1000\r\nvasya 100\r\nkolya 200\r\npetya 300\r\noleg 400\r\n", "output": "4\r\nkolya noob\r\noleg random\r\npetya random\r\nvasya pro\r\n"}, {"input": "10\r\na 1\r\nb 2\r\nc 3\r\nd 4\r\ne 5\r\nf 6\r\ng 7\r\nh 8\r\ni 9\r\nj 10\r\n", "output": "10\r\na noob\r\nb noob\r\nc noob\r\nd noob\r\ne random\r\nf random\r\ng random\r\nh average\r\ni hardcore\r\nj pro\r\n"}, {"input": "10\r\nj 10\r\ni 9\r\nh 8\r\ng 7\r\nf 6\r\ne 5\r\nd 4\r\nc 3\r\nb 2\r\na 1\r\n", "output": "10\r\na noob\r\nb noob\r\nc noob\r\nd noob\r\ne random\r\nf random\r\ng random\r\nh average\r\ni hardcore\r\nj pro\r\n"}, {"input": "1\r\ntest 0\r\n", "output": "1\r\ntest pro\r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): # Read input data with open(input_path) as f: n = int(f.readline()) players = {} for _ in range(n): name, points = f.readline().strip().split() points = int(points) if name not in players or points > players[name]: players[name] = points m = len(players) best_scores = list(players.values()) # Compute correct categories correct = {} for name in players: score = players[name] cnt = sum(1 for s in best_scores if s > score) percentage = (cnt * 100.0) / m if percentage > 50: cat = 'noob' elif percentage > 20: cat = 'random' elif percentage > 10: cat = 'average' elif percentage > 1: cat = 'hardcore' else: cat = 'pro' correct[name] = cat # Read submission output with open(submission_path) as f: lines = f.read().splitlines() if not lines: print(0) return try: m_sub = int(lines[0]) except: print(0) return if m_sub != m: print(0) return submission = {} for line in lines[1:]: parts = line.strip().split() if len(parts) != 2: print(0) return name, cat = parts if name in submission: print(0) return submission[name] = cat # Check all players are present and correct if submission.keys() != correct.keys(): print(0) return for name, cat in submission.items(): if correct.get(name) != cat: print(0) return print(1) if __name__ == "__main__": input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] main(input_path, output_path, submission_path)
true
559/C
559
C
PyPy 3-64
TESTS
3
61
6,348,800
199045173
import bisect import heapq import sys from types import GeneratorType from functools import cmp_to_key from collections import defaultdict, Counter, deque import math from functools import lru_cache from heapq import nlargest from functools import reduce import random from itertools import combinations from itertools import accumulate from operator import xor from operator import mul inf = float("inf") PLATFORM = "CF" if PLATFORM == "LUOGU": import numpy as np sys.setrecursionlimit(1000000) class FastIO: def __init__(self): return @staticmethod def _read(): return sys.stdin.readline().strip() def read_int(self): return int(self._read()) def read_float(self): return float(self._read()) def read_ints(self): return map(int, self._read().split()) def read_floats(self): return map(float, self._read().split()) def read_ints_minus_one(self): return map(lambda x: int(x) - 1, self._read().split()) def read_list_ints(self): return list(map(int, self._read().split())) def read_list_floats(self): return list(map(float, self._read().split())) def read_list_ints_minus_one(self): return list(map(lambda x: int(x) - 1, self._read().split())) def read_str(self): return self._read() def read_list_strs(self): return self._read().split() def read_list_str(self): return list(self._read()) @staticmethod def st(x): return sys.stdout.write(str(x) + '\n') @staticmethod def lst(x): return sys.stdout.write(" ".join(str(w) for w in x) + '\n') @staticmethod def round_5(f): res = int(f) if f - res >= 0.5: res += 1 return res @staticmethod def max(a, b): return a if a > b else b @staticmethod def min(a, b): return a if a < b else b @staticmethod def bootstrap(f, queue=[]): def wrappedfunc(*args, **kwargs): if queue: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if isinstance(to, GeneratorType): queue.append(to) to = next(to) else: queue.pop() if not queue: break to = queue[-1].send(to) return to return wrappedfunc class Combinatorics: def __init__(self, n, mod): # 模板:求全排列组合数 self.perm = [1] * n self.rev = [1] * n self.mod = mod for i in range(1, n): # 阶乘数 i! 取模 self.perm[i] = self.perm[i - 1] * i self.perm[i] %= self.mod self.rev[-1] = pow(self.perm[-1], -1, self.mod) for i in range(n-2, 0, -1): self.rev[i] = (self.rev[i+1]*(i+1)%mod) return def comb(self, a, b): # 组合数根据乘法逆元求解 res = self.perm[a] * self.rev[b] * self.rev[a - b] return res % self.mod def main(ac=FastIO()): m, n, k = ac.read_ints() mod = 10**9 + 7 cb = Combinatorics(m+n, mod) pos = [ac.read_list_ints_minus_one() for _ in range(k)] pos.sort(key=lambda it: it[0]) def dist(x1, y1, x2, y2): return cb.comb(x2+y2-x1-y1, x2-x1) ans = dist(0, 0, m-1, n-1) bad = [] for x in range(k): i, j = pos[x] cur = dist(0, 0, i, j) for y in range(x): a, b = pos[y] if b <= j: cur -= dist(a, b, i, j)*bad[y] cur %= mod bad.append(cur) ans -= cur*dist(i, j, m-1, n-1) ans %= mod ac.st(ans) return main()
55
264
9,420,800
194862736
# The idea is to compute dp[i], the number of paths from top left to ith point. # Here, the first and last point = top left and bottom right respectively # To compute dp[i], we use complementary counting to remove paths that are invalid. # The idea is that each invalid path has a "last" black cell j that they go through, # after which the remaining ways for this path to get to the top left = dp[j]. MOD = 10**9 + 7 MAXN = 2*10**5 fac = [1] * (MAXN + 1) inv_fac = [0] * (MAXN + 1) for i in range(2, MAXN+1): fac[i] = i * fac[i-1] % MOD inv_fac[MAXN] = pow(fac[MAXN], -1, MOD) for i in range(MAXN-1, -1, -1): inv_fac[i] = inv_fac[i+1] * (i+1) % MOD def choose(n, k): return (fac[n] * inv_fac[k]) % MOD * inv_fac[n-k] % MOD h, w, n = map(int, input().split()) from collections import namedtuple Cell = namedtuple('Cell', ['r', 'c']) cells = [Cell(1, 1)] + [Cell(*map(int, input().split())) for _ in range(n)] + [Cell(h, w)] cells.sort() def num_paths(i, j): dr = abs(cells[i].r - cells[j].r) dc = abs(cells[i].c - cells[j].c) return choose(dr + dc, dr) dp = [0] * (n+2) dp[0] = 1 for i in range(1, n+2): dp[i] = num_paths(0, i) # remove invalid paths for j in range(1, i): if cells[j].c <= cells[i].c: dp[i] = (dp[i] - dp[j]*num_paths(i, j)) % MOD print(dp[-1])
Codeforces Round 313 (Div. 1)
CF
2,015
2
256
Gerald and Giant Chess
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
null
null
[{"input": "3 4 2\n2 2\n2 3", "output": "2"}, {"input": "100 100 3\n15 16\n16 15\n99 88", "output": "545732279"}]
2,200
["combinatorics", "dp", "math", "number theory"]
55
[{"input": "3 4 2\r\n2 2\r\n2 3\r\n", "output": "2\r\n"}, {"input": "100 100 3\r\n15 16\r\n16 15\r\n99 88\r\n", "output": "545732279\r\n"}, {"input": "1000 1000 4\r\n50 50\r\n51 50\r\n50 51\r\n51 51\r\n", "output": "899660737\r\n"}, {"input": "100000 100000 4\r\n50001 50001\r\n50000 50000\r\n50000 50001\r\n50001 50000\r\n", "output": "999612315\r\n"}, {"input": "2 2 2\r\n2 1\r\n1 2\r\n", "output": "0\r\n"}, {"input": "100 10 30\r\n40 4\r\n15 3\r\n75 3\r\n88 10\r\n32 1\r\n16 5\r\n81 8\r\n45 2\r\n72 8\r\n11 6\r\n86 4\r\n50 2\r\n9 4\r\n11 1\r\n20 3\r\n47 3\r\n2 4\r\n68 3\r\n90 5\r\n85 2\r\n88 1\r\n88 5\r\n86 3\r\n70 9\r\n49 3\r\n34 4\r\n5 7\r\n77 5\r\n50 1\r\n87 5\r\n", "output": "402737011\r\n"}, {"input": "100000 100000 2\r\n1 2\r\n2 1\r\n", "output": "0\r\n"}, {"input": "100000 100000 2\r\n99999 100000\r\n100000 99999\r\n", "output": "0\r\n"}, {"input": "100000 100000 3\r\n99998 100000\r\n99999 99999\r\n100000 99998\r\n", "output": "0\r\n"}]
false
stdio
null
true
68/B
68
B
Python 3
TESTS
3
92
6,963,200
122348646
nk = list(input().split()) n, k = int(nk[0]), float(nk[1]) energy = list(map(float, input().split())) avg = sum(energy)/len(energy) sum_lf = 0 sum_rg = 0 cnt_lf = 0 cnt_rg = 0 for i in range(n): if(energy[i]<avg): cnt_lf+=1 sum_lf+=energy[i] else: cnt_rg+=1 sum_rg+=energy[i] x = (cnt_lf * sum_rg - cnt_rg * sum_lf) / (cnt_rg * (100 - k)/100 + cnt_lf) print("%.9f"%((sum_rg - x)/(cnt_rg)))
42
124
2,969,600
210677123
import sys input = lambda: sys.stdin.readline().rstrip() N,K = map(int, input().split()) A = list(map(int, input().split())) def check(m): sums,t=0,0 for a in A: if a>m: sums+=m t += (a-m)*(100-K)/100 else: sums+=a if sums+t>=m*N: return True return False l,r=0,max(A) while l+0.0000001<r: m = (l+r)/2 if check(m): l=m else: r=m print(l)
Codeforces Beta Round 62
CF
2,011
2
256
Energy exchange
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by $$x - \frac{xk}{100}$$ units. Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.
First line of the input contains two integers n and k (1 ≤ n ≤ 10000, 0 ≤ k ≤ 99) — number of accumulators and the percent of energy that is lost during transfers. Next line contains n integers a1, a2, ... , an — amounts of energy in the first, second, .., n-th accumulator respectively (0 ≤ ai ≤ 1000, 1 ≤ i ≤ n).
Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy. The absolute or relative error in the answer should not exceed 10 - 6.
null
null
[{"input": "3 50\n4 2 1", "output": "2.000000000"}, {"input": "2 90\n1 11", "output": "1.909090909"}]
1,600
["binary search"]
42
[{"input": "3 50\r\n4 2 1\r\n", "output": "2.000000000\r\n"}, {"input": "2 90\r\n1 11\r\n", "output": "1.909090909\r\n"}, {"input": "5 26\r\n42 65 23 43 64\r\n", "output": "45.415178571\r\n"}, {"input": "5 45\r\n964 515 454 623 594\r\n", "output": "594.109756098\r\n"}, {"input": "1 20\r\n784\r\n", "output": "784.000000000\r\n"}, {"input": "10 20\r\n812 896 36 596 709 641 679 778 738 302\r\n", "output": "597.255813953\r\n"}, {"input": "10 83\r\n689 759 779 927 15 231 976 943 604 917\r\n", "output": "406.839285714\r\n"}, {"input": "11 1\r\n235 280 196 670 495 379 391 280 847 875 506\r\n", "output": "467.586301370\r\n"}, {"input": "12 71\r\n472 111 924 103 975 527 807 618 400 523 607 424\r\n", "output": "413.249554367\r\n"}, {"input": "13 89\r\n19 944 341 846 764 676 222 957 953 481 708 920 950\r\n", "output": "361.924390244\r\n"}, {"input": "14 6\r\n256 465 759 589 242 824 638 985 506 128 809 105 301 827\r\n", "output": "523.427098675\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] # Read reference output with open(output_path, 'r') as f: ref_line = f.readline().strip() try: E_ref = float(ref_line) except: print(0) return # Read submission output with open(submission_path, 'r') as f: sub_line = f.readline().strip() try: E_sub = float(sub_line) except: print(0) return abs_err = abs(E_sub - E_ref) if abs_err <= 1e-6: print(1) return if E_ref == 0: print(0) return rel_err = abs_err / E_ref if rel_err <= 1e-6: print(1) return print(0) if __name__ == "__main__": main()
true
152/B
152
B
Python 3
TESTS
6
156
0
121684589
n,m=map(int, input().split()) xc,yc=map(int, input().split()) ans,n1=0,int(input()) for _ in range(n1): dx,dy=map(int,input().split()) if dx>0: sx=(n-xc)//dx elif dx<0: sx=(xc-1)//(-dx) else: sx=n if dy>0: sy=(m-yc)//dy elif dy<0: sy=(yc-1)//(-dy) else: sy=m step=min(sx,sy) xc+=step*dx yc+=step*dy ans+=step print(ans)
34
92
0
218476865
n,m=map(int,input().split()) x,y=map(int,input().split()) k=int(input()) c=0 for i in range(k): s,d=map(int,input().split()) a=n+m if s>0: a=min(a, (n-x) // s) if s<0: a=min(a, (x-1) // -s) if d>0: a=min(a, (m-y) // d) if d<0: a=min(a, (y-1) // -d) c+=a x+=s*a y+=d*a print(c)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
152/B
152
B
Python 3
TESTS
6
154
0
121683922
n,m=map(int,input().split()) xc,yc=map(int,input().split()) n1=int(input()) ans=0 for i in range(n1): dx,dy=map(int,input().split()) if dy>0: sty=(m-yc)//dy elif dy<0: sty=-(yc-1)//dy else: sty=m if dx>0: stx=(n-xc)//dx elif dx<0: stx=-(xc-1)//dx else: stx=n st=min(stx,sty) xc+=st*dx yc+=st*dy ans+=st print(ans)
34
122
0
221482780
n, m = map(int, input().split()) xc, yc = map(int, input().split()) k = int(input()) total_steps = 0 # Initialize the total number of steps to zero for _ in range(k): dx, dy = map(int, input().split()) # Calculate the maximum number of valid steps in the current direction if dx > 0: max_steps_x = (n - xc) // dx elif dx < 0: max_steps_x = (xc - 1) // abs(dx) else: max_steps_x = float('inf') if dy > 0: max_steps_y = (m - yc) // dy elif dy < 0: max_steps_y = (yc - 1) // abs(dy) else: max_steps_y = float('inf') # Calculate the maximum valid steps in the current direction max_steps = min(max_steps_x, max_steps_y) # Update Vasya's position xc += dx * max_steps yc += dy * max_steps # Update the total number of steps total_steps += max_steps print(total_steps)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
560/A
560
A
Python 3
PRETESTS
3
46
0
12175946
# zadacha A n = int(input()) A = list(map(int, input().split())) if 1 in A: print("-1") else: minn = min(A) print(minn-1)
16
31
0
177224195
n = int(input()) checker = False a = list(map(int, input().split())) for i in range(len(a)): if a[i] == 1: checker = True break if checker: print(-1) else: print(1)
Codeforces Round 313 (Div. 2)
CF
2,015
2
256
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
null
null
[{"input": "5\n1 2 3 4 5", "output": "-1"}]
1,000
["implementation", "sortings"]
16
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "-1\r\n"}, {"input": "1\r\n2\r\n", "output": "1\r\n"}, {"input": "10\r\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837\r\n", "output": "-1\r\n"}, {"input": "10\r\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264\r\n", "output": "1\r\n"}, {"input": "50\r\n110876 835020 859879 999908 712969 788264 287153 921820 330355 499311 209594 484829 296329 940051 174081 931503 1 780512 390075 97866 124255 950067 697612 244256 782385 789882 37608 82153 399889 598867 416717 377988 535636 511221 792568 683271 131077 290194 496712 330720 587436 563481 645817 942562 654093 980561 382937 48293 582608 116156\r\n", "output": "-1\r\n"}, {"input": "50\r\n474421 421097 217233 156339 27075 733996 281778 863492 184707 956857 288561 70997 393786 337382 663642 131184 637 273801 799870 295017 392338 842567 161819 297705 102013 930684 375703 838048 154915 138503 629056 256591 893619 19263 787927 684541 320265 841090 421423 490879 394582 493952 619247 633202 612928 50907 276653 407819 489945 153173\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n", "output": "-1\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1\r\n"}, {"input": "2\r\n3 2\r\n", "output": "1\r\n"}, {"input": "2\r\n2 3\r\n", "output": "1\r\n"}]
false
stdio
null
true
62/D
62
D
Python 3
TESTS
4
62
0
139384995
def find_index(path, elem, index): indexes = [] for i in range(len(path)): if path[i] == elem: if index != i and i + 1 != len(path): indexes.append(i) return indexes def build_home_path(n: int, m: int, old_path: list) -> list: """ Parameters: :n (int): number of rooms :m (int): number of corridors :old_path (list): old build path :return: new build path """ revers_path = list(reversed(old_path)) roots = [i for i in range(1, n + 1)] for i in range(len(revers_path)): if revers_path[i] in roots: indexes = find_index(revers_path, revers_path[i], i) for index in indexes: cycle = revers_path[i:index+1] new_path = list(reversed(revers_path[:i] + list(reversed(cycle)) + revers_path[index+1:])) if new_path > old_path: return new_path roots.remove(revers_path[i]) new_path = list(reversed(old_path)) if new_path > old_path: return new_path return None n, m = map(int,input().split()) p = list(map(int,input().split())) res = build_home_path(n,m,p) if res is None: print("No solution") else: print(" ".join(str(x) for x in res))
30
124
819,200
187019306
n,m = map(int,input().split()) m+=1 p = list(map(lambda x:int(x)-1,input().split())) a = [0]*m q = [[False]*n for i in range(n)] d = [[] for i in range(n)] for i in range(1,m): d[p[i]].append(p[i-1]) d[p[i-1]].append(p[i]) for i in range(n): d[i].sort() s = [(p[0],True,p[0])] l = 0 while s: v,f,vv = s[-1] if f is None: s.pop() l-=1 q[vv][v]=q[v][vv]=False continue q[vv][v]=q[v][vv]=True s[-1]=(v,None,vv) a[l]=v l+=1 if l==m: if f: continue else: break for u in reversed(d[v]): if f and u<p[l]: continue if q[u][v]: continue s.append((u,f and u==p[l],v)) if s: print(' '.join(map(lambda x:str(x+1),a))) else: print("No solution")
Codeforces Beta Round 58
CF
2,011
2
256
Wormhouse
Arnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from 1 to n. All the corridors are bidirectional. Arnie wants the new house to look just like the previous one. That is, it should have exactly n rooms and, if a corridor from room i to room j existed in the old house, it should be built in the new one. We know that during the house constructing process Arnie starts to eat an apple starting from some room and only stops when he eats his way through all the corridors and returns to the starting room. It is also known that Arnie eats without stopping. That is, until Arnie finishes constructing the house, he is busy every moment of his time gnawing a new corridor. Arnie doesn't move along the already built corridors. However, gnawing out corridors in one and the same order any time you change a house is a very difficult activity. That's why Arnie, knowing the order in which the corridors were located in the previous house, wants to gnaw corridors in another order. It is represented as a list of rooms in the order in which they should be visited. The new list should be lexicographically smallest, but it also should be strictly lexicographically greater than the previous one. Help the worm.
The first line contains two integers n and m (3 ≤ n ≤ 100, 3 ≤ m ≤ 2000). It is the number of rooms and corridors in Arnie's house correspondingly. The next line contains m + 1 positive integers that do not exceed n. They are the description of Arnie's old path represented as a list of rooms he visited during the gnawing. It is guaranteed that the last number in the list coincides with the first one. The first room described in the list is the main entrance, that's why Arnie should begin gnawing from it. You may assume that there is no room which is connected to itself and there is at most one corridor between any pair of rooms. However, it is possible to find some isolated rooms which are disconnected from others.
Print m + 1 positive integers that do not exceed n. Those numbers are the description of the new path, according to which Arnie should gnaw out his new house. If it is impossible to find new path you should print out No solution. The first number in your answer should be equal to the last one. Also it should be equal to the main entrance.
null
null
[{"input": "3 3\n1 2 3 1", "output": "1 3 2 1"}, {"input": "3 3\n1 3 2 1", "output": "No solution"}]
2,300
["dfs and similar", "graphs"]
30
[{"input": "3 3\r\n1 2 3 1\r\n", "output": "1 3 2 1 "}, {"input": "3 3\r\n1 3 2 1\r\n", "output": "No solution"}, {"input": "4 4\r\n1 2 4 3 1\r\n", "output": "1 3 4 2 1 "}, {"input": "6 7\r\n3 2 4 1 6 5 1 3\r\n", "output": "No solution"}, {"input": "8 12\r\n4 6 5 1 4 3 1 8 3 7 8 5 4\r\n", "output": "4 6 5 1 4 3 1 8 7 3 8 5 4 "}, {"input": "5 6\r\n3 4 1 2 5 1 3\r\n", "output": "3 4 1 5 2 1 3 "}, {"input": "7 9\r\n3 2 7 3 5 1 2 6 1 3\r\n", "output": "3 2 7 3 5 1 6 2 1 3 "}, {"input": "6 7\r\n1 5 6 1 4 3 2 1\r\n", "output": "1 6 5 1 2 3 4 1 "}, {"input": "4 3\r\n1 2 3 1\r\n", "output": "1 3 2 1 "}, {"input": "10 40\r\n10 3 8 4 10 2 8 1 2 6 3 5 7 6 10 8 9 7 8 5 4 9 1 3 7 2 5 10 9 2 4 3 9 6 5 1 4 6 1 7 10\r\n", "output": "10 3 8 4 10 2 8 1 2 6 3 5 7 6 10 8 9 7 8 5 4 9 1 3 7 2 5 10 9 2 4 3 9 6 5 1 6 4 1 7 10 "}]
false
stdio
null
true
32/A
32
A
Python 3
TESTS
7
342
0
206847583
a, b = map(int, input().split()) c = list(map(int, input().split())) ans = 0 for i in c: for h in c: if i - h <= b and i - h > 0: ans += 2 for i in c: if c.count(i) >= 2: ans += 1 print(ans)
32
92
0
171048055
n,d = list(map(int, input().split())) lst = list(map(int, input().split())) cnt=0 i=0 j=1 lst.sort() while j<n: if lst[j]-lst[i]<=d: cnt+= (j-i) j+=1 else: i+=1 print(cnt*2)
Codeforces Beta Round 32 (Div. 2, Codeforces format)
CF
2,010
2
256
Reconnaissance
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways (1, 2) and (2, 1) should be regarded as different.
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
null
null
[{"input": "5 10\n10 20 50 60 65", "output": "6"}, {"input": "5 1\n55 30 29 31 55", "output": "6"}]
800
["brute force"]
32
[{"input": "5 10\r\n10 20 50 60 65\r\n", "output": "6\r\n"}, {"input": "5 1\r\n55 30 29 31 55\r\n", "output": "6\r\n"}, {"input": "6 10\r\n4 6 4 1 9 3\r\n", "output": "30\r\n"}, {"input": "7 100\r\n19 1694 261 162 1 234 513\r\n", "output": "8\r\n"}, {"input": "8 42\r\n37 53 74 187 568 22 5 65\r\n", "output": "20\r\n"}, {"input": "10 4\r\n11 6 76 49 28 20 57 152 5 32\r\n", "output": "4\r\n"}, {"input": "100 100\r\n51 93 101 960 2 477 213 129 663 925 254 78 1486 274 160 481 132 156 412 372 5 57 152 298 1771 7 359 468 254 406 202 929 221 366 552 97 555 29 822 118 539 140 992 854 7 163 134 103 940 30 409 1003 398 43 555 79 107 40 23 103 643 171 310 382 770 337 18 189 570 177 29 54 855 171 205 291 299 935 620 180 114 358 88 292 118 400 218 537 369 60 683 192 13 537 59 824 264 191 3 300\r\n", "output": "2404\r\n"}]
false
stdio
null
true
32/A
32
A
Python 3
TESTS
7
1,028
0
137970340
n,d = map(eval,input().split()) list_1 = list(map(eval,input().split())) N = 0 m = 0 for i in range(len(list_1)): if list_1.count(list_1[i]) == 2: N += 1 elif list_1.count(list_1[i]) > 2: m = list_1.count(list_1[i]) for j in range(len(list_1)): if list_1[i] != list_1[j] and abs(list_1[i]-list_1[j])<=d: N += 1 print(N+m*(m-1))
32
92
0
173010593
n, d = (int(i) for i in input().split()) a = sorted(int(i) for i in input().split()) res = 0 for i in range(n): lo, hi = i + 1, n while lo < hi: mi = lo + (hi - lo) // 2 if a[mi] - a[i] > d: hi = mi else: lo = mi + 1 res += 2 * (lo - i - 1) print(res)
Codeforces Beta Round 32 (Div. 2, Codeforces format)
CF
2,010
2
256
Reconnaissance
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways (1, 2) and (2, 1) should be regarded as different.
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
null
null
[{"input": "5 10\n10 20 50 60 65", "output": "6"}, {"input": "5 1\n55 30 29 31 55", "output": "6"}]
800
["brute force"]
32
[{"input": "5 10\r\n10 20 50 60 65\r\n", "output": "6\r\n"}, {"input": "5 1\r\n55 30 29 31 55\r\n", "output": "6\r\n"}, {"input": "6 10\r\n4 6 4 1 9 3\r\n", "output": "30\r\n"}, {"input": "7 100\r\n19 1694 261 162 1 234 513\r\n", "output": "8\r\n"}, {"input": "8 42\r\n37 53 74 187 568 22 5 65\r\n", "output": "20\r\n"}, {"input": "10 4\r\n11 6 76 49 28 20 57 152 5 32\r\n", "output": "4\r\n"}, {"input": "100 100\r\n51 93 101 960 2 477 213 129 663 925 254 78 1486 274 160 481 132 156 412 372 5 57 152 298 1771 7 359 468 254 406 202 929 221 366 552 97 555 29 822 118 539 140 992 854 7 163 134 103 940 30 409 1003 398 43 555 79 107 40 23 103 643 171 310 382 770 337 18 189 570 177 29 54 855 171 205 291 299 935 620 180 114 358 88 292 118 400 218 537 369 60 683 192 13 537 59 824 264 191 3 300\r\n", "output": "2404\r\n"}]
false
stdio
null
true
32/A
32
A
Python 3
TESTS
7
1,028
0
137968080
n,d = map(eval,input().split()) list_1 = list(map(eval,input().split())) N = 0 for i in range(len(list_1)): if list_1.count(list_1[i]) > 1: N += 1 for j in range(len(list_1)): if list_1[i] != list_1[j] and abs(list_1[i]-list_1[j])<=d: N += 1 print(N)
32
122
0
142411592
str1 = str(input()) n = int(str1.split(' ')[0]) d = int(str1.split(' ')[1]) str2 = str(input()) lis = [int(i) for i in str2.split(' ')] lis.sort() pair = 0 left = 0 right = 1 while right < n: if lis[right] - lis[left] <= d: pair += 2 * (right - left) else: while lis[right] - lis[left] > d and right != left: left += 1 pair += 2 * (right - left) right += 1 print(pair)
Codeforces Beta Round 32 (Div. 2, Codeforces format)
CF
2,010
2
256
Reconnaissance
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways (1, 2) and (2, 1) should be regarded as different.
The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.
null
null
[{"input": "5 10\n10 20 50 60 65", "output": "6"}, {"input": "5 1\n55 30 29 31 55", "output": "6"}]
800
["brute force"]
32
[{"input": "5 10\r\n10 20 50 60 65\r\n", "output": "6\r\n"}, {"input": "5 1\r\n55 30 29 31 55\r\n", "output": "6\r\n"}, {"input": "6 10\r\n4 6 4 1 9 3\r\n", "output": "30\r\n"}, {"input": "7 100\r\n19 1694 261 162 1 234 513\r\n", "output": "8\r\n"}, {"input": "8 42\r\n37 53 74 187 568 22 5 65\r\n", "output": "20\r\n"}, {"input": "10 4\r\n11 6 76 49 28 20 57 152 5 32\r\n", "output": "4\r\n"}, {"input": "100 100\r\n51 93 101 960 2 477 213 129 663 925 254 78 1486 274 160 481 132 156 412 372 5 57 152 298 1771 7 359 468 254 406 202 929 221 366 552 97 555 29 822 118 539 140 992 854 7 163 134 103 940 30 409 1003 398 43 555 79 107 40 23 103 643 171 310 382 770 337 18 189 570 177 29 54 855 171 205 291 299 935 620 180 114 358 88 292 118 400 218 537 369 60 683 192 13 537 59 824 264 191 3 300\r\n", "output": "2404\r\n"}]
false
stdio
null
true
152/B
152
B
PyPy 3
TESTS
6
622
28,569,600
115397102
n, m = map(int, input().split()) xc, yc = map(int, input().split()) k = int(input()) steps = 0 for i in range(k): steps1, step2, ans = 0, 0, 0 dx, dy = map(int, input().split()) lo, hi = 0, n while lo <= hi: mid = lo + (hi - lo) // 2 if mid*dx + xc >= 1 and mid*dx + xc <= n: lo = mid + 1 steps1 = mid else: hi = mid - 1 l, r = 0, m while l <= r: mi = l + (r - l) // 2 if mi*dy + yc >= 1 and mi*dy + yc <= m: l = mi + 1 step2 = mi #print(step2) else: r = mi - 1 ans = min(step2, steps1) steps += min(steps1, step2) xc += ans * dx yc += ans * dy print(steps)
34
124
0
209279034
n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) ans = 0 for _ in range(k): dx, dy = map(int, input().split()) if 0 < dx+x <= n and 0 < dy+y <= m: if dx >= 0: a = abs((n-x)//dx) if dx != 0 else 0 else: a = abs(x//dx)-1 b = abs((m-y)//dy) if dy > 0 else abs(y//dy)-1 if dy < 0 else 0 if a >= b and a and b: a = b elif b >= a and b and a: b = a if not a and b: ans += abs(b) elif not b and a: ans += abs(a) else: ans += min(abs(a), abs(b)) x += a*dx y += b*dy print(ans)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
152/B
152
B
Python 3
TESTS
6
248
614,400
96497138
n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) vectors = [] for _ in range(k): vectors.append(tuple(map(int, input().split()))) ans = 0 for i in range(k): step_x = 0 step_y = 0 steps = 0 if vectors[i][0] < 0: step_x = (x - 1) // abs(vectors[i][0]) elif vectors[i][0] > 0: step_x = (n - x) // vectors[i][0] else: step_x = n if vectors[i][1] < 0: step_y = (y - 1) // abs(vectors[i][1]) elif vectors[i][1] > 0: step_y = (m - y) // vectors[i][1] else: step_y = m steps = min(step_x, step_y) ans += steps x += steps * vectors[i][0] y += steps * vectors[i][1] print(ans)
34
124
0
218465194
n , m = map(int,input().split()) x,y = map(int,input().split()) k = int(input()) s = 0 for i in range(k): d,p = map(int,input().split()) if d>0: a=(n-x)//d elif d<0: a=(x-1)//abs(d) if p>0: b=(m-y)//p if d==0: a=b+1 elif p<0: b=(y-1)//abs(p) if d==0: a = b+1 elif p == 0: b=a+1 v = min(a,b) x = x+v*d y = y+v*p s = s+v print(s)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
1009/A
1009
A
Python 3
TESTS
3
124
0
137516387
n, m = map(int, input().split()) c = list(map(int, input().split())) a = list(map(int, input().split())) count = 0 t = 0 for i in range(n): # t = count for j in range(m): if a[j] > c[i]: a[j] = -1 c[i] = 10000 count += 1 break # if t == count: # break print(count)
19
46
0
136827538
a,b=map(int,input().split(" ")) c=input().split(" ") d=input().split(" ") n=0 c=[int(i) for i in c] d=[int(j) for j in d] for i in range(a): if n!=b: if d[n]>=c[i]: n=n+1 print(n)
Educational Codeforces Round 47 (Rated for Div. 2)
ICPC
2,018
1
256
Game Shopping
Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$. Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$. Games in the shop are ordered from left to right, Maxim tries to buy every game in that order. When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop. Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game. For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$. Your task is to get the number of games Maxim will buy.
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_j \le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.
Print a single integer — the number of games Maxim will buy.
null
The first example is described in the problem statement. In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop. In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.
[{"input": "5 4\n2 4 5 2 4\n5 3 4 6", "output": "3"}, {"input": "5 2\n20 40 50 20 40\n19 20", "output": "0"}, {"input": "6 4\n4 8 15 16 23 42\n1000 1000 1000 1000", "output": "4"}]
800
["implementation"]
19
[{"input": "5 4\r\n2 4 5 2 4\r\n5 3 4 6\r\n", "output": "3\r\n"}, {"input": "5 2\r\n20 40 50 20 40\r\n19 20\r\n", "output": "0\r\n"}, {"input": "6 4\r\n4 8 15 16 23 42\r\n1000 1000 1000 1000\r\n", "output": "4\r\n"}, {"input": "5 1\r\n1 1 1 1 1\r\n5\r\n", "output": "1\r\n"}, {"input": "5 1\r\n10 1 1 1 1\r\n1000\r\n", "output": "1\r\n"}, {"input": "5 1\r\n100 100 100 100 100\r\n100\r\n", "output": "1\r\n"}, {"input": "2 1\r\n2 1\r\n1\r\n", "output": "1\r\n"}, {"input": "2 3\r\n3 1\r\n2 4 2\r\n", "output": "1\r\n"}, {"input": "1 5\r\n4\r\n1 4 3 3 2\r\n", "output": "0\r\n"}, {"input": "5 3\r\n4 2 3 1 1\r\n2 1 3\r\n", "output": "3\r\n"}, {"input": "3 5\r\n5 2 5\r\n1 4 1 4 2\r\n", "output": "0\r\n"}, {"input": "7 3\r\n9 7 10 2 1 1 1\r\n8 9 6\r\n", "output": "3\r\n"}, {"input": "5 3\r\n2 5 3 3 2\r\n2 5 3\r\n", "output": "3\r\n"}]
false
stdio
null
true
1009/G
1009
G
Python 3
TESTS
0
108
0
40756225
w = input() d = {} for c in w: d[c] = w.count(c) inv = dict() for i in range(int(input())): idx,name = input().split() idx = int(idx)-1 name = [c for c in name if c in d] if name: inv[idx] = name def solve(counts, investors, value=None): if value == None: value = dict() if not investors: return True, value i, *invs = sorted(investors.items(),key=lambda kv: kv[0]) investor, possible = i choices = [c for c in counts if counts[c] > 0 and c in possible] for choice in sorted(choices): counts[choice] -= 1 value[investor] = choice good, ret = solve(counts, dict(invs), value) if good: return good, ret value[investor] = None counts[choice] += 1 return False, None good, value = solve(d, inv) if not good: print(end="Impossible") else: for i in range(len(w)): o = "" if i in value: o = value[i] else: o = min(c for c in d if d[c] > 0) d[c] -= 1 print(end=o) print()
57
233
10,137,600
167672037
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = list(input().rstrip()) pow2 = [1] for _ in range(6): pow2.append(2 * pow2[-1]) p = pow2[6] cnt = [0] * p for i in s: cnt[pow2[i - 97]] += 1 sp = set(pow2) u = [[pow2[i]] for i in range(6)] for i in range(1, p): if i in sp: continue for j in range(6): pj = pow2[j] if i & pj: cnt[i] += cnt[pj] u[j].append(i) n = len(s) y = [p - 1] * n m = int(input()) for _ in range(m): pos, s = input().rstrip().split() x = 0 for i in s: x ^= pow2[i - 97] y[int(pos) - 1] = x c = [0] * p for i in y: c[i] += 1 v = [[i] for i in range(p)] for i in range(p - 1, -1, -1): ci = c[i] for j in range(i + 1, p): if i & j == i: c[j] += ci v[i].append(j) ans = [] for i in y: for j in v[i]: c[j] -= 1 ok = 0 for j in range(6): pj = pow2[j] if not i & pj or not cnt[pj]: continue f = 1 for k in range(1, p): if c[k] > cnt[k] - min(1, k & pj): f = 0 break if f: ok = 1 ans.append(chr(97 + j)) for k in u[j]: cnt[k] -= 1 break if not ok: ans = ["Impossible"] break sys.stdout.write("".join(ans))
Educational Codeforces Round 47 (Rated for Div. 2)
ICPC
2,018
2
256
Allowed Letters
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup! Actually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent. In addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there. Finally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?) More formally, you are given a string consisting of lowercase Latin letters from "a" to "f". You can swap letters at any positions arbitrary number of times (zero swaps is also possible). What is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters? If Polycarp can't produce any valid name then print "Impossible".
The first line is the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) — the name Polycarp has came up with. The string consists only of lowercase Latin letters from "a" to "f". The second line contains a single integer $$$m$$$ ($$$0 \le m \le |s|$$$) — the number of investors. The $$$i$$$-th of the next $$$m$$$ lines contain an integer number $$$pos_i$$$ and a non-empty string of allowed characters for $$$pos_i$$$ ($$$1 \le pos_i \le |s|$$$). Each string contains pairwise distinct letters from "a" to "f". $$$pos_1, pos_2, \dots, pos_m$$$ are pairwise distinct. If any position of the string doesn't appear in the investors demands then any letter can go in this position.
If Polycarp can't produce any valid name then print "Impossible". Otherwise print the smallest lexicographically name Polycarp can obtain by swapping letters in string $$$s$$$ such that the letter at every position is among the allowed ones.
null
null
[{"input": "bedefead\n5\n2 e\n1 dc\n5 b\n7 ef\n6 ef", "output": "deadbeef"}, {"input": "abacaba\n0", "output": "aaaabbc"}, {"input": "fc\n2\n1 cfab\n2 f", "output": "cf"}]
2,400
["bitmasks", "flows", "graph matchings", "graphs", "greedy"]
57
[{"input": "bedefead\r\n5\r\n2 e\r\n1 dc\r\n5 b\r\n7 ef\r\n6 ef\r\n", "output": "deadbeef\r\n"}, {"input": "abacaba\r\n0\r\n", "output": "aaaabbc\r\n"}, {"input": "fc\r\n2\r\n1 cfab\r\n2 f\r\n", "output": "cf\r\n"}, {"input": "bbcbbc\r\n6\r\n1 c\r\n2 c\r\n3 b\r\n4 ab\r\n5 ab\r\n6 ab\r\n", "output": "ccbbbb\r\n"}, {"input": "abcdefffffffffffffff\r\n5\r\n20 abcde\r\n19 abcde\r\n18 abcde\r\n17 abcde\r\n16 abcde\r\n", "output": "fffffffffffffffabcde\r\n"}, {"input": "abcdefffffffffffffff\r\n20\r\n1 acf\r\n2 cdef\r\n3 ef\r\n4 def\r\n5 adef\r\n6 acdef\r\n7 bdef\r\n8 abdf\r\n9 bcdf\r\n10 abf\r\n11 abf\r\n12 bcdf\r\n13 df\r\n14 df\r\n15 abcdf\r\n16 abcde\r\n17 abcde\r\n18 abcde\r\n19 abcde\r\n20 abcde\r\n", "output": "fffffffffffffffabcde\r\n"}, {"input": "aaeff\r\n5\r\n2 afbdce\r\n5 c\r\n1 dbc\r\n4 afcbde\r\n3 ef\r\n", "output": "Impossible\r\n"}, {"input": "cdff\r\n1\r\n2 ae\r\n", "output": "Impossible\r\n"}, {"input": "dfb\r\n2\r\n1 c\r\n3 cae\r\n", "output": "Impossible\r\n"}, {"input": "cefe\r\n2\r\n4 ca\r\n1 da\r\n", "output": "Impossible\r\n"}, {"input": "cdccc\r\n5\r\n2 fae\r\n1 dabc\r\n4 dcfabe\r\n3 abc\r\n5 bdcafe\r\n", "output": "Impossible\r\n"}, {"input": "bdc\r\n3\r\n1 f\r\n3 fdacb\r\n2 eb\r\n", "output": "Impossible\r\n"}, {"input": "effa\r\n3\r\n3 ca\r\n2 bd\r\n4 abfdce\r\n", "output": "Impossible\r\n"}, {"input": "bfd\r\n2\r\n2 aecf\r\n3 dfb\r\n", "output": "bfd\r\n"}, {"input": "bfb\r\n3\r\n1 f\r\n3 acdef\r\n2 cdefab\r\n", "output": "Impossible\r\n"}, {"input": "fce\r\n3\r\n3 abdecf\r\n1 efdcba\r\n2 ac\r\n", "output": "ecf\r\n"}, {"input": "ded\r\n1\r\n2 aedc\r\n", "output": "dde\r\n"}, {"input": "a\r\n1\r\n1 b\r\n", "output": "Impossible\r\n"}]
false
stdio
null
true
1009/A
1009
A
Python 3
TESTS
3
108
0
40856410
answer=0 n,m=map(int, input("").split(" ")) games=input("").split(" ") wallet=input("").split(" ") for i in range(m): if int(games[i])<=int(wallet[i]): answer+=1 else: del games[i] games.append(10000) i-=1 print(answer)
19
46
0
136833530
n,m=input().split() n=int(n) m=int(m) lis1=input().split(' ') lis1=[int(i) for i in lis1] lis2=input().split(' ') lis2=[int(i) for i in lis2] cnt=0 for i in range(max(n,m)): if lis2[0] >= lis1[0]: cnt += 1 lis1.pop(0) lis2.pop(0) if len(lis1)==0 or len(lis2)==0: break else: lis1.pop(0) if len(lis1)==0: break print(cnt)
Educational Codeforces Round 47 (Rated for Div. 2)
ICPC
2,018
1
256
Game Shopping
Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$. Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$. Games in the shop are ordered from left to right, Maxim tries to buy every game in that order. When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop. Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game. For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$. Your task is to get the number of games Maxim will buy.
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_j \le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.
Print a single integer — the number of games Maxim will buy.
null
The first example is described in the problem statement. In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop. In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.
[{"input": "5 4\n2 4 5 2 4\n5 3 4 6", "output": "3"}, {"input": "5 2\n20 40 50 20 40\n19 20", "output": "0"}, {"input": "6 4\n4 8 15 16 23 42\n1000 1000 1000 1000", "output": "4"}]
800
["implementation"]
19
[{"input": "5 4\r\n2 4 5 2 4\r\n5 3 4 6\r\n", "output": "3\r\n"}, {"input": "5 2\r\n20 40 50 20 40\r\n19 20\r\n", "output": "0\r\n"}, {"input": "6 4\r\n4 8 15 16 23 42\r\n1000 1000 1000 1000\r\n", "output": "4\r\n"}, {"input": "5 1\r\n1 1 1 1 1\r\n5\r\n", "output": "1\r\n"}, {"input": "5 1\r\n10 1 1 1 1\r\n1000\r\n", "output": "1\r\n"}, {"input": "5 1\r\n100 100 100 100 100\r\n100\r\n", "output": "1\r\n"}, {"input": "2 1\r\n2 1\r\n1\r\n", "output": "1\r\n"}, {"input": "2 3\r\n3 1\r\n2 4 2\r\n", "output": "1\r\n"}, {"input": "1 5\r\n4\r\n1 4 3 3 2\r\n", "output": "0\r\n"}, {"input": "5 3\r\n4 2 3 1 1\r\n2 1 3\r\n", "output": "3\r\n"}, {"input": "3 5\r\n5 2 5\r\n1 4 1 4 2\r\n", "output": "0\r\n"}, {"input": "7 3\r\n9 7 10 2 1 1 1\r\n8 9 6\r\n", "output": "3\r\n"}, {"input": "5 3\r\n2 5 3 3 2\r\n2 5 3\r\n", "output": "3\r\n"}]
false
stdio
null
true
724/D
724
D
Python 3
PRETESTS
4
62
4,608,000
21294474
def minn(a): m = a[0] p = 0 for i in range(1, len(a)): if a[i] <= m: m = a[i] p = i return m, p k = int(input()) s = input() cnt = list(s[:k]) min_elem, place = minn(cnt) ans = [min_elem] for i in range(k, len(s)): cnt.pop(0) cnt.append(s[i]) new_min_elem, new_place = minn(cnt) if new_place != place - 1: ans.append(new_min_elem) place = new_place ans.sort() print(''.join(map(str, ans)))
71
405
6,860,800
21307524
from collections import Counter from string import ascii_lowercase as asc m, s = int(input()), input() g = Counter(s) def solve(c): p = 0 for q in ''.join(x if x >= c else ' ' for x in s).split(): i, j = 0, -1 while j + m < len(q): j = q.rfind(c, j + 1, j + m + 1) if j == -1: return None i += 1 p += i return p for c in asc: f = solve(c) if f is not None: g[c] = f print(''.join(x*g[x] for x in asc if x <= c)) break
Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined)
CF
2,016
2
256
Dense Subsequence
You are given a string s, consisting of lowercase English letters, and the integer m. One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order. Formally, we choose a subsequence of indices 1 ≤ i1 < i2 < ... < it ≤ |s|. The selected sequence must meet the following condition: for every j such that 1 ≤ j ≤ |s| - m + 1, there must be at least one selected index that belongs to the segment [j,  j + m - 1], i.e. there should exist a k from 1 to t, such that j ≤ ik ≤ j + m - 1. Then we take any permutation p of the selected indices and form a new string sip1sip2... sipt. Find the lexicographically smallest string, that can be obtained using this procedure.
The first line of the input contains a single integer m (1 ≤ m ≤ 100 000). The second line contains the string s consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100 000. It is also guaranteed that the number m doesn't exceed the length of the string s.
Print the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.
null
In the first sample, one can choose the subsequence {3} and form a string "a". In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab".
[{"input": "3\ncbabc", "output": "a"}, {"input": "2\nabcab", "output": "aab"}, {"input": "3\nbcabcbaccba", "output": "aaabb"}]
1,900
["data structures", "greedy", "strings"]
71
[{"input": "3\r\ncbabc\r\n", "output": "a\r\n"}, {"input": "2\r\nabcab\r\n", "output": "aab\r\n"}, {"input": "3\r\nbcabcbaccba\r\n", "output": "aaabb\r\n"}, {"input": "5\r\nimmaydobun\r\n", "output": "ab\r\n"}, {"input": "5\r\nwjjdqawypvtgrncmqvcsergermprauyevcegjtcrrblkwiugrcjfpjyxngyryxntauxlouvwgjzpsuxyxvhavgezwtuzknetdibv\r\n", "output": "aaaabbcccccddeeeeeefggggggghiijjjjjjkkllmmnnnnoppppqqrrrrrrrrsstttttu\r\n"}, {"input": "10\r\nefispvmzuutsrpxzfrykhabznxiyquwvhwhrksrgzodtuepfvamilfdynapzhzyhncorhzuewrrkcduvuhwsrprjrmgctnvrdtpj\r\n", "output": "aaabcccddddeeeffffgghhhhhhhiiijjkkklm\r\n"}, {"input": "20\r\nhlicqhxayiodyephxlfoetfketnaabpfegqcrjzlshkxfzjssvpvzhzylgowwovgxznzowvpklbwbzhwtkkaomjkenhpedmbmjic\r\n", "output": "aaaabbbbcccddeeeeeeffffg\r\n"}, {"input": "50\r\ntyhjolxuexoffdkdwimsjujorgeksyiyvvqecvhpjsuayqnibijtipuqhkulxpysotlmtrsgygpkdhkrtntwqzrpfckiscaphyhv\r\n", "output": "aab\r\n"}, {"input": "1\r\nbaaa\r\n", "output": "aaab\r\n"}, {"input": "5\r\nbbbbba\r\n", "output": "ab\r\n"}, {"input": "10\r\nbbabcbbaabcbcbcbaabbccaacccbbbcaaacabbbbaaaccbcccacbbccaccbbaacaccbabcaaaacaccacbaaccaaccbaacabbbaac\r\n", "output": "aaaaaaaaaaa\r\n"}]
false
stdio
null
true
29/A
29
A
Python 3
TESTS
5
216
0
60777852
def calrange(x, d): if d>=0: return [x, x+d] else: return [x+d, x] n=int(input()) x=[] d=[] r=[] b=[] c=0 for i in range(n): tx, td=[int(x) for x in input().split()] x.append(tx), d.append(td) r.append(calrange(tx, td)) for i in range(n): for j in range(n): if i!=j and c==0: if r[i][0]<=x[j]<=r[i][1]: b.insert(j, i) if j in b: if b[j]==b.index(j): print("YES") c=1 if c==0: print("NO")
30
92
0
142066183
s = [] for n in range(int(input())): x, d = map(int, input().split()) s.append(([x, x+d])) find = True for i in range(len(s)): if find is False: break x, d = s[i] for j in range(len(s)): if i == j: continue z, y = s[j] if x == y and z == d: print("YES") find = False break if find: print("NO")
Codeforces Beta Round 29 (Div. 2, Codeforces format)
CF
2,010
2
256
Spit Problem
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.
The first line contains integer n (1 ≤ n ≤ 100) — the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 ≤ xi ≤ 104, 1 ≤ |di| ≤ 2·104) — records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.
If there are two camels, which spitted at each other, output YES. Otherwise, output NO.
null
null
[{"input": "2\n0 1\n1 -1", "output": "YES"}, {"input": "3\n0 1\n1 1\n2 -2", "output": "NO"}, {"input": "5\n2 -10\n3 10\n0 5\n5 -5\n10 1", "output": "YES"}]
1,000
["brute force"]
30
[{"input": "2\r\n0 1\r\n1 -1\r\n", "output": "YES\r\n"}, {"input": "3\r\n0 1\r\n1 1\r\n2 -2\r\n", "output": "NO\r\n"}, {"input": "5\r\n2 -10\r\n3 10\r\n0 5\r\n5 -5\r\n10 1\r\n", "output": "YES\r\n"}, {"input": "10\r\n-9897 -1144\r\n-4230 -6350\r\n2116 -3551\r\n-3635 4993\r\n3907 -9071\r\n-2362 4120\r\n-6542 984\r\n5807 3745\r\n7594 7675\r\n-5412 -6872\r\n", "output": "NO\r\n"}, {"input": "11\r\n-1536 3809\r\n-2406 -8438\r\n-1866 395\r\n5636 -490\r\n-6867 -7030\r\n7525 3575\r\n-6796 2908\r\n3884 4629\r\n-2862 -6122\r\n-8984 6122\r\n7137 -326\r\n", "output": "YES\r\n"}, {"input": "12\r\n-9765 1132\r\n-1382 -215\r\n-9405 7284\r\n-2040 3947\r\n-9360 3150\r\n6425 9386\r\n806 -2278\r\n-2121 -7284\r\n5663 -1608\r\n-8377 9297\r\n6245 708\r\n8470 6024\r\n", "output": "YES\r\n"}, {"input": "15\r\n8122 -9991\r\n-4068 -3386\r\n8971 3731\r\n3458 5161\r\n-8700 7562\r\n2691 8735\r\n-1510 -3892\r\n5183 -3753\r\n-7018 6637\r\n-7454 3386\r\n-818 -6377\r\n6771 -8647\r\n-7357 -1246\r\n-6186 1922\r\n9889 -3627\r\n", "output": "YES\r\n"}, {"input": "20\r\n-5264 6424\r\n-3664 -7459\r\n-2780 -9859\r\n-3317 6842\r\n5681 -8092\r\n1555 1904\r\n-6684 1414\r\n6593 -1253\r\n-5708 -1202\r\n335 1733\r\n-926 7579\r\n3459 -1904\r\n-4486 4006\r\n6201 3616\r\n2847 -5255\r\n8438 7057\r\n8171 6042\r\n-9102 3545\r\n7731 -233\r\n6264 6563\r\n", "output": "YES\r\n"}]
false
stdio
null
true
152/B
152
B
Python 3
TESTS
6
92
0
189868249
def main(): n, m = list(map(int, input().split())) x_0, y_0 = list(map(int, input().split())) k = int(input()) steps = 0 for i in range(k): dx, dy = list(map(int, input().split())) if dx > 0: valid_x = (n - x_0) // dx elif dx == 0: valid_x = n else: valid_x = (1 - x_0) // dx if dy > 0: valid_y = (m - y_0) // dy elif dy == 0: valid_y = m else: valid_y = (1 - y_0) // dy if valid_y == m and valid_x == n: valid_x, valid_y = 0, 0 x_0, y_0 = x_0 + min(valid_y, valid_x) * dx, y_0 + min(valid_y, valid_x) * dy steps += min(valid_y, valid_x) print(steps) if __name__ == "__main__": main()
34
154
0
136563686
import sys mn = sys.stdin.readline()[:-1].split(' ') n, m = int(mn[0]), int(mn[1]) xy = sys.stdin.readline()[:-1].split(' ') x, y = int(xy[0]), int(xy[1]) count = 0 k = int(sys.stdin.readline()[:-1]) for i in range(k): dxy = sys.stdin.readline()[:-1].split(' ') dx, dy = int(dxy[0]), int(dxy[1]) if dx < 0: xStep = int((x-1) / abs(dx)) elif dx == 0: xStep = -1 else: xStep = int((n-x) / dx) if dy < 0: yStep = int((y-1) / abs(dy)) elif dy == 0: yStep = -1 else: yStep = int((m-y) / dy) if xStep <= 0 and yStep <= 0: step = 0 elif xStep == -1 and yStep > 0: step = yStep elif yStep == -1 and xStep > 0: step = xStep else: step = min(xStep, yStep) x += dx * step y += dy * step count += step print(count)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
560/A
560
A
Python 3
TESTS
3
46
0
12237948
n = input() arr = input() flag = False arr.split(' ') for a in arr: if a == "1": flag = True break if flag: print("-1") else: print("1")
16
31
0
180082104
n = int(input()) a = list(map(int,input().split())) bln = True for i in range(len(a)): if a[i] == 1: print(-1) bln = False if bln: print(1)
Codeforces Round 313 (Div. 2)
CF
2,015
2
256
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
null
null
[{"input": "5\n1 2 3 4 5", "output": "-1"}]
1,000
["implementation", "sortings"]
16
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "-1\r\n"}, {"input": "1\r\n2\r\n", "output": "1\r\n"}, {"input": "10\r\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837\r\n", "output": "-1\r\n"}, {"input": "10\r\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264\r\n", "output": "1\r\n"}, {"input": "50\r\n110876 835020 859879 999908 712969 788264 287153 921820 330355 499311 209594 484829 296329 940051 174081 931503 1 780512 390075 97866 124255 950067 697612 244256 782385 789882 37608 82153 399889 598867 416717 377988 535636 511221 792568 683271 131077 290194 496712 330720 587436 563481 645817 942562 654093 980561 382937 48293 582608 116156\r\n", "output": "-1\r\n"}, {"input": "50\r\n474421 421097 217233 156339 27075 733996 281778 863492 184707 956857 288561 70997 393786 337382 663642 131184 637 273801 799870 295017 392338 842567 161819 297705 102013 930684 375703 838048 154915 138503 629056 256591 893619 19263 787927 684541 320265 841090 421423 490879 394582 493952 619247 633202 612928 50907 276653 407819 489945 153173\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n", "output": "-1\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1\r\n"}, {"input": "2\r\n3 2\r\n", "output": "1\r\n"}, {"input": "2\r\n2 3\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
124
6,758,400
129967833
a = int(input()) count = 0 c = 'ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE' c.split() for i in range(a): b = input() if b.isdigit(): if int(b) < 18: count += 1 elif b in c: count += 1 print(count)
28
62
0
150127566
n = int(input()) alc = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] m = 0 for i in range(n): x = input() if '1' in x or '2' in x or '3' in x or '4' in x or '5' in x or '6' in x or '7' in x or '8' in x or '9' in x or '0' in x: if int(x) < 18: m += 1 else: if x in alc: m += 1 print(m)
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
560/A
560
A
Python 3
TESTS
3
31
0
192487142
# LUOGU_RID: 101605300 n, *a = map(int, open(0).read().split()) print(-1 if min(a) == 1 else min(a) - 1)
16
31
0
211103427
n = int(input()) banknotes = list(map(int, input().split())) flag = False for bn in banknotes: if bn == 1: flag = True print (-1 if flag else 1)
Codeforces Round 313 (Div. 2)
CF
2,015
2
256
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
null
null
[{"input": "5\n1 2 3 4 5", "output": "-1"}]
1,000
["implementation", "sortings"]
16
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "-1\r\n"}, {"input": "1\r\n2\r\n", "output": "1\r\n"}, {"input": "10\r\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837\r\n", "output": "-1\r\n"}, {"input": "10\r\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264\r\n", "output": "1\r\n"}, {"input": "50\r\n110876 835020 859879 999908 712969 788264 287153 921820 330355 499311 209594 484829 296329 940051 174081 931503 1 780512 390075 97866 124255 950067 697612 244256 782385 789882 37608 82153 399889 598867 416717 377988 535636 511221 792568 683271 131077 290194 496712 330720 587436 563481 645817 942562 654093 980561 382937 48293 582608 116156\r\n", "output": "-1\r\n"}, {"input": "50\r\n474421 421097 217233 156339 27075 733996 281778 863492 184707 956857 288561 70997 393786 337382 663642 131184 637 273801 799870 295017 392338 842567 161819 297705 102013 930684 375703 838048 154915 138503 629056 256591 893619 19263 787927 684541 320265 841090 421423 490879 394582 493952 619247 633202 612928 50907 276653 407819 489945 153173\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n", "output": "-1\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1\r\n"}, {"input": "2\r\n3 2\r\n", "output": "1\r\n"}, {"input": "2\r\n2 3\r\n", "output": "1\r\n"}]
false
stdio
null
true
152/B
152
B
Python 3
TESTS
6
234
921,600
3731189
import re import itertools from collections import Counter class Task: n, m = 0, 0 start, end = 0, 0 vectors = [] answer = 0 def getData(self): self.n, self.m = [int(x) for x in input().split(' ')] self.start, self.end = [int(x) for x in input().split(' ')] numberOfVectors = int(input()) for i in range(0, numberOfVectors): self.vectors += [[int(x) for x in input().split(' ')]] def solve(self): x, y = self.start, self.end for currentVector in self.vectors: maxStepsX = self.maxSteps(self.n, x, currentVector[0]) maxStepsY = self.maxSteps(self.m, y, currentVector[1]) x += min(maxStepsX, maxStepsY) * currentVector[0] y += min(maxStepsX, maxStepsY) * currentVector[1] self.answer += min(maxStepsX, maxStepsY) def maxSteps(self, maxX, x, dx): if dx == 0: return maxX - 1 return (maxX - x) // dx if dx > 0 else (x - 1) // (-dx) def printAnswer(self): print(self.answer) task = Task(); task.getData(); task.solve(); task.printAnswer();
34
154
0
150376636
'''CodeForces: Steps''' import math if __name__ == '__main__': # input Operation n, m = list(map(int, input().split())) x, y = list(map(int, input().split())) steps = 0 for _ in range(int(input())): a = math.inf dx, dy = map(int, input().split()) if dx > 0: a = min(a, (n - x) // dx) if dx < 0: a = min(a, (x - 1) // -dx) if dy > 0: a = min(a, (m - y) // dy) if dy < 0: a = min(a, (y - 1) // -dy) x += dx * a y += dy * a steps += a print(steps)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
560/A
560
A
Python 3
TESTS
3
31
0
189228068
# -*- coding: utf-8 -*- """ Created on Sat Jan 14 12:02:06 2023 @author: Lenovo """ n = int(input()) s = input() if '1' in s: print(-1) else: print(1)
16
31
0
219699260
n=int(input()) arr=[int(i) for i in input().split()] arr.sort() if arr[0]==1: print(-1) else : print(1)
Codeforces Round 313 (Div. 2)
CF
2,015
2
256
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
null
null
[{"input": "5\n1 2 3 4 5", "output": "-1"}]
1,000
["implementation", "sortings"]
16
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "-1\r\n"}, {"input": "1\r\n2\r\n", "output": "1\r\n"}, {"input": "10\r\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837\r\n", "output": "-1\r\n"}, {"input": "10\r\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264\r\n", "output": "1\r\n"}, {"input": "50\r\n110876 835020 859879 999908 712969 788264 287153 921820 330355 499311 209594 484829 296329 940051 174081 931503 1 780512 390075 97866 124255 950067 697612 244256 782385 789882 37608 82153 399889 598867 416717 377988 535636 511221 792568 683271 131077 290194 496712 330720 587436 563481 645817 942562 654093 980561 382937 48293 582608 116156\r\n", "output": "-1\r\n"}, {"input": "50\r\n474421 421097 217233 156339 27075 733996 281778 863492 184707 956857 288561 70997 393786 337382 663642 131184 637 273801 799870 295017 392338 842567 161819 297705 102013 930684 375703 838048 154915 138503 629056 256591 893619 19263 787927 684541 320265 841090 421423 490879 394582 493952 619247 633202 612928 50907 276653 407819 489945 153173\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n", "output": "-1\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1\r\n"}, {"input": "2\r\n3 2\r\n", "output": "1\r\n"}, {"input": "2\r\n2 3\r\n", "output": "1\r\n"}]
false
stdio
null
true
560/A
560
A
Python 3
TESTS
3
46
0
22872075
n=int(input()) a=list(map(int,input().split())) print(-1 if min(a)==1 else min(a)-1)
16
31
0
219699469
n=int (input()) arr=[int(i) for i in input().split()] arr.sort() if arr[0]==1: print(-1) else: print(1)
Codeforces Round 313 (Div. 2)
CF
2,015
2
256
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
null
null
[{"input": "5\n1 2 3 4 5", "output": "-1"}]
1,000
["implementation", "sortings"]
16
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "-1\r\n"}, {"input": "1\r\n2\r\n", "output": "1\r\n"}, {"input": "10\r\n371054 506438 397130 1 766759 208409 769264 549213 641270 771837\r\n", "output": "-1\r\n"}, {"input": "10\r\n635370 154890 909382 220996 276501 716105 538714 140162 171960 271264\r\n", "output": "1\r\n"}, {"input": "50\r\n110876 835020 859879 999908 712969 788264 287153 921820 330355 499311 209594 484829 296329 940051 174081 931503 1 780512 390075 97866 124255 950067 697612 244256 782385 789882 37608 82153 399889 598867 416717 377988 535636 511221 792568 683271 131077 290194 496712 330720 587436 563481 645817 942562 654093 980561 382937 48293 582608 116156\r\n", "output": "-1\r\n"}, {"input": "50\r\n474421 421097 217233 156339 27075 733996 281778 863492 184707 956857 288561 70997 393786 337382 663642 131184 637 273801 799870 295017 392338 842567 161819 297705 102013 930684 375703 838048 154915 138503 629056 256591 893619 19263 787927 684541 320265 841090 421423 490879 394582 493952 619247 633202 612928 50907 276653 407819 489945 153173\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n", "output": "-1\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1\r\n"}, {"input": "2\r\n3 2\r\n", "output": "1\r\n"}, {"input": "2\r\n2 3\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
124
0
112232498
n = int(input()) alchoholic = 'ABSINTH BEER BRANDY CHAMPAGNE GIN RUM SAKE TEQUILA VODKA WHISKEY WINE' ans = 0 for i in range(n): x = input() if x in alchoholic: ans += 1 elif x.isnumeric(): ans += 1 if int(x) < 18 else 0 print(ans)
28
62
0
150139438
n = int(input()) lst = [] c = 0 alcohol = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"] while n: n -= 1 lst.append(input()) for i in lst: if i.isdigit() and int(i) < 18: c += 1 elif i in alcohol: c += 1 print(c)
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
124
0
112233221
n = int(input()) alchoholic = ' ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE' ans = 0 for i in range(n): x = input() if x in alchoholic: ans += 1 elif x.isnumeric(): if int(x) < 18: ans += 1 print(ans)
28
62
0
195250963
drinks = ["ABSINTH","BEER","BRANDY","CHAMPAGNE","GIN","RUM","SAKE","TEQUILA","VODKA", "WHISKEY", "WINE"] ans=0 for _ in range(int(input())): s=input() if s.isdigit() and int(s)<18: ans+=1 elif s.isalpha() and s in drinks: ans+=1 print(ans)
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/E
56
E
PyPy 3
TESTS
7
498
6,246,400
66756304
from typing import List, Tuple from bisect import bisect_left import math def get_max(tree: List[int], node: int, nl:int, nr: int, l: int, r: int) -> int: if nl >= l and nr <= r: return tree[node] if nl > r or nr < l: return -1 mid = (nl + nr) // 2 return max( get_max(tree, 2 * node + 1, nl, mid, l, r), get_max(tree, 2 * node + 2, mid + 1, nr, l, r), ) def update_max(tree: List[int], node: int, nl:int, nr: int, id: int, val: int) -> int: if nl == id and nr == id: tree[node] = max(tree[node], val) return tree[node] mid = (nl + nr) // 2 if id <= mid: new_max = update_max(tree, 2 * node + 1, nl, mid, id, val) else: new_max = update_max(tree, 2 * node + 2, mid + 1, nr, id, val) tree[node] = max(tree[node], new_max) return tree[node] def compute(n: int, d: List[Tuple[int, int]]) -> List[int]: if n == 1: return [1] d = [(x, i, h) for i, (x, h) in enumerate(d)] d = sorted(d) xp = [x for x, _, _ in d] tree_levels = int(math.ceil(math.log2(n))) tree_size = 2 ** (tree_levels + 1) - 1 tree = [0] * tree_size output = [1] * n for i in range(n - 1, -1, -1): x, id, h = d[i] j = bisect_left(xp, x + h, i) - 1 max_dist = max(get_max(tree, 0, 0, n - 1, i, j), x + h) update_max(tree, 0, 0, n - 1, i, max_dist) output[id] = bisect_left(xp, max_dist, i) - i return output if __name__ == '__main__': N = int(input()) D = [input().split() for _ in range(N)] D = [(int(x), int(h)) for x, h in D] print(' '.join([str(val) for val in compute(N, D)]))
34
842
21,504,000
181521732
import bisect import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def update(i, x, tree): i += l1 tree[i] = x i //= 2 while i: tree[i] = max(tree[2 * i], tree[2 * i + 1]) i //= 2 return def get_max(s, t, tree): s += l1 t += l1 ans = -inf while s <= t: if s % 2 == 0: s //= 2 else: ans = max(ans, tree[s]) s = (s + 1) // 2 if t % 2 == 1: t //= 2 else: ans = max(ans, tree[t]) t = (t - 1) // 2 return ans n = int(input()) d = dict() for i in range(n): x, h = map(int, input().split()) d[x] = (i, h) u = list(d.keys()) u.sort() inf = pow(10, 9) + 1 l1 = pow(2, n.bit_length()) l2 = 2 * l1 ma = [-inf] * l2 for i in range(n): ma[i + l1] = i + 1 for i in range(l1 - 1, 0, -1): ma[i] = max(ma[2 * i], ma[2 * i + 1]) ans = [0] * n for i in range(n - 1, -1, -1): x = u[i] j, h = d[x] r = bisect.bisect_left(u, x + h) - 1 l = i m = get_max(l, r, ma) ans[j] = m - i update(i, m, ma) sys.stdout.write(" ".join(map(str, ans)))
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Domino Principle
Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has the coordinate xi and the height hi. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that. Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate x and height h leads to the fall of all dominoes on the segment [x + 1, x + h - 1].
The first line contains integer n (1 ≤ n ≤ 105) which is the number of dominoes. Then follow n lines containing two integers xi and hi ( - 108 ≤ xi ≤ 108, 2 ≤ hi ≤ 108) each, which are the coordinate and height of every domino. No two dominoes stand on one point.
Print n space-separated numbers zi — the number of dominoes that will fall if Vasya pushes the i-th domino to the right (including the domino itself).
null
null
[{"input": "4\n16 5\n20 5\n10 10\n18 2", "output": "3 1 4 1"}, {"input": "4\n0 10\n1 5\n9 10\n15 10", "output": "4 1 2 1"}]
2,200
["binary search", "data structures", "sortings"]
34
[{"input": "4\r\n16 5\r\n20 5\r\n10 10\r\n18 2\r\n", "output": "3 1 4 1 "}, {"input": "4\r\n0 10\r\n1 5\r\n9 10\r\n15 10\r\n", "output": "4 1 2 1 "}, {"input": "3\r\n6 7\r\n2 9\r\n-6 10\r\n", "output": "1 2 3 "}, {"input": "4\r\n-6 9\r\n9 5\r\n-7 4\r\n0 9\r\n", "output": "2 1 3 1 "}, {"input": "5\r\n-47 19\r\n-43 14\r\n83 27\r\n-67 46\r\n-58 98\r\n", "output": "2 1 1 4 3 "}, {"input": "6\r\n20 39\r\n38 13\r\n-25 48\r\n-22 38\r\n13 39\r\n90 54\r\n", "output": "2 1 5 4 3 1 "}, {"input": "10\r\n34 9\r\n-41 26\r\n-62 32\r\n1 10\r\n77 14\r\n92 7\r\n-45 35\r\n75 19\r\n-23 2\r\n-46 8\r\n", "output": "1 2 5 1 1 1 3 3 1 4 "}]
false
stdio
null
true
152/B
152
B
Python 3
TESTS
4
92
0
214199374
n, m = list(map(int, input().split())) x, y = list(map(int, input().split())) k = int(input()) ans = 0 def calc(n, x, dx): if dx == 0: return 100000000 if dx > 0: return (n - x) // dx return (x - 1) // -dx for q in range(k): dx, dy = list(map(int, input().split())) steps = min(calc(n, x, dx), calc(m, y, dy)) x += dx * steps y += dy * steps ans += steps #print(steps) print(ans)
34
154
0
163447778
from math import inf n,m = map(int,input().split()) x,y = map(int,input().split()) total = 0 for i in range(int(input())): dx,dy = map(int,input().split()) stepsX = 0 if dx > 0 : permetedX = n -x stepsX = permetedX // dx if dx <0 : permetedX = x-1 stepsX = permetedX // abs(dx) stepsX *= -1 if dx == 0: stepsX = inf stepsY = 0 if dy > 0 : permetedY = m-y stepsY = permetedY // dy if dy <0 : permetedY = y-1 stepsY = permetedY // abs(dy) stepsY *=-1 if dy == 0: stepsY = inf steps = min(abs(stepsX),abs(stepsY)) x = x + dx*steps y = y + dy*steps total += steps # print(x,y,steps) print(total)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
845/D
845
D
PyPy 3
TESTS
7
311
9,318,400
132049448
class LazySegTree: # RMQ and RUQ def __init__(self, init_val, seg_ide, lazy_ide, segfunc): self.n = len(init_val) self.num = 2**(self.n-1).bit_length() self.seg_ide = seg_ide self.lazy_ide = lazy_ide self.segfunc = segfunc # seg, lazy: 1-indexed self.seg = [seg_ide]*2*self.num for i in range(self.n): self.seg[i+self.num] = init_val[i] for i in range(self.num-1, 0, -1): self.seg[i] = self.segfunc(self.seg[2*i], self.seg[2*i+1]) self.lazy = [lazy_ide]*2*self.num def gindex(self, l, r): # l, r: 1-indexed L = l + self.num R = r + self.num lm = (L // (L & -L)) >> 1 rm = (R // (R & -R)) >> 1 while L < R: if R <= rm: yield R if L <= lm: yield L L = L >> 1 R = R >> 1 while L: yield L L = L >> 1 def propagate(self, *ids): # ids: 1-indexed for i in reversed(ids): v = self.lazy[i] if v is None: continue self.lazy[2*i] = self.lazy[2*i+1] = self.seg[2*i] = self.seg[2*i+1] = v self.lazy[i] = None def update(self, l, r, x): # l, r: 0-indexed # change x to [l, r) *ids, = self.gindex(l, r) self.propagate(*ids) L = l + self.num R = r + self.num while L < R: if R & 1: R -= 1 self.lazy[R] = self.seg[R] = x if L & 1: self.lazy[L] = self.seg[L] = x L += 1 L = L >> 1 R = R >> 1 for i in ids: # i: 1-indexed self.seg[i] = self.segfunc(self.seg[2*i], self.seg[2*i+1]) def query(self, l, r): # l, r: 0-indexed # query for [l, r) if r <= l: return self.seg_ide self.propagate(*self.gindex(l, r)) L = l + self.num R = r + self.num res = self.seg_ide while L < R: if R & 1: R -= 1 res = self.segfunc(res, self.seg[R]) if L & 1: res = self.segfunc(self.seg[L], res) L += 1 L = L >> 1 R = R >> 1 return res def __str__(self): # for debug arr = [self.query(i,i+1) for i in range(self.n)] return str(arr) import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n = int(input()) INF = 350 limit = INF cur = INF change = [] overtake = True notallowed = 0 import bisect ans = 0 seg = LazySegTree([-1]*400, -1, None, max) for i in range(n): temp = list(map(int, input().split())) if temp[0] == 1: s = temp[1] if cur > limit: cur = s continue else: cur = s if cur > limit: j = seg.query(cur, seg.n) k = bisect.bisect_right(change, j) ans += len(change)-k seg.update(cur, seg.n, -1) elif temp[0] == 2: if not overtake: ans += notallowed notallowed = 0 elif temp[0] == 3: s = temp[1] if cur > s: ans += 1 change.append(i) seg.update(s, s+1, i) limit = s elif temp[0] == 4: overtake = True notallowed = 0 elif temp[0] == 5: change.append(i) seg.update(INF, INF+1, i) limit = INF elif temp[0] == 6: overtake = False notallowed += 1 print(ans)
25
140
9,318,400
155527993
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) now = 0 ng = 0 ans = 0 x = [] for _ in range(n): t = list(map(int, input().split())) if t[0] == 1: now = t[1] while x and x[-1] < now: ans += 1 x.pop() elif t[0] == 2: ans += ng ng = 0 elif t[0] == 3: x.append(t[1]) while x and x[-1] < now: ans += 1 x.pop() elif t[0] == 4: ng = 0 elif t[0] == 5: x = [] else: ng += 1 print(ans)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
845/D
845
D
Python 3
TESTS
7
826
7,475,200
29668284
n = int(input()) answer = 0 arr = [] colvo_znak = 0 for i in range(n): arr.append(input()) for i in range(n): if len(arr[i])>1: arr[i]=arr[i].split() arr[i][1] = int(arr[i][1]) else: arr[i] = int(arr[i]) speed_p = 0 arr_zn =-1 arr_not_of_spid = [100000000] for i in range(n): if len(str(arr[i]))>1: if arr[i][0]=="1": speed_p = arr[i][1] if arr[i][1] > arr_not_of_spid[0]: answer+=1 if len(str(arr[i]))>1: if arr[i][0]=="3": arr_not_of_spid[0]=arr[i][1] if i != n-1: if len(str(arr[i+1]))<2 and speed_p > arr[i][1]: answer+=1 if arr[i]==6: arr_zn=6 colvo_znak+=1 if arr[i] == 5: arr_not_of_spid = [100000000] if arr[i]==4: arr_zn =4 colvo_znak = 0 if arr[i]==2 and arr_zn==6: answer+=colvo_znak colvo_znak = 0 print(answer)
25
155
9,318,400
132050195
import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n = int(input()) overtake = True notallowed = 0 stack = [] cur = -1 ans = 0 for i in range(n): temp = list(map(int, input().split())) if temp[0] == 1: s = temp[1] while stack and stack[-1] < s: stack.pop() ans += 1 cur = s elif temp[0] == 2: if not overtake: ans += notallowed notallowed = 0 elif temp[0] == 3: s = temp[1] if cur > s: ans += 1 else: stack.append(s) elif temp[0] == 4: overtake = True notallowed = 0 elif temp[0] == 5: stack = [] elif temp[0] == 6: overtake = False notallowed += 1 print(ans)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
845/D
845
D
Python 3
TESTS
7
311
3,788,800
143344925
import math listOfEvents = [] allowedSpeed = math.inf currentSpeed = 0 overtakeAllowed = True overtaking = False mistakes = 0 numberOfOvertakeLimit = 0 numberOfEvents = int(input()) for i in range(numberOfEvents): listOfEvents.append(input()) for event in listOfEvents: if event[0] == '1': tempList = event.split(' ') currentSpeed = int(tempList[1]) if currentSpeed > allowedSpeed: mistakes += 1 elif event[0] == '2': overtaking = True if not overtakeAllowed: mistakes += numberOfOvertakeLimit numberOfOvertakeLimit = 0 elif event[0] == '3': tempList = event.split(' ') allowedSpeed = int(tempList[1]) if currentSpeed > allowedSpeed: mistakes += 1 elif event[0] == '4': overtakeAllowed = True numberOfOvertakeLimit = 0 elif event[0] == '5': allowedSpeed = math.inf elif event[0] == '6': overtakeAllowed = False numberOfOvertakeLimit += 1 print(mistakes)
25
249
8,601,600
93327437
import sys n = int(sys.stdin.buffer.readline().decode('utf-8')) inf = 10**9 speed = 0 limit = [inf] overtake = 1 ot_sign = 0 ans = 0 for _ in range(n): q = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split())) if q[0] == 1: while limit[-1] < q[1]: ans += 1 limit.pop() speed = q[1] elif q[0] == 2: if not overtake: ans += ot_sign ot_sign = 0 elif q[0] == 3: if speed > q[1]: ans += 1 else: limit.append(q[1]) elif q[0] == 4: overtake = 1 ot_sign = 0 elif q[0] == 5: limit.clear() limit.append(inf) else: overtake = 0 ot_sign += 1 print(ans)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
408/A
408
A
Python 3
TESTS
4
31
0
154821974
n = int(input()) book = {} cashiers = [int(num) for num in input().split(' ', n-1)] for i in range(0, n): key = cashiers[i] tem = [int(x) for x in input().split()] book[key] = tem time_list = [] for i in range(0, n): t = 5 * sum(book[cashiers[i]]) + 15 * cashiers[i] time_list.append(t) print(min(time_list))
20
31
0
183971755
n=int(input()) l=list(map(int, input().split())) mintime=1e10 for i in l: k=list(map(int, input().split())) time=sum(k)*5+i*15 if(time<mintime): mintime=time print(mintime)
Codeforces Round 239 (Div. 2)
CF
2,014
1
256
Line to Cashier
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that: - the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.
Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.
null
In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.
[{"input": "1\n1\n1", "output": "20"}, {"input": "4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8", "output": "100"}]
900
["implementation"]
20
[{"input": "1\r\n1\r\n1\r\n", "output": "20\r\n"}, {"input": "4\r\n1 4 3 2\r\n100\r\n1 2 2 3\r\n1 9 1\r\n7 8\r\n", "output": "100\r\n"}, {"input": "4\r\n5 4 5 5\r\n3 1 3 1 2\r\n3 1 1 3\r\n1 1 1 2 2\r\n2 2 1 1 3\r\n", "output": "100\r\n"}, {"input": "5\r\n5 3 6 6 4\r\n7 5 3 3 9\r\n6 8 2\r\n1 10 8 5 9 2\r\n9 7 8 5 9 10\r\n9 8 3 3\r\n", "output": "125\r\n"}, {"input": "5\r\n10 10 10 10 10\r\n6 7 8 6 8 5 9 8 10 5\r\n9 6 9 8 7 8 8 10 8 5\r\n8 7 7 8 7 5 6 8 9 5\r\n6 5 10 5 5 10 7 8 5 5\r\n10 9 8 7 6 9 7 9 6 5\r\n", "output": "480\r\n"}, {"input": "10\r\n9 10 10 10 9 5 9 7 8 7\r\n11 6 10 4 4 15 7 15 5\r\n3 9 11 12 11 1 13 13 1 5\r\n6 15 9 12 3 2 8 12 11 10\r\n7 1 1 6 10 2 6 1 14 2\r\n8 14 2 3 6 1 14 1 12\r\n6 10 9 3 5\r\n13 12 12 7 13 4 4 8 10\r\n5 6 4 3 14 9 13\r\n8 12 1 5 7 4 13 1\r\n1 9 5 3 5 1 4\r\n", "output": "240\r\n"}, {"input": "10\r\n5 5 5 5 5 5 5 5 5 5\r\n5 5 4 5 4\r\n6 5 7 7 6\r\n5 4 4 5 5\r\n4 4 5 5 5\r\n7 6 4 5 7\r\n4 6 5 4 5\r\n6 6 7 6 6\r\n4 5 4 4 7\r\n7 5 4 4 5\r\n6 6 7 4 4\r\n", "output": "190\r\n"}, {"input": "1\r\n1\r\n100\r\n", "output": "515\r\n"}, {"input": "1\r\n90\r\n90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90\r\n", "output": "41850\r\n"}]
false
stdio
null
true
2/A
2
A
PyPy 3-64
TESTS
15
154
614,400
183727307
from sys import stdin; inp = stdin.readline def IA(): return list(map(int, inp().split())) def FA(): return list(map(float, inp().split())) def SA(): return inp().split() def I(): return int(inp()) def F(): return float(inp()) def S(): return inp() from collections import defaultdict from itertools import accumulate from operator import itemgetter def main(): n = I() scores = defaultdict(int) total = defaultdict(int) rounds = [] for i in range(n): n, s = list(input().split()) s = int(s) total[n] += s rounds.append((n,s)) # print(total) res = sorted(total.items(), key=itemgetter(1), reverse=True) max_s = res[0][1] # print(res) if res[0][1] != res[1][1]: return res[0][0] else: for r in rounds: scores[r[0]] += r[1] # print(scores[r[0]], r[0]) if scores[r[0]] >= max_s and total[r[0]] > 0: return r[0] if __name__ == '__main__': print(main())
20
62
0
163020676
# Description of the problem can be found at http://codeforces.com/problemset/problem/2/A n = int(input()) l_k = list() for _ in range(n): l_k.append(input().split()) d_s = {} for i in range(n): k = l_k[i][0] s = int(l_k[i][1]) if k not in d_s: d_s[k] = int(s) else: d_s[k] += int(s) m = max(d_s[x] for x in d_s) d_s_2 = {} for i in range(n): k = l_k[i][0] s = int(l_k[i][1]) if k not in d_s_2: d_s_2[k] = int(s) else: d_s_2[k] += int(s) if d_s_2[k] >= m and d_s[k] == m: print(k) quit()
Codeforces Beta Round 2
ICPC
2,010
1
64
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Print the name of the winner.
null
null
[{"input": "3\nmike 3\nandrew 5\nmike 2", "output": "andrew"}, {"input": "3\nandrew 3\nandrew 2\nmike 5", "output": "andrew"}]
1,500
["hashing", "implementation"]
20
[{"input": "3\r\nmike 3\r\nandrew 5\r\nmike 2\r\n", "output": "andrew\r\n"}, {"input": "3\r\nandrew 3\r\nandrew 2\r\nmike 5\r\n", "output": "andrew\r\n"}, {"input": "5\r\nkaxqybeultn -352\r\nmgochgrmeyieyskhuourfg -910\r\nkaxqybeultn 691\r\nmgochgrmeyieyskhuourfg -76\r\nkaxqybeultn -303\r\n", "output": "kaxqybeultn\r\n"}, {"input": "7\r\nksjuuerbnlklcfdjeyq 312\r\ndthjlkrvvbyahttifpdewvyslsh -983\r\nksjuuerbnlklcfdjeyq 268\r\ndthjlkrvvbyahttifpdewvyslsh 788\r\nksjuuerbnlklcfdjeyq -79\r\nksjuuerbnlklcfdjeyq -593\r\nksjuuerbnlklcfdjeyq 734\r\n", "output": "ksjuuerbnlklcfdjeyq\r\n"}, {"input": "12\r\natrtthfpcvishmqbakprquvnejr 185\r\natrtthfpcvishmqbakprquvnejr -699\r\natrtthfpcvishmqbakprquvnejr -911\r\natrtthfpcvishmqbakprquvnejr -220\r\nfcgslzkicjrpbqaifgweyzreajjfdo 132\r\nfcgslzkicjrpbqaifgweyzreajjfdo -242\r\nm 177\r\nm -549\r\natrtthfpcvishmqbakprquvnejr -242\r\nm 38\r\natrtthfpcvishmqbakprquvnejr -761\r\nfcgslzkicjrpbqaifgweyzreajjfdo 879\r\n", "output": "fcgslzkicjrpbqaifgweyzreajjfdo\r\n"}, {"input": "15\r\naawtvezfntstrcpgbzjbf 681\r\nzhahpvqiptvksnbjkdvmknb -74\r\naawtvezfntstrcpgbzjbf 661\r\njpdwmyke 474\r\naawtvezfntstrcpgbzjbf -547\r\naawtvezfntstrcpgbzjbf 600\r\nzhahpvqiptvksnbjkdvmknb -11\r\njpdwmyke 711\r\nbjmj 652\r\naawtvezfntstrcpgbzjbf -1000\r\naawtvezfntstrcpgbzjbf -171\r\nbjmj -302\r\naawtvezfntstrcpgbzjbf 961\r\nzhahpvqiptvksnbjkdvmknb 848\r\nbjmj -735\r\n", "output": "aawtvezfntstrcpgbzjbf\r\n"}, {"input": "17\r\nqdplghhx -649\r\nivhgbxiv 424\r\nivhgbxiv -72\r\nivhgbxiv 479\r\nugowfouebkelargxylsxn 83\r\nugowfouebkelargxylsxn -840\r\nivhgbxiv 382\r\nqdplghhx -904\r\nivhgbxiv -710\r\nugowfouebkelargxylsxn -838\r\nqdplghhx -974\r\nqdplghhx 571\r\nivhgbxiv -145\r\nugowfouebkelargxylsxn -788\r\nivhgbxiv 209\r\nivhgbxiv 420\r\nqdplghhx -158\r\n", "output": "ivhgbxiv\r\n"}]
false
stdio
null
true
2/A
2
A
Python 3
TESTS
15
92
102,400
210104794
#print("n?") n = int(input()) winner = "" high_score = 0 list = {} record = [] winnerlist = [] #ゲームの記録 for i in range(n): #print(i) str = input().split() player = str[0] point = int(str[1]) #playerがlistに存在する/しない if(player in list): list[player] += point else: list[player] = point record.append([player,point]) #print(list) #print(record) #ゲームの振り返り for pl in list: if(list[pl] >= high_score): high_score = list[pl] winnerlist.append(pl) #print(winnerlist) if(len(winnerlist) == 1): winner = winnerlist[0] else: list.clear() for i in range(n): player = record[i][0] point = record[i][1] #playerがlistに存在する/しない if(player in list): list[player] += point else: list[player] = point if((player in winnerlist) and (list[player] >= high_score)): winner = player break print(winner)
20
62
102,400
207151523
all_members = {} first = '' mem = {} n = int(input()) lst = [input() for i in range(n)] for i in range(n): name, score = lst[i].split() if name not in all_members: all_members[name] = int(score) else: all_members[name] += int(score) f = max(all_members, key=all_members.get) if first == '': first = f elif all_members[f] > all_members[first]: first = max(all_members, key=all_members.get) maxx = all_members[first] for q in all_members: if all_members[q] == maxx: mem[q] = 0 for j in range(n): name, score = lst[j].split() if name in mem: mem[name] += int(score) else: continue if mem[name] >= maxx: print(name) break
Codeforces Beta Round 2
ICPC
2,010
1
64
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Print the name of the winner.
null
null
[{"input": "3\nmike 3\nandrew 5\nmike 2", "output": "andrew"}, {"input": "3\nandrew 3\nandrew 2\nmike 5", "output": "andrew"}]
1,500
["hashing", "implementation"]
20
[{"input": "3\r\nmike 3\r\nandrew 5\r\nmike 2\r\n", "output": "andrew\r\n"}, {"input": "3\r\nandrew 3\r\nandrew 2\r\nmike 5\r\n", "output": "andrew\r\n"}, {"input": "5\r\nkaxqybeultn -352\r\nmgochgrmeyieyskhuourfg -910\r\nkaxqybeultn 691\r\nmgochgrmeyieyskhuourfg -76\r\nkaxqybeultn -303\r\n", "output": "kaxqybeultn\r\n"}, {"input": "7\r\nksjuuerbnlklcfdjeyq 312\r\ndthjlkrvvbyahttifpdewvyslsh -983\r\nksjuuerbnlklcfdjeyq 268\r\ndthjlkrvvbyahttifpdewvyslsh 788\r\nksjuuerbnlklcfdjeyq -79\r\nksjuuerbnlklcfdjeyq -593\r\nksjuuerbnlklcfdjeyq 734\r\n", "output": "ksjuuerbnlklcfdjeyq\r\n"}, {"input": "12\r\natrtthfpcvishmqbakprquvnejr 185\r\natrtthfpcvishmqbakprquvnejr -699\r\natrtthfpcvishmqbakprquvnejr -911\r\natrtthfpcvishmqbakprquvnejr -220\r\nfcgslzkicjrpbqaifgweyzreajjfdo 132\r\nfcgslzkicjrpbqaifgweyzreajjfdo -242\r\nm 177\r\nm -549\r\natrtthfpcvishmqbakprquvnejr -242\r\nm 38\r\natrtthfpcvishmqbakprquvnejr -761\r\nfcgslzkicjrpbqaifgweyzreajjfdo 879\r\n", "output": "fcgslzkicjrpbqaifgweyzreajjfdo\r\n"}, {"input": "15\r\naawtvezfntstrcpgbzjbf 681\r\nzhahpvqiptvksnbjkdvmknb -74\r\naawtvezfntstrcpgbzjbf 661\r\njpdwmyke 474\r\naawtvezfntstrcpgbzjbf -547\r\naawtvezfntstrcpgbzjbf 600\r\nzhahpvqiptvksnbjkdvmknb -11\r\njpdwmyke 711\r\nbjmj 652\r\naawtvezfntstrcpgbzjbf -1000\r\naawtvezfntstrcpgbzjbf -171\r\nbjmj -302\r\naawtvezfntstrcpgbzjbf 961\r\nzhahpvqiptvksnbjkdvmknb 848\r\nbjmj -735\r\n", "output": "aawtvezfntstrcpgbzjbf\r\n"}, {"input": "17\r\nqdplghhx -649\r\nivhgbxiv 424\r\nivhgbxiv -72\r\nivhgbxiv 479\r\nugowfouebkelargxylsxn 83\r\nugowfouebkelargxylsxn -840\r\nivhgbxiv 382\r\nqdplghhx -904\r\nivhgbxiv -710\r\nugowfouebkelargxylsxn -838\r\nqdplghhx -974\r\nqdplghhx 571\r\nivhgbxiv -145\r\nugowfouebkelargxylsxn -788\r\nivhgbxiv 209\r\nivhgbxiv 420\r\nqdplghhx -158\r\n", "output": "ivhgbxiv\r\n"}]
false
stdio
null
true
152/B
152
B
Python 3
TESTS
6
654
7,577,600
128457609
def isValid(steps, n, m, startingPoint, vector): x, y = startingPoint return ((vector[0] * steps) + x <= n and (vector[1] * steps) + y <= m and (vector[1] * steps) + y > 0 and (vector[0] * steps) + x > 0) def getNumberOfSteps(vector, startingPoint, n, m): rightPointer = min(n, m) leftPointer = 0 steps = 0 while(rightPointer >= leftPointer): middlePointer = (rightPointer + leftPointer) // 2 if isValid(middlePointer, n, m, startingPoint, vector): steps = max(steps, middlePointer) leftPointer = middlePointer + 1 else: rightPointer = middlePointer - 1 startingPoint = ((vector[0] * steps) + startingPoint[0], (vector[1] * steps) + startingPoint[1]) return (steps, startingPoint) n, m = map(int, input().split()) x, y = map(int, input().split()) startingPoint = (x, y) k = int(input()) vectors = [] for i in range(k): x, y = map(int, input().split()) vector = (x, y) vectors.append(vector) steps = 0 for vector in vectors: currentSteps, startingPoint = getNumberOfSteps(vector, startingPoint, n, m) # print(currentSteps) steps += currentSteps print(steps)
34
154
0
167996801
n,m=list(map(int,input().split()));pos=list(map(int,input().split()));k=int(input());c=0 for i in range(k): x,y=list(map(int,input().split())) if x!=0 and y!=0: if x<0:numx=(pos[0]-1)//abs(x) elif x>0:numx=(n-pos[0])//abs(x) if y<0:numy=(pos[1]-1)//abs(y) elif y>0:numy=(m-pos[1])//abs(y) z=min(numx,numy) ; c+=z ; pos[0]+=z*x ; pos[1]+=z*y elif x==0: if y<0:numy=(pos[1]-1)//abs(y) elif y>0:numy=(m-pos[1])//abs(y) z=numy ; c+=z ; pos[1]+=z*y elif y==0: if x<0:numx=(pos[0]-1)//abs(x) elif x>0:numx=(n-pos[0])//abs(x) z=numx ; c+=z ; pos[0]+=z*x print(c)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
15/C
15
C
Python 3
TESTS
5
154
5,222,400
17975437
n = input() n = int(n) ans = 0 for i in range(0, n): x, m = map(int, input().split()) end = x+m-1 if x % 2 == 1: ans ^= x x = x+1 m = m-1 if m == 0: continue; if m % 2 == 1: ans ^= 1 if end % 2 == 0: ans ^= end if ans == 0: print('bolik') else: print('tolik')
25
248
4,505,600
191480790
import sys; R = sys.stdin.readline r = 0 for _ in range(int(R())): x,m = map(int,R().split()) a,b = x,x+m-1 if a&1: r ^= a; a += 1 if not b&1: r ^= b; b -= 1 if (b-a+1)&2: r ^= 1 print("tolik" if r else "bolik")
Codeforces Beta Round 15
ICPC
2,010
2
64
Industrial Nim
There are n stone quarries in Petrograd. Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it. Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses. Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik».
The first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.
Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise.
null
null
[{"input": "2\n2 1\n3 2", "output": "tolik"}, {"input": "4\n1 1\n1 1\n1 1\n1 1", "output": "bolik"}]
2,000
["games"]
25
[{"input": "2\r\n2 1\r\n3 2\r\n", "output": "tolik\r\n"}, {"input": "4\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n", "output": "bolik\r\n"}, {"input": "10\r\n2 3\r\n1 4\r\n5 8\r\n4 10\r\n10 8\r\n7 2\r\n1 2\r\n1 7\r\n4 10\r\n5 3\r\n", "output": "tolik\r\n"}, {"input": "20\r\n8 6\r\n6 3\r\n2 9\r\n7 8\r\n9 1\r\n2 4\r\n3 6\r\n6 3\r\n5 6\r\n5 3\r\n6 5\r\n2 10\r\n2 9\r\n6 3\r\n10 6\r\n10 10\r\n10 7\r\n3 9\r\n16 1\r\n1 3\r\n", "output": "bolik\r\n"}, {"input": "30\r\n53 12\r\n13 98\r\n21 60\r\n76 58\r\n39 5\r\n62 58\r\n73 80\r\n13 75\r\n37 45\r\n44 86\r\n1 85\r\n13 33\r\n17 50\r\n12 26\r\n97 48\r\n52 40\r\n2 71\r\n95 79\r\n38 76\r\n24 54\r\n91 39\r\n97 92\r\n94 80\r\n50 61\r\n33 56\r\n22 91\r\n39 94\r\n31 56\r\n28 16\r\n20 44\r\n", "output": "tolik\r\n"}, {"input": "1\r\n3737203222172202 1\r\n", "output": "tolik\r\n"}, {"input": "1\r\n3737203222172202 1\r\n", "output": "tolik\r\n"}]
false
stdio
null
true
152/B
152
B
PyPy 3
TESTS
4
684
30,822,400
123816054
from itertools import product from math import ceil, gcd, sqrt import string from decimal import Decimal def binary_table(string_with_all_characters, length_to_make): return [''.join(x) for x in product(string_with_all_characters, repeat=length_to_make)] def all_possible_substrings(string): return [int(string[i: j]) for i in range(len(string)) for j in range(i + 1, len(string) + 1)] def number_of_substrings(length): return int(length * (length + 1) / 2) height, width, = map(int, input().split()) initial_point_x, initial_point_y = map(int, input().split()) """ x - height y - width """ vectors = [] num_of_steps = 0 for i in range(int(input())): x, y = map(int, input().split()) x_ = 10000 y_ = 10000 if x > 0: x_ = (height - initial_point_x) // x elif x < 0: x_ = (initial_point_x - 1) // -x if y > 0: y_ = (width - initial_point_y) // y elif y < 0: y_ = (initial_point_y - 1) // -y mina = min(x_, y_) initial_point_x += mina * x initial_point_y += mina * y num_of_steps += mina print(num_of_steps)
34
154
0
196857259
n, m = map(int, input().split()) xc, yc = map(int, input().split()) k = int(input()) total_steps = 0 for i in range(k): dx, dy = map(int, input().split()) max_steps = float('inf') if dx > 0: max_steps = min(max_steps, (n - xc) // dx) elif dx < 0: max_steps = min(max_steps, (xc - 1) // (-dx)) if dy > 0: max_steps = min(max_steps, (m - yc) // dy) elif dy < 0: max_steps = min(max_steps, (yc - 1) // (-dy)) xc += max_steps * dx yc += max_steps * dy total_steps += max_steps print(total_steps)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
248/A
248
A
Python 3
TESTS
56
184
6,963,200
126720542
n = int(input()) numberofLeft = 0 numberofright = 0 numberofall = 0 out = 0 leftOnly = 0 rightOnly = 0 allOnly = 0 for i in range(n): inp = list(map(int, input().split())) if(inp[0] == 0 and inp[1] == 1): numberofright += 1 elif(inp[0] == 1 and inp[1] == 0): numberofLeft += 1 elif(inp[0] == 1 and inp[1] == 1): numberofall += 1 leftOnly += (2*numberofright)+numberofall rightOnly += (2*numberofLeft)+numberofall allOnly += numberofLeft+numberofright out = min(leftOnly, rightOnly, allOnly) print(out) """ 5 0 1 1 0 0 1 1 1 0 1 8 1 0 1 0 1 0 0 1 0 1 1 1 1 1 0 1 """
57
92
0
147455902
n = int(input()) left, right = 0, 0 for i in range(n): l, r = input().split(" ") left+=int(l) right+=int(r) ans = (min(left, n-left)+min(right, n-right)) print(ans)
Codeforces Round 152 (Div. 2)
CF
2,012
2
256
Cupboards
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find. And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open. Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position. Your task is to write a program that will determine the required number of seconds t.
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
null
null
[{"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1", "output": "3"}]
800
["implementation"]
57
[{"input": "5\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n", "output": "3\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "3\r\n0 1\r\n1 1\r\n1 1\r\n", "output": "1\r\n"}, {"input": "8\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n1 0\r\n0 1\r\n1 0\r\n", "output": "7\r\n"}, {"input": "8\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n1 1\r\n1 1\r\n0 1\r\n", "output": "6\r\n"}, {"input": "15\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "5\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n", "output": "4\r\n"}]
false
stdio
null
true
248/A
248
A
PyPy 3
TESTS
20
468
4,096,000
100880794
left = [] right = [] for _ in range(int(input())): l,r = map(int,input().split()) left.append(l) right.append(r) c = 0 if left.count(1) > left.count(0): c+=(len(left) - left.count(1)) elif left.count(1) < left.count(0): c+=(len(left) - left.count(0)) else: c+=(len(left)//2) if right.count(1) > right.count(0): c+=(len(right) - right.count(1) ) elif left.count(1) < left.count(0): c+=(len(right) - right.count(0)) else: c+=(len(right)//2) print(c)
57
92
0
205596452
n = int(input()) Ltotal, Rtotal = 0, 0 for x in range(n): l, r = map(int, input().split()) Ltotal += l Rtotal += r ans = 0 if Ltotal > n-Ltotal: ans += n-Ltotal else: ans += Ltotal if Rtotal > n-Rtotal: ans += n-Rtotal else: ans += Rtotal print(ans)
Codeforces Round 152 (Div. 2)
CF
2,012
2
256
Cupboards
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find. And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open. Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position. Your task is to write a program that will determine the required number of seconds t.
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
null
null
[{"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1", "output": "3"}]
800
["implementation"]
57
[{"input": "5\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n", "output": "3\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "3\r\n0 1\r\n1 1\r\n1 1\r\n", "output": "1\r\n"}, {"input": "8\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n1 0\r\n0 1\r\n1 0\r\n", "output": "7\r\n"}, {"input": "8\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n1 1\r\n1 1\r\n0 1\r\n", "output": "6\r\n"}, {"input": "15\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "5\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n", "output": "4\r\n"}]
false
stdio
null
true
248/A
248
A
Python 3
TESTS
56
154
0
173433372
n = int(input()) i = 1 a=b=0 while True: if i>n: break l,r = input().split() if int(l)==0: a = a+1 elif int(r)==0: b = b+1 i = i+1 k = [int(a+b), int(a+(n-b)), int((n-a)+b), int((n-a)+(n-b))] print(min(k))
57
92
0
207726325
t=int(input()) tot=0 tot1=0 debug = False for i in range(0,t): m,n=map(int,input().split()) tot=tot+m tot1=tot1+n mi=0 ma=0 if debug: print(tot, tot1) mi=min(tot,(t-tot)) ma=min(tot1,(t-tot1)) if debug: print(mi, ma, mi + ma) print(mi+ma)
Codeforces Round 152 (Div. 2)
CF
2,012
2
256
Cupboards
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find. And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open. Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position. Your task is to write a program that will determine the required number of seconds t.
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
null
null
[{"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1", "output": "3"}]
800
["implementation"]
57
[{"input": "5\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n", "output": "3\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "3\r\n0 1\r\n1 1\r\n1 1\r\n", "output": "1\r\n"}, {"input": "8\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n1 0\r\n0 1\r\n1 0\r\n", "output": "7\r\n"}, {"input": "8\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n1 1\r\n1 1\r\n0 1\r\n", "output": "6\r\n"}, {"input": "15\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "5\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n", "output": "4\r\n"}]
false
stdio
null
true
248/A
248
A
Python 3
TESTS
56
124
512,000
164725359
def solve(n,board): cl = cr = 0 for row in board: if row[0] == 0: cl+=1 elif row[1] == 0: cr +=1 return min(cl,n-cl)+min(cr,n-cr) n = int(input()) board = [] for i in range(n): board.append(list(map(int,input().split()))) print(solve(n,board))
57
92
0
207886016
a = int(input()) b0 = 0 b1 = 0 c0 = 0 c1 = 0 for i in range(a): b, c = map(int, input().split()) if b == 0: b0 += 1 else: b1 += 1 if c == 0: c0 += 1 else: c1 += 1 print(min(b0, b1) + min(c0, c1))
Codeforces Round 152 (Div. 2)
CF
2,012
2
256
Cupboards
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find. And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open. Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position. Your task is to write a program that will determine the required number of seconds t.
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
null
null
[{"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1", "output": "3"}]
800
["implementation"]
57
[{"input": "5\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n", "output": "3\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "3\r\n0 1\r\n1 1\r\n1 1\r\n", "output": "1\r\n"}, {"input": "8\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n1 0\r\n0 1\r\n1 0\r\n", "output": "7\r\n"}, {"input": "8\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n1 1\r\n1 1\r\n0 1\r\n", "output": "6\r\n"}, {"input": "15\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "5\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n", "output": "4\r\n"}]
false
stdio
null
true
501/C
501
C
PyPy 3-64
TESTS
2
62
512,000
156403356
n_vertices = int(input()) n_edges = 0 stack_leafs = [] ans = [] arr_s = [] arr_deg = [] for i in range(n_vertices): deg, s = map(int, input().split()) arr_deg.append(deg) arr_s.append(s) n_edges += deg if arr_deg[i] == 1: stack_leafs.append(i) # your code may be here n_edges //= 2 while stack_leafs: i = stack_leafs.pop() # 1 0 p = arr_s[i] # vertex, which connects with leaf | 0 if arr_deg[i]>0: ans.append((i, p)) # [(1, 0)] #print("Added", i, p) arr_s[p] ^= i arr_deg[p] -= 1 arr_deg[i] -= 1 if arr_deg[p] and arr_deg[i] > 1: stack_leafs.append(p) print(n_edges) for i in ans: print(*i)
49
327
12,800,000
9409593
def main(): import sys tokens = [int(i) for i in sys.stdin.read().split()] tokens.reverse() n = tokens.pop() vertices = [[tokens.pop(), tokens.pop()] for i in range(n)] l = [] for i in range(n): if vertices[i][0] == 1: l.append(i) result = [] while l: v = l.pop() if vertices[v][0] == 0: continue u = vertices[v][1] result.append((v, u)) vertices[u][0] -= 1 vertices[u][1] ^= v if vertices[u][0] == 1: l.append(u) print(len(result)) print('\n'.join(' '.join(str(j) for j in i) for i in result)) main()
Codeforces Round 285 (Div. 2)
CF
2,015
1
256
Misha and Forest
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space.
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
null
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
[{"input": "3\n2 3\n1 0\n1 0", "output": "2\n1 0\n2 0"}, {"input": "2\n1 1\n1 0", "output": "1\n0 1"}]
1,500
["constructive algorithms", "data structures", "greedy", "sortings", "trees"]
49
[{"input": "3\r\n2 3\r\n1 0\r\n1 0\r\n", "output": "2\r\n1 0\r\n2 0\r\n"}, {"input": "2\r\n1 1\r\n1 0\r\n", "output": "1\r\n0 1\r\n"}, {"input": "10\r\n3 13\r\n2 6\r\n1 5\r\n3 5\r\n1 3\r\n2 2\r\n2 6\r\n1 6\r\n1 3\r\n2 3\r\n", "output": "9\r\n2 5\r\n4 3\r\n7 6\r\n8 3\r\n5 0\r\n6 1\r\n3 9\r\n1 0\r\n9 0\r\n"}, {"input": "10\r\n1 2\r\n1 7\r\n1 0\r\n1 8\r\n0 0\r\n1 9\r\n0 0\r\n1 1\r\n1 3\r\n1 5\r\n", "output": "4\r\n0 2\r\n1 7\r\n3 8\r\n5 9\r\n"}, {"input": "5\r\n1 1\r\n2 2\r\n2 2\r\n2 6\r\n1 3\r\n", "output": "4\r\n0 1\r\n4 3\r\n1 2\r\n3 2\r\n"}, {"input": "10\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "11\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n1 8\r\n1 7\r\n0 0\r\n0 0\r\n", "output": "1\r\n7 8\r\n"}, {"input": "12\r\n0 0\r\n1 3\r\n0 0\r\n1 1\r\n0 0\r\n1 7\r\n0 0\r\n1 5\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "2\r\n1 3\r\n5 7\r\n"}, {"input": "13\r\n2 7\r\n0 0\r\n0 0\r\n2 11\r\n2 7\r\n2 14\r\n2 3\r\n2 1\r\n1 11\r\n3 15\r\n1 6\r\n2 11\r\n1 9\r\n", "output": "10\r\n8 11\r\n10 6\r\n12 9\r\n11 3\r\n6 9\r\n3 0\r\n9 5\r\n0 4\r\n5 7\r\n4 7\r\n"}, {"input": "14\r\n1 10\r\n1 9\r\n3 4\r\n1 2\r\n0 0\r\n1 11\r\n1 12\r\n1 10\r\n1 10\r\n2 10\r\n3 15\r\n3 14\r\n2 4\r\n0 0\r\n", "output": "10\r\n0 10\r\n1 9\r\n3 2\r\n5 11\r\n6 12\r\n7 10\r\n8 10\r\n9 11\r\n12 2\r\n11 2\r\n"}, {"input": "15\r\n0 0\r\n1 6\r\n3 2\r\n1 13\r\n2 15\r\n2 5\r\n1 1\r\n2 1\r\n1 4\r\n1 2\r\n0 0\r\n1 14\r\n0 0\r\n1 3\r\n2 9\r\n", "output": "9\r\n1 6\r\n3 13\r\n8 4\r\n9 2\r\n11 14\r\n4 7\r\n14 2\r\n7 5\r\n2 5\r\n"}, {"input": "16\r\n1 10\r\n2 13\r\n1 13\r\n2 1\r\n1 3\r\n2 2\r\n1 14\r\n0 0\r\n1 1\r\n1 14\r\n1 0\r\n0 0\r\n0 0\r\n1 2\r\n2 15\r\n0 0\r\n", "output": "8\r\n0 10\r\n2 13\r\n4 3\r\n6 14\r\n8 1\r\n9 14\r\n3 5\r\n1 5\r\n"}, {"input": "17\r\n0 0\r\n2 6\r\n0 0\r\n2 11\r\n0 0\r\n1 13\r\n1 3\r\n1 10\r\n0 0\r\n1 1\r\n1 7\r\n0 0\r\n0 0\r\n3 9\r\n0 0\r\n2 12\r\n0 0\r\n", "output": "7\r\n5 13\r\n6 3\r\n7 10\r\n9 1\r\n3 13\r\n1 15\r\n13 15\r\n"}, {"input": "18\r\n0 0\r\n0 0\r\n2 19\r\n1 2\r\n2 29\r\n0 0\r\n1 7\r\n1 6\r\n1 12\r\n1 13\r\n0 0\r\n1 12\r\n4 23\r\n1 9\r\n0 0\r\n0 0\r\n2 14\r\n1 4\r\n", "output": "9\r\n3 2\r\n6 7\r\n8 12\r\n9 13\r\n11 12\r\n17 4\r\n2 16\r\n4 12\r\n16 12\r\n"}, {"input": "19\r\n1 13\r\n0 0\r\n1 9\r\n1 11\r\n1 11\r\n2 3\r\n2 30\r\n0 0\r\n1 5\r\n1 2\r\n0 0\r\n5 29\r\n1 6\r\n2 11\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n2 13\r\n", "output": "10\r\n0 13\r\n2 9\r\n3 11\r\n4 11\r\n8 5\r\n12 6\r\n13 11\r\n5 11\r\n6 18\r\n11 18\r\n"}, {"input": "20\r\n0 0\r\n2 15\r\n0 0\r\n2 7\r\n1 1\r\n0 0\r\n0 0\r\n0 0\r\n1 9\r\n2 11\r\n0 0\r\n1 1\r\n0 0\r\n0 0\r\n1 3\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "5\r\n4 1\r\n8 9\r\n11 1\r\n14 3\r\n9 3\r\n"}, {"input": "1\r\n0 0\r\n", "output": "0\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] output_path = sys.argv[2] # not used submission_path = sys.argv[3] # Read input with open(input_path) as f: lines = [line.strip() for line in f if line.strip()] n = int(lines[0]) degrees = [] s_list = [] for line in lines[1:n+1]: d, s = map(int, line.split()) degrees.append(d) s_list.append(s) # Read submission output with open(submission_path) as f: sub_lines = [line.strip() for line in f if line.strip()] if not sub_lines: print(0) return try: m = int(sub_lines[0]) except: print(0) return edges = [] for line in sub_lines[1:]: parts = line.split() if len(parts) != 2: print(0) return try: a = int(parts[0]) b = int(parts[1]) except: print(0) return edges.append( (a, b) ) # Check sum_deg is even and m matches sum_deg = sum(degrees) if sum_deg % 2 != 0: print(0) return if m != sum_deg // 2: print(0) return # Check edges count if len(edges) != m: print(0) return # Check each edge is valid and no duplicates seen = set() for a, b in edges: if a == b: print(0) return if not (0 <= a < n) or not (0 <= b < n): print(0) return u, v = min(a, b), max(a, b) if (u, v) in seen: print(0) return seen.add( (u, v) ) # Build adjacency list adj = [[] for _ in range(n)] for a, b in edges: adj[a].append(b) adj[b].append(a) # Check degrees and XOR sums for v in range(n): if len(adj[v]) != degrees[v]: print(0) return xor_sum = 0 for nei in adj[v]: xor_sum ^= nei if xor_sum != s_list[v]: print(0) return # Check for cycles using Union-Find parent = list(range(n)) def find(u): while parent[u] != u: parent[u] = parent[parent[u]] u = parent[u] return u for a, b in edges: root_a = find(a) root_b = find(b) if root_a == root_b: print(0) return parent[root_a] = root_b # All checks passed print(1) if __name__ == "__main__": main()
true
248/A
248
A
Python 3
TESTS
56
278
512,000
76075712
def counter(massive: list) -> list: count1 = 0 count2 = 0 for i in range(len(massive)): if massive[i] == 1: count1 +=1 else: count2 += 1 if count1 >= count2: return count1, 1 else: return count2, 0 def diff(mass: list, number: int) -> list: count = 0 for i in range(len(mass)): if mass[i] != number: count += 1 return count left_doors = [] right_doors = [] n = int(input()) for i in range(n): a, b = input().split() left_doors.append(int(a)) right_doors.append(int(b)) left_count, num1 = counter(left_doors) right_count, num2 = counter(right_doors) if left_count <= right_count: num = num1 another = num2 else: num = num2 another = num1 first = diff(left_doors, num) second = diff(right_doors, another) answer = first + second print(answer)
57
92
0
209520121
n =int(input()) left_open = 0 right_open = 0 for _ in range(n): (left, right) = map(int, input().split()) if left == 1: left_open += 1 if right == 1: right_open += 1 min_left = min(left_open, n-left_open) min_right = min(right_open, n-right_open) print(min_left+min_right)
Codeforces Round 152 (Div. 2)
CF
2,012
2
256
Cupboards
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find. And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open. Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position. Your task is to write a program that will determine the required number of seconds t.
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
null
null
[{"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1", "output": "3"}]
800
["implementation"]
57
[{"input": "5\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n", "output": "3\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "3\r\n0 1\r\n1 1\r\n1 1\r\n", "output": "1\r\n"}, {"input": "8\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n1 0\r\n0 1\r\n1 0\r\n", "output": "7\r\n"}, {"input": "8\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n1 1\r\n1 1\r\n0 1\r\n", "output": "6\r\n"}, {"input": "15\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "5\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n", "output": "4\r\n"}]
false
stdio
null
true
248/A
248
A
PyPy 3-64
TESTS
56
342
4,915,200
209173990
n = int(input()) only_right = 0 only_left = 0 both = 0 neither = 0 for i in range(n): l, r = map(int, input().split()) if l == 0 and r == 0: both += 2 only_right += 1 only_left += 1 elif l == 0 and r == 1: only_left += 2 both += 1 neither += 1 elif l == 1 and r == 0: only_right += 2 both += 1 neither += 1 else: neither += 1 only_right += 1 only_left += 1 print(min(only_left, only_right, both, neither))
57
92
0
212998246
t = int(input()) left = 0 right = 0 for _ in range(t): p, q = map(int, input().split()) left += p right += q result = min(left, t - left) + min(right, t - right) print(result)
Codeforces Round 152 (Div. 2)
CF
2,012
2
256
Cupboards
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find. And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open. Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position. Your task is to write a program that will determine the required number of seconds t.
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
null
null
[{"input": "5\n0 1\n1 0\n0 1\n1 1\n0 1", "output": "3"}]
800
["implementation"]
57
[{"input": "5\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n", "output": "3\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "3\r\n0 1\r\n1 1\r\n1 1\r\n", "output": "1\r\n"}, {"input": "8\r\n0 1\r\n1 0\r\n0 1\r\n1 1\r\n0 1\r\n1 0\r\n0 1\r\n1 0\r\n", "output": "7\r\n"}, {"input": "8\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n1 1\r\n1 1\r\n0 1\r\n", "output": "6\r\n"}, {"input": "15\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n0 0\r\n", "output": "0\r\n"}, {"input": "5\r\n1 0\r\n1 0\r\n1 0\r\n0 1\r\n0 1\r\n", "output": "4\r\n"}]
false
stdio
null
true
845/D
845
D
Python 3
TESTS
7
436
0
29662805
import sys, os n = int(input()) a = set() k = 0 res = 0 for i in range(n): x = input() if x == "4": k = 0 continue if x == "2": res += k k = 0 continue if x == "6": k += 1 continue if x == "5": a = set() continue if x[0] == "3": d = int(x[2:]) if d < haste: res += 1 continue a.add(d) continue if x[0] == "1": d = int(x[2:]) haste = d for j in range(len(a)): l = min(a) if l < d: res += 1 a.remove(l) else: break print(res)
25
421
1,638,400
118122702
n = int(input()) r = 0 cnt = 0 sp = int(input()[2:]) lims = [301] for ind in range(n-1): s = input() if s[0] == "1": sp = int(s[2:]) while lims[-1] < sp: cnt += 1 lims.pop() elif s[0] == "2": cnt += r r = 0 elif s[0] == "3": newlim = int(s[2:]) if sp > newlim: cnt += 1 else: lims.append(newlim) elif s[0] == "4": r = 0 elif s[0] == "5": lims = [301] elif s[0] == "6": r += 1 print(cnt)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
437/C
437
C
PyPy 3
TESTS
11
140
2,048,000
22158462
from sys import stdin,stdout # stdin = open("/Users/seeva92/Workspace/Contests/1.txt","r") # stdout = open("/Users/seeva92/Workspace/Contests/2.txt","w") n,m = map(int,stdin.readline().split()) v = list(map(int,stdin.readline().split())) g = [list() for i in range(n)] for i in range(m): x,y = map(int,stdin.readline().split()) g[x-1].append(y-1) g[y-1].append(x-1) def main(): res = 0 vis = [False for i in range(n)] q = []; q.append(0); vis[0] = True mp = dict() while len(q)>0: t = q.pop(); for i in g[t]: if mp.get((i,t),0) == 0 and mp.get((t,i),0)==0: res += min(v[i],v[t]) mp[(i,t)] = 1; mp[(t,i)] = 1 q.append(i) stdout.write(str(res)) main()
29
31
0
183828239
n,m=map(int,input().split()) ans=0 num=list(map(int,input().split())) for i in range(m): x,y=map(int,input().split()) ans+=min(num[x-1],num[y-1]) print(ans)
Codeforces Round 250 (Div. 2)
CF
2,014
1
256
The Child and Toy
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed. Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.
Output the minimum total energy the child should spend to remove all n parts of the toy.
null
One of the optimal sequence of actions in the first sample is: - First, remove part 3, cost of the action is 20. - Then, remove part 2, cost of the action is 10. - Next, remove part 4, cost of the action is 10. - At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum. In the second sample, the child will spend 400 no matter in what order he will remove the parts.
[{"input": "4 3\n10 20 30 40\n1 4\n1 2\n2 3", "output": "40"}, {"input": "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4", "output": "400"}, {"input": "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4", "output": "160"}]
1,400
["graphs", "greedy", "sortings"]
29
[{"input": "4 3\r\n10 20 30 40\r\n1 4\r\n1 2\r\n2 3\r\n", "output": "40\r\n"}, {"input": "4 4\r\n100 100 100 100\r\n1 2\r\n2 3\r\n2 4\r\n3 4\r\n", "output": "400\r\n"}, {"input": "7 10\r\n40 10 20 10 20 80 40\r\n1 5\r\n4 7\r\n4 5\r\n5 2\r\n5 7\r\n6 4\r\n1 6\r\n1 3\r\n4 3\r\n1 4\r\n", "output": "160\r\n"}, {"input": "1 0\r\n23333\r\n", "output": "0\r\n"}, {"input": "5 4\r\n1 2 2 2 2\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "4\r\n"}, {"input": "10 30\r\n3 6 17 15 13 15 6 12 9 1\r\n3 8\r\n1 10\r\n4 7\r\n1 7\r\n3 7\r\n2 9\r\n8 10\r\n3 1\r\n3 4\r\n8 6\r\n10 3\r\n3 9\r\n2 3\r\n10 4\r\n2 10\r\n5 8\r\n9 5\r\n6 1\r\n2 1\r\n7 2\r\n7 6\r\n7 10\r\n4 8\r\n5 6\r\n3 6\r\n4 1\r\n8 9\r\n7 9\r\n4 2\r\n5 10\r\n", "output": "188\r\n"}, {"input": "3 3\r\n1 1 1\r\n1 2\r\n2 3\r\n3 1\r\n", "output": "3\r\n"}]
false
stdio
null
true
152/B
152
B
PyPy 3
TESTS
4
496
9,625,600
117850555
if __name__ == "__main__": n,m = (int(i) for i in input().split()) xc,yc = (int(i) for i in input().split()) k = int(input()) vecs = [(int(i) for i in input().split()) for _ in range(k)] total = 0 for dx,dy in vecs: x_dist = (xc-1 if dx < 0 else n-xc) x_moves = abs(x_dist//abs(dx)) if dx != 0 else max(xc-1,n-xc) y_dist = (yc-1 if dy < 0 else m-yc) y_moves = y_dist//abs(dy) if dy != 0 else max(yc-1,m-yc) moves = min(x_moves,y_moves) total += moves xc += moves*dx yc += moves*dy print(total)
34
154
512,000
150380654
n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) vectors = [] for i in range(k): dx, dy = map(int, input().split()) vectors.append([dx, dy]) no_of_steps = 0 for vector in vectors: temp = [] if(vector[0] != 0): if(vector[0] > 0): temp.append((n-x) // vector[0]) else: temp.append((1-x) // vector[0]) if(vector[1] != 0): if(vector[1] > 0): temp.append((m-y) // vector[1]) else: temp.append((1-y) // vector[1]) current_steps = min(temp) no_of_steps += current_steps x += current_steps*vector[0] y += current_steps*vector[1] print(no_of_steps)
Codeforces Round 108 (Div. 2)
CF
2,012
2
256
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).
Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
null
In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
[{"input": "4 5\n1 1\n3\n1 1\n1 1\n0 -2", "output": "4"}, {"input": "10 10\n1 2\n1\n-1 0", "output": "0"}]
1,300
["binary search", "implementation"]
34
[{"input": "4 5\r\n1 1\r\n3\r\n1 1\r\n1 1\r\n0 -2\r\n", "output": "4\r\n"}, {"input": "10 10\r\n1 2\r\n1\r\n-1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n10 3\r\n10\r\n-2 -6\r\n-1 0\r\n-8 0\r\n0 5\r\n-1 3\r\n16 -16\r\n-1 9\r\n0 -18\r\n9 -1\r\n-9 5\r\n", "output": "13\r\n"}, {"input": "20 10\r\n14 4\r\n10\r\n6 0\r\n-7 -7\r\n12 -2\r\n-4 9\r\n20 3\r\n-1 -16\r\n0 2\r\n-1 1\r\n20 0\r\n-1 1\r\n", "output": "4\r\n"}, {"input": "1000 2000\r\n226 566\r\n20\r\n0 -100\r\n-100 100\r\n100 0\r\n42 0\r\n-100 -79\r\n-66 -16\r\n0 -7\r\n-1 0\r\n0 100\r\n100 91\r\n99 0\r\n1 0\r\n-100 0\r\n70 -100\r\n-100 100\r\n100 1\r\n66 0\r\n-100 1\r\n-47 -100\r\n-42 0\r\n", "output": "708\r\n"}, {"input": "1 1\r\n1 1\r\n1\r\n1 1\r\n", "output": "0\r\n"}, {"input": "3 3\r\n2 2\r\n1\r\n2 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
2/A
2
A
Python 3
TESTS
13
92
0
218357268
d = {} mx = None for _ in range(int(input())): name,score = map(str,input().split()) score = int(score) if name in d: d[name]+=score else: d[name] = score if mx==None or d[name]>d[mx]:mx = name print(mx)
20
62
102,400
213979247
a,b={},[] for _ in ' '*int(input()): n,s=input().split(); a[n]=a.get(n,0)+int(s); b+=[(a[n],n)] m=max(a.values()) print([x for v,x in b if a[x]==m and v>=m][0])
Codeforces Beta Round 2
ICPC
2,010
1
64
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Print the name of the winner.
null
null
[{"input": "3\nmike 3\nandrew 5\nmike 2", "output": "andrew"}, {"input": "3\nandrew 3\nandrew 2\nmike 5", "output": "andrew"}]
1,500
["hashing", "implementation"]
20
[{"input": "3\r\nmike 3\r\nandrew 5\r\nmike 2\r\n", "output": "andrew\r\n"}, {"input": "3\r\nandrew 3\r\nandrew 2\r\nmike 5\r\n", "output": "andrew\r\n"}, {"input": "5\r\nkaxqybeultn -352\r\nmgochgrmeyieyskhuourfg -910\r\nkaxqybeultn 691\r\nmgochgrmeyieyskhuourfg -76\r\nkaxqybeultn -303\r\n", "output": "kaxqybeultn\r\n"}, {"input": "7\r\nksjuuerbnlklcfdjeyq 312\r\ndthjlkrvvbyahttifpdewvyslsh -983\r\nksjuuerbnlklcfdjeyq 268\r\ndthjlkrvvbyahttifpdewvyslsh 788\r\nksjuuerbnlklcfdjeyq -79\r\nksjuuerbnlklcfdjeyq -593\r\nksjuuerbnlklcfdjeyq 734\r\n", "output": "ksjuuerbnlklcfdjeyq\r\n"}, {"input": "12\r\natrtthfpcvishmqbakprquvnejr 185\r\natrtthfpcvishmqbakprquvnejr -699\r\natrtthfpcvishmqbakprquvnejr -911\r\natrtthfpcvishmqbakprquvnejr -220\r\nfcgslzkicjrpbqaifgweyzreajjfdo 132\r\nfcgslzkicjrpbqaifgweyzreajjfdo -242\r\nm 177\r\nm -549\r\natrtthfpcvishmqbakprquvnejr -242\r\nm 38\r\natrtthfpcvishmqbakprquvnejr -761\r\nfcgslzkicjrpbqaifgweyzreajjfdo 879\r\n", "output": "fcgslzkicjrpbqaifgweyzreajjfdo\r\n"}, {"input": "15\r\naawtvezfntstrcpgbzjbf 681\r\nzhahpvqiptvksnbjkdvmknb -74\r\naawtvezfntstrcpgbzjbf 661\r\njpdwmyke 474\r\naawtvezfntstrcpgbzjbf -547\r\naawtvezfntstrcpgbzjbf 600\r\nzhahpvqiptvksnbjkdvmknb -11\r\njpdwmyke 711\r\nbjmj 652\r\naawtvezfntstrcpgbzjbf -1000\r\naawtvezfntstrcpgbzjbf -171\r\nbjmj -302\r\naawtvezfntstrcpgbzjbf 961\r\nzhahpvqiptvksnbjkdvmknb 848\r\nbjmj -735\r\n", "output": "aawtvezfntstrcpgbzjbf\r\n"}, {"input": "17\r\nqdplghhx -649\r\nivhgbxiv 424\r\nivhgbxiv -72\r\nivhgbxiv 479\r\nugowfouebkelargxylsxn 83\r\nugowfouebkelargxylsxn -840\r\nivhgbxiv 382\r\nqdplghhx -904\r\nivhgbxiv -710\r\nugowfouebkelargxylsxn -838\r\nqdplghhx -974\r\nqdplghhx 571\r\nivhgbxiv -145\r\nugowfouebkelargxylsxn -788\r\nivhgbxiv 209\r\nivhgbxiv 420\r\nqdplghhx -158\r\n", "output": "ivhgbxiv\r\n"}]
false
stdio
null
true
29/D
29
D
Python 3
TESTS
4
92
0
219481182
def dfs(v, parent): route.append(v) for u in graph[v]: if u != parent: dfs(u, v) route.append(v) def solve(): leaf_order_index = 0 dfs(1, 0) for v in route: if v == leaf_order[leaf_order_index]: leaf_order_index += 1 if leaf_order_index == len(leaf_order): break if leaf_order_index != len(leaf_order): return -1 else: return route # Read input n = int(input()) graph = [[] for _ in range(n + 1)] for _ in range(n - 1): u, v = map(int, input().split()) graph[u].append(v) graph[v].append(u) leaf_order = list(map(int, input().split())) # Initialize the route route = [] # Calculate and print the route result = solve() if result == -1: print(result) else: print(" ".join(map(str, result)))
35
154
2,252,800
164853221
import sys input = sys.stdin.readline from collections import deque def build_tree(edges, root): children = dict() parent = dict() stack = deque() stack.append(root) parent[root] = -1 while stack: u = stack.pop() children[u] = [] for v in edges[u]: if v != parent[u]: stack.append(v) children[u].append(v) parent[v] = u return children, parent # def visit(u, children, parent, data): # return # def postvisit(u, children, parent, data): # data[u] = set().union(*[data[v] for v in children[u]]) # data[u].add(u) # def explore_tree(children, parent, root, data): # stack = deque() # stack.append((root, 0)) # while stack: # u, b = stack.pop() # if b == 0: # visit(u, children, parent, data) # stack.append((u, 1)) # for v in children[u]: # stack.append((v, 0)) # else: # postvisit(u, children, parent, data) def get_route(parent, root, u): route = [] while u != root: route.append(u) u = parent[u] route.append(u) return list(reversed(route)) def find_path(children, parent, root, route, l): path = [] seen = set() seen_count = dict() stack = deque() stack.append((root, 0)) i = 0 while stack: u, depth = stack.pop() path.append(u) seen.add(u) if i == len(l): continue if not children[u]: if depth + 1 != len(route[l[i]]) or route[l[i]][depth] != u: return path, False i += 1 else: if u not in seen_count: seen_count[u] = 0 if seen_count[u] == len(children[u]): continue if len(route[l[i]]) < depth + 2: return path, False if route[l[i]][depth] != u: return path, False if route[l[i]][depth + 1] in seen: return path, False if route[l[i]][depth + 1] not in children[u]: return path, False stack.append((u, depth)) stack.append((route[l[i]][depth + 1], depth + 1)) seen_count[u] += 1 return path, i == len(l) n = int(input()) edges = dict() for _ in range(n - 1): u, v = map(int, input().split()) if u not in edges: edges[u] = [] if v not in edges: edges[v] = [] edges[u].append(v) edges[v].append(u) children, parent = build_tree(edges, 1) l = [int(i) for i in input().split()] route = dict() for i in l: route[i] = get_route(parent, 1, i) path, valid = find_path(children, parent, 1, route, l) if valid: print(" ".join(map(str, path))) else: print(-1)
Codeforces Beta Round 29 (Div. 2, Codeforces format)
CF
2,010
2
256
Ant on the Tree
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too. An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex. The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
null
null
[{"input": "3\n1 2\n2 3\n3", "output": "1 2 3 2 1"}, {"input": "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 6 3", "output": "1 2 4 5 4 6 4 2 1 3 1"}, {"input": "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 3 6", "output": "-1"}]
2,000
["constructive algorithms", "dfs and similar", "trees"]
35
[{"input": "3\r\n1 2\r\n2 3\r\n3\r\n", "output": "1 2 3 2 1 "}, {"input": "6\r\n1 2\r\n1 3\r\n2 4\r\n4 5\r\n4 6\r\n5 6 3\r\n", "output": "1 2 4 5 4 6 4 2 1 3 1 "}, {"input": "6\r\n1 2\r\n1 3\r\n2 4\r\n4 5\r\n4 6\r\n5 3 6\r\n", "output": "-1\r\n"}, {"input": "10\r\n8 10\r\n2 1\r\n7 5\r\n5 4\r\n6 10\r\n2 3\r\n3 10\r\n2 9\r\n7 2\r\n6 9 4 8\r\n", "output": "-1\r\n"}, {"input": "8\r\n4 3\r\n6 7\r\n8 6\r\n6 1\r\n4 6\r\n6 5\r\n6 2\r\n3 2 7 8 5\r\n", "output": "1 6 4 3 4 6 2 6 7 6 8 6 5 6 1 "}, {"input": "8\r\n4 3\r\n1 4\r\n8 5\r\n7 6\r\n3 5\r\n7 3\r\n4 2\r\n2 6 8\r\n", "output": "1 4 2 4 3 7 6 7 3 5 8 5 3 4 1 "}, {"input": "20\r\n4 13\r\n17 7\r\n19 10\r\n18 1\r\n5 15\r\n2 6\r\n11 7\r\n3 6\r\n5 1\r\n20 16\r\n12 5\r\n10 17\r\n14 18\r\n8 13\r\n13 15\r\n19 1\r\n9 19\r\n6 13\r\n17 20\r\n14 12 4 2 3 9 8 11 16\r\n", "output": "-1\r\n"}, {"input": "3\r\n1 2\r\n1 3\r\n2 3\r\n", "output": "1 2 1 3 1 "}, {"input": "3\r\n1 2\r\n1 3\r\n3 2\r\n", "output": "1 3 1 2 1 "}, {"input": "4\r\n1 2\r\n1 3\r\n1 4\r\n4 3 2\r\n", "output": "1 4 1 3 1 2 1 "}, {"input": "5\r\n1 2\r\n4 3\r\n1 4\r\n4 5\r\n5 2 3\r\n", "output": "-1\r\n"}]
false
stdio
null
true
29/D
29
D
Python 3
TESTS
4
60
0
219480956
def find_route(tree, leaves_order): n = len(tree) leaf_index = 0 visited = [False] * (n + 1) route = [] def dfs(node): nonlocal leaf_index if visited[node]: return visited[node] = True route.append(node) if node == leaves_order[leaf_index]: leaf_index += 1 for neighbor in tree[node]: if not visited[neighbor]: dfs(neighbor) route.append(node) dfs(1) if leaf_index != len(leaves_order): return -1 else: return route # Read input n = int(input()) tree = [[] for _ in range(n + 1)] for _ in range(n - 1): a, b = map(int, input().split()) tree[a].append(b) tree[b].append(a) leaves_order = list(map(int, input().split())) # Find the route route = find_route(tree, leaves_order) # Print the result if route == -1: print(-1) else: print(' '.join(map(str, route)))
35
154
5,120,000
219368205
t=int(input()) my_dict={i+1:[] for i in range(t)} for i in range(t-1): a,b=map(int,input().split()) my_dict[a].append(b) my_dict[b].append(a) s=list(map(int,input().split())) my_dict2={i+1:[] for i in range(t)} queue=[1] vis=[1]*(t) vis[0]=0 while queue: ele=queue.pop(0) for i in my_dict[ele]: if vis[i-1] : vis[i-1]=0 my_dict2[ele].append(i) queue.append(i) listt=[] ele=1 def logic(my_dict2,ele): listt=[] for i in my_dict2[ele]: listt2=logic(my_dict2,i) for j in listt2: listt.append([ele]+j) if len(listt)==0: return [[ele]] return listt listt=logic(my_dict2,1) listt2=[-1]*t for i in listt: listt2[i[-1]-1]=i ans=[] def logic2(listt1,listt2): for i in range(min(len(listt1),len(listt2))-1): if listt1[i+1]!=listt2[i+1]: a=list(listt1[i:-1]) a.reverse() return a+list(listt2[i+1:]) ans=listt2[s[0]-1] for i in range(len(s)-1): a=listt2[s[i]-1] b=listt2[s[i+1]-1] ans.extend(logic2(a,b)) a=listt2[s[-1]-1][:-1] a.reverse() ans.extend(a) if len(ans)>2*(t-1)+1: print(-1) else: print(*ans)
Codeforces Beta Round 29 (Div. 2, Codeforces format)
CF
2,010
2
256
Ant on the Tree
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too. An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex. The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
null
null
[{"input": "3\n1 2\n2 3\n3", "output": "1 2 3 2 1"}, {"input": "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 6 3", "output": "1 2 4 5 4 6 4 2 1 3 1"}, {"input": "6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 3 6", "output": "-1"}]
2,000
["constructive algorithms", "dfs and similar", "trees"]
35
[{"input": "3\r\n1 2\r\n2 3\r\n3\r\n", "output": "1 2 3 2 1 "}, {"input": "6\r\n1 2\r\n1 3\r\n2 4\r\n4 5\r\n4 6\r\n5 6 3\r\n", "output": "1 2 4 5 4 6 4 2 1 3 1 "}, {"input": "6\r\n1 2\r\n1 3\r\n2 4\r\n4 5\r\n4 6\r\n5 3 6\r\n", "output": "-1\r\n"}, {"input": "10\r\n8 10\r\n2 1\r\n7 5\r\n5 4\r\n6 10\r\n2 3\r\n3 10\r\n2 9\r\n7 2\r\n6 9 4 8\r\n", "output": "-1\r\n"}, {"input": "8\r\n4 3\r\n6 7\r\n8 6\r\n6 1\r\n4 6\r\n6 5\r\n6 2\r\n3 2 7 8 5\r\n", "output": "1 6 4 3 4 6 2 6 7 6 8 6 5 6 1 "}, {"input": "8\r\n4 3\r\n1 4\r\n8 5\r\n7 6\r\n3 5\r\n7 3\r\n4 2\r\n2 6 8\r\n", "output": "1 4 2 4 3 7 6 7 3 5 8 5 3 4 1 "}, {"input": "20\r\n4 13\r\n17 7\r\n19 10\r\n18 1\r\n5 15\r\n2 6\r\n11 7\r\n3 6\r\n5 1\r\n20 16\r\n12 5\r\n10 17\r\n14 18\r\n8 13\r\n13 15\r\n19 1\r\n9 19\r\n6 13\r\n17 20\r\n14 12 4 2 3 9 8 11 16\r\n", "output": "-1\r\n"}, {"input": "3\r\n1 2\r\n1 3\r\n2 3\r\n", "output": "1 2 1 3 1 "}, {"input": "3\r\n1 2\r\n1 3\r\n3 2\r\n", "output": "1 3 1 2 1 "}, {"input": "4\r\n1 2\r\n1 3\r\n1 4\r\n4 3 2\r\n", "output": "1 4 1 3 1 2 1 "}, {"input": "5\r\n1 2\r\n4 3\r\n1 4\r\n4 5\r\n5 2 3\r\n", "output": "-1\r\n"}]
false
stdio
null
true
724/D
724
D
Python 3
PRETESTS
4
46
4,608,000
21297046
m = int(input()) s = input() d = [] i = 0 a = min(s[i: i + m]) i = s.rfind(a, i , i + m) d.append(a) while i + m < len(s): a = min(s[i + 1: i + 1 + m]) #print(s[i + 1: i + 1 + m]) d.append(a) #ind = i + 1 + m i = s.rfind(a, i + 1, i + 1 + m) #print(a, i) try: a = min(s[len(s) - m:]) ind = s.rfind(a, len(s) - m, len(s)) if ind != i: d.append(a) except: pass print(''.join(sorted(d)))
71
124
9,011,200
200894970
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline m = int(input()) s = [0] + list(input().rstrip()) n = len(s) - 1 u = [[] for _ in range(130)] for i in range(1, n + 1): u[s[i]].append(i) x = [0] * (n + 1) for i in range(97, 123): for j in u[i]: x[j] = 1 y = list(x) for j in range(1, n + 1): y[j] += y[j - 1] ok = 1 for j in range(m, n + 1): if not y[j] - y[j - m]: ok = 0 break if ok: for j in u[i]: x[j] = 0 la = 0 v = -1 c = 0 for j in range(1, n + 1): if s[j] < i: la = j elif s[j] == i: v = j if la + m == j: la = v c += 1 ans = [chr(j) * len(u[j]) for j in range(97, i)] + [chr(i) * c] break sys.stdout.write("".join(ans))
Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined)
CF
2,016
2
256
Dense Subsequence
You are given a string s, consisting of lowercase English letters, and the integer m. One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order. Formally, we choose a subsequence of indices 1 ≤ i1 < i2 < ... < it ≤ |s|. The selected sequence must meet the following condition: for every j such that 1 ≤ j ≤ |s| - m + 1, there must be at least one selected index that belongs to the segment [j,  j + m - 1], i.e. there should exist a k from 1 to t, such that j ≤ ik ≤ j + m - 1. Then we take any permutation p of the selected indices and form a new string sip1sip2... sipt. Find the lexicographically smallest string, that can be obtained using this procedure.
The first line of the input contains a single integer m (1 ≤ m ≤ 100 000). The second line contains the string s consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100 000. It is also guaranteed that the number m doesn't exceed the length of the string s.
Print the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.
null
In the first sample, one can choose the subsequence {3} and form a string "a". In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab".
[{"input": "3\ncbabc", "output": "a"}, {"input": "2\nabcab", "output": "aab"}, {"input": "3\nbcabcbaccba", "output": "aaabb"}]
1,900
["data structures", "greedy", "strings"]
71
[{"input": "3\r\ncbabc\r\n", "output": "a\r\n"}, {"input": "2\r\nabcab\r\n", "output": "aab\r\n"}, {"input": "3\r\nbcabcbaccba\r\n", "output": "aaabb\r\n"}, {"input": "5\r\nimmaydobun\r\n", "output": "ab\r\n"}, {"input": "5\r\nwjjdqawypvtgrncmqvcsergermprauyevcegjtcrrblkwiugrcjfpjyxngyryxntauxlouvwgjzpsuxyxvhavgezwtuzknetdibv\r\n", "output": "aaaabbcccccddeeeeeefggggggghiijjjjjjkkllmmnnnnoppppqqrrrrrrrrsstttttu\r\n"}, {"input": "10\r\nefispvmzuutsrpxzfrykhabznxiyquwvhwhrksrgzodtuepfvamilfdynapzhzyhncorhzuewrrkcduvuhwsrprjrmgctnvrdtpj\r\n", "output": "aaabcccddddeeeffffgghhhhhhhiiijjkkklm\r\n"}, {"input": "20\r\nhlicqhxayiodyephxlfoetfketnaabpfegqcrjzlshkxfzjssvpvzhzylgowwovgxznzowvpklbwbzhwtkkaomjkenhpedmbmjic\r\n", "output": "aaaabbbbcccddeeeeeeffffg\r\n"}, {"input": "50\r\ntyhjolxuexoffdkdwimsjujorgeksyiyvvqecvhpjsuayqnibijtipuqhkulxpysotlmtrsgygpkdhkrtntwqzrpfckiscaphyhv\r\n", "output": "aab\r\n"}, {"input": "1\r\nbaaa\r\n", "output": "aaab\r\n"}, {"input": "5\r\nbbbbba\r\n", "output": "ab\r\n"}, {"input": "10\r\nbbabcbbaabcbcbcbaabbccaacccbbbcaaacabbbbaaaccbcccacbbccaccbbaacaccbabcaaaacaccacbaaccaaccbaacabbbaac\r\n", "output": "aaaaaaaaaaa\r\n"}]
false
stdio
null
true
408/A
408
A
PyPy 3-64
TESTS
4
77
0
135938878
x = int(input()) ls = list(map(int, input().split())) my_dict = dict() for i in range(x) : my_dict[ls[i]] = list(map(int, input().split())) ans = 1000000001 for i in range(x) : key = ls[i] ans = min(ans, ((key * 15) + sum(my_dict[key]) * 5)) print(ans)
20
31
102,400
206447509
#Keshika Patwari #Indian Institute Of Technology, Jodhpur # 2022 import sys input=sys.stdin.readline def exe(): return min(k) n=int(input()) ln=list(map(int,input().split())) k=[] for i in range(n): a=list(map(int,input().split())) b=sum(a)*5+ln[i]*15 k.append(b) print(exe())
Codeforces Round 239 (Div. 2)
CF
2,014
1
256
Line to Cashier
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that: - the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.
Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.
null
In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.
[{"input": "1\n1\n1", "output": "20"}, {"input": "4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8", "output": "100"}]
900
["implementation"]
20
[{"input": "1\r\n1\r\n1\r\n", "output": "20\r\n"}, {"input": "4\r\n1 4 3 2\r\n100\r\n1 2 2 3\r\n1 9 1\r\n7 8\r\n", "output": "100\r\n"}, {"input": "4\r\n5 4 5 5\r\n3 1 3 1 2\r\n3 1 1 3\r\n1 1 1 2 2\r\n2 2 1 1 3\r\n", "output": "100\r\n"}, {"input": "5\r\n5 3 6 6 4\r\n7 5 3 3 9\r\n6 8 2\r\n1 10 8 5 9 2\r\n9 7 8 5 9 10\r\n9 8 3 3\r\n", "output": "125\r\n"}, {"input": "5\r\n10 10 10 10 10\r\n6 7 8 6 8 5 9 8 10 5\r\n9 6 9 8 7 8 8 10 8 5\r\n8 7 7 8 7 5 6 8 9 5\r\n6 5 10 5 5 10 7 8 5 5\r\n10 9 8 7 6 9 7 9 6 5\r\n", "output": "480\r\n"}, {"input": "10\r\n9 10 10 10 9 5 9 7 8 7\r\n11 6 10 4 4 15 7 15 5\r\n3 9 11 12 11 1 13 13 1 5\r\n6 15 9 12 3 2 8 12 11 10\r\n7 1 1 6 10 2 6 1 14 2\r\n8 14 2 3 6 1 14 1 12\r\n6 10 9 3 5\r\n13 12 12 7 13 4 4 8 10\r\n5 6 4 3 14 9 13\r\n8 12 1 5 7 4 13 1\r\n1 9 5 3 5 1 4\r\n", "output": "240\r\n"}, {"input": "10\r\n5 5 5 5 5 5 5 5 5 5\r\n5 5 4 5 4\r\n6 5 7 7 6\r\n5 4 4 5 5\r\n4 4 5 5 5\r\n7 6 4 5 7\r\n4 6 5 4 5\r\n6 6 7 6 6\r\n4 5 4 4 7\r\n7 5 4 4 5\r\n6 6 7 4 4\r\n", "output": "190\r\n"}, {"input": "1\r\n1\r\n100\r\n", "output": "515\r\n"}, {"input": "1\r\n90\r\n90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90\r\n", "output": "41850\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
92
0
107525829
n=int(input()) z=0 a=['ABSINTH', 'BEER',' BRANDY','CHAMPAGNE','GIN', 'RUM','SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] for i in range(n): s=input() if s in a: z+=1 try: if int(s)<18: z+=1 except: pass print(z)
28
62
0
230776815
n = int(input()) alcohol = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] ans = 0 for i in range(n): line = input() if line.isnumeric() and int(line) < 18 or line in alcohol: ans += 1 print(ans)
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
5
122
6,963,200
127308825
n=int(input()) lst=[] c=0 for i in range(0,n): item=str(input()) lst.append(item) if item[0]>='0' and item[0]<='9': k=int(item) if k<18: c+=1 elif item=='ABSINTH' or item=='BEER' or item=='BRANDY' or item=='CHAMPANGE' or item=='GIN' or item=='RUM' or item=='SAKE' or item=='TEQUILA' or item=='VODKA' or item=='WHISKEY' or item=='WINE': c+=1 print(c)
28
92
0
13091115
n = int(input()) a = 0 q = '1234567890' e = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] for i in range(n): s = input() if s[0] in q: s = int(s) if s < 18: a += 1 else: if s in e: a += 1 print(a)
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
908/C
908
C
PyPy 3
TESTS
6
186
2,150,400
76766429
# import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys input=sys.stdin.readline MOD = 1000000007 MOD2 = 998244353 ii = lambda: int(input().strip('\n')) si = lambda: input().strip('\n') dgl = lambda: list(map(int,input().strip('\n'))) f = lambda: map(int, input().strip('\n').split()) il = lambda: list(map(int, input().strip('\n').split())) ls = lambda: list(input().strip('\n')) let = 'abcdefghijklmnopqrstuvwxyz' n,r=f() l=il() ans=[r] for i in range(1,n): mx,tr=-1,-1 for j in range(i): if abs(l[j]-l[i])<=(2*r) and ans[j]>mx: mx=ans[j] tr=abs(l[i]-l[j]) if mx==-1: ans.append(r) else: ans.append(mx+(4*r*r-tr*tr)**0.5) print(*ans)
15
93
7,475,200
148743562
from collections import defaultdict as dd from collections import deque import bisect import heapq from math import sqrt def ri(): return int(input()) def rl(): return list(map(int, input().split())) def solve(): n, r = rl() r = r * 1.0 X = rl() prev = [] # y-coord of center in stopped position for x in X: highest = r for i, y2 in enumerate(prev): x2 = X[i] if abs(x2 - x) > 2 * r: continue y = sqrt(4*r*r - (x - x2)**2) + y2 highest = max(highest, y) prev.append(highest) print (*prev) mode = 's' if mode == 'T': t = ri() for i in range(t): solve() else: solve()
Good Bye 2017
CF
2,017
2
256
New Year and Curling
Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if $$\frac{|a-b|}{\max(1,b)} \leq 10^{-6}$$ for all coordinates.
null
The final positions of the disks will look as follows: In particular, note the position of the last disk.
[{"input": "6 2\n5 5 6 8 3 12", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613"}]
1,500
["brute force", "geometry", "implementation", "math"]
15
[{"input": "6 2\r\n5 5 6 8 3 12\r\n", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613\r\n"}, {"input": "1 1\r\n5\r\n", "output": "1\r\n"}, {"input": "5 300\r\n939 465 129 611 532\r\n", "output": "300 667.864105343 1164.9596696 1522.27745533 2117.05388391\r\n"}, {"input": "5 1\r\n416 387 336 116 81\r\n", "output": "1 1 1 1 1\r\n"}, {"input": "3 10\r\n1 100 1000\r\n", "output": "10 10 10\r\n"}, {"input": "2 1\r\n2 20\r\n", "output": "1 1\r\n"}, {"input": "3 2\r\n10 10 100\r\n", "output": "2 6.0 2\r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): with open(input_path) as f: n, r = map(int, f.readline().split()) with open(output_path) as f: ref = list(map(float, f.read().strip().split())) with open(submission_path) as f: sub = list(map(float, f.read().strip().split())) if len(ref) != n or len(sub) != n: print(0) return for a, b in zip(sub, ref): error = abs(a - b) denominator = max(1.0, b) if error / denominator > 1e-6: print(0) return print(1) if __name__ == "__main__": input_path, output_path, submission_path = sys.argv[1:4] main(input_path, output_path, submission_path)
true
908/C
908
C
Python 3
TESTS
6
187
5,632,000
34209980
from math import sqrt def findCollision(x, m, r): j = None for i in range(m): if abs(x[m] - x[i]) <= 2*r: j = i return j n, r = list(map(int, input().rstrip().split())) x = list(map(int, input().rstrip().split())) y = [0 for _ in range(n)] y[0] = r for i in range(1, n): j = findCollision(x, i, r) if j is None: y[i] = r else: y[i] = y[j] + sqrt(4*r*r - (x[i] - x[j])**2) print(' '.join(map(str, y)))
15
109
2,252,800
113142820
import math n, r = [int(x) for x in input().split()] x = [int(x) for x in input().split()] ans = [] for i in range(n): t = r for j in range(i): a = abs(x[i] - x[j]) if a <= 2 * r: t2 = (2 * r)**2 t2 -= a**2 t2 = math.sqrt(t2) + ans[j] t = max(t, t2) ans.append(t) for k in ans: print(k)
Good Bye 2017
CF
2,017
2
256
New Year and Curling
Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if $$\frac{|a-b|}{\max(1,b)} \leq 10^{-6}$$ for all coordinates.
null
The final positions of the disks will look as follows: In particular, note the position of the last disk.
[{"input": "6 2\n5 5 6 8 3 12", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613"}]
1,500
["brute force", "geometry", "implementation", "math"]
15
[{"input": "6 2\r\n5 5 6 8 3 12\r\n", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613\r\n"}, {"input": "1 1\r\n5\r\n", "output": "1\r\n"}, {"input": "5 300\r\n939 465 129 611 532\r\n", "output": "300 667.864105343 1164.9596696 1522.27745533 2117.05388391\r\n"}, {"input": "5 1\r\n416 387 336 116 81\r\n", "output": "1 1 1 1 1\r\n"}, {"input": "3 10\r\n1 100 1000\r\n", "output": "10 10 10\r\n"}, {"input": "2 1\r\n2 20\r\n", "output": "1 1\r\n"}, {"input": "3 2\r\n10 10 100\r\n", "output": "2 6.0 2\r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): with open(input_path) as f: n, r = map(int, f.readline().split()) with open(output_path) as f: ref = list(map(float, f.read().strip().split())) with open(submission_path) as f: sub = list(map(float, f.read().strip().split())) if len(ref) != n or len(sub) != n: print(0) return for a, b in zip(sub, ref): error = abs(a - b) denominator = max(1.0, b) if error / denominator > 1e-6: print(0) return print(1) if __name__ == "__main__": input_path, output_path, submission_path = sys.argv[1:4] main(input_path, output_path, submission_path)
true
845/D
845
D
Python 3
TESTS
7
530
5,632,000
34958708
events = int(input()) speed = -1 limitSigns = [] overtake = True noOvertakeSigns = 0 signs = 0 for i in range(events): l = input().split(" ") e_type = int(l[0]) if e_type == 1: speed = int(l[1]) newLimSigns = [] for i in limitSigns: if speed > i: signs += 1 else: newLimSigns.append(i) limitSigns = newLimSigns if e_type == 2: if not overtake: signs += noOvertakeSigns noOvertakeSigns = 0 if e_type == 3: limit = int(l[1]) if speed > limit: signs += 1 else: limitSigns.append(limit) if e_type == 4: overtake = True noOvertakeSigns = 0 if e_type == 5: limitSigns = [] if e_type == 6: overtake = False noOvertakeSigns += 1 print(signs)
25
436
6,963,200
129905274
n = int(input()) v = int(input()[2:]) p = [1e9] d = k = 0 for i in range(n - 1): s = input() t = int(s[0]) if t == 1: v = int(s[2:]) while p[-1] < v: p.pop() k += 1 if t == 2: k += d d = 0 if t == 3: u = int(s[2:]) if v > u: k += 1 else: p.append(u) if t == 4: d = 0 if t == 5: p = [1e9] if t == 6: d += 1 print(k)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
845/D
845
D
PyPy 3
TESTS
7
1,435
7,270,400
118584644
n = int(input()) speed = 0 speed_limits = [] overtake = 0 ignore = 0 for i in range(n): event = list(input().split()) if (len(event) == 2): # 1 изменил скорость на х if int(event[0]) == 1: speed = int(event[1]) # speed = 100 # speed_limits = [90, 80, 120] # speed_limits = [120, 90, 80] for i in speed_limits[::-1]: if i < speed: ignore += 1 speed_limits.remove(i) # while len(speed_limits) > 0 and speed_limits[-1] < speed: # ignore += 1 # speed_limits.pop() # 3 новый знак ограничение скорости х else: if int(event[1]) < speed: ignore += 1 else: speed_limits.append(int(event[1])) else: # 2 совершил обгон if int(event[0]) == 2: ignore += overtake overtake = 0 # 4 новый знак обгон разрешен elif int(event[0]) == 4: overtake = 0 # 5 новый знак отмена ограничения скорости elif int(event[0]) == 5: speed_limits = [] else: # 6 новый знак обгон запрещен overtake += 1 print(ignore)
25
561
1,945,600
29760687
#!/usr/bin/env python3 from sys import stdin, stdout from math import inf def rint(): return map(int, stdin.readline().split()) #lines = stdin.readlines() csp = 0 ov = 1 sign = [] ans = 0 spst = [inf] ovst = [1] n = int(input()) for i in range(n): sign = list(rint()) if sign[0] == 1: csp = sign[1] while csp > spst[-1]: spst.pop() ans += 1 if sign[0] == 2: while ovst[-1] == 0: ovst.pop() ans += 1 if sign[0] == 3: if sign[1] >= csp: spst.append(sign[1]) else: ans += 1 if sign[0] == 4: ovst.append(1) if sign[0] == 5: spst.append(inf) if sign[0] == 6: ovst.append(0) print(ans)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
437/C
437
C
PyPy 3
TESTS
11
218
35,020,800
80060094
n,m=map(int,input().split()) from collections import defaultdict v=[0]*(n+1) adj=[] for i in range(n+1): adj.append([]) l=list(map(int,input().split())) d=defaultdict(list) for i in range(m): x,y=map(int,input().split()) adj[x].append(y) adj[y].append(x) d[x]=[0]*(n+1) d[y]=[0]*(n+1) ans=0 def dfs(x): global ans v[x]=1 for i in adj[x]: if not v[i]: ans+=min(l[i-1],l[x-1]) d[x][i]=1 d[i][x]=1 dfs(i) else: if d[x][i]==0: ans+=min(l[i-1],l[x-1]) d[x][i]=1 d[i][x]=1 dfs(1) print(ans)
29
46
0
9571314
def main(): n, m = map(int, input().split()) vv = list(map(int, input().split())) print(sum(min(vv[i - 1] for i in map(int, input().split())) for _ in range(m))) if __name__ == '__main__': main()
Codeforces Round 250 (Div. 2)
CF
2,014
1
256
The Child and Toy
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed. Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.
Output the minimum total energy the child should spend to remove all n parts of the toy.
null
One of the optimal sequence of actions in the first sample is: - First, remove part 3, cost of the action is 20. - Then, remove part 2, cost of the action is 10. - Next, remove part 4, cost of the action is 10. - At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum. In the second sample, the child will spend 400 no matter in what order he will remove the parts.
[{"input": "4 3\n10 20 30 40\n1 4\n1 2\n2 3", "output": "40"}, {"input": "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4", "output": "400"}, {"input": "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4", "output": "160"}]
1,400
["graphs", "greedy", "sortings"]
29
[{"input": "4 3\r\n10 20 30 40\r\n1 4\r\n1 2\r\n2 3\r\n", "output": "40\r\n"}, {"input": "4 4\r\n100 100 100 100\r\n1 2\r\n2 3\r\n2 4\r\n3 4\r\n", "output": "400\r\n"}, {"input": "7 10\r\n40 10 20 10 20 80 40\r\n1 5\r\n4 7\r\n4 5\r\n5 2\r\n5 7\r\n6 4\r\n1 6\r\n1 3\r\n4 3\r\n1 4\r\n", "output": "160\r\n"}, {"input": "1 0\r\n23333\r\n", "output": "0\r\n"}, {"input": "5 4\r\n1 2 2 2 2\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "4\r\n"}, {"input": "10 30\r\n3 6 17 15 13 15 6 12 9 1\r\n3 8\r\n1 10\r\n4 7\r\n1 7\r\n3 7\r\n2 9\r\n8 10\r\n3 1\r\n3 4\r\n8 6\r\n10 3\r\n3 9\r\n2 3\r\n10 4\r\n2 10\r\n5 8\r\n9 5\r\n6 1\r\n2 1\r\n7 2\r\n7 6\r\n7 10\r\n4 8\r\n5 6\r\n3 6\r\n4 1\r\n8 9\r\n7 9\r\n4 2\r\n5 10\r\n", "output": "188\r\n"}, {"input": "3 3\r\n1 1 1\r\n1 2\r\n2 3\r\n3 1\r\n", "output": "3\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
218
6,656,000
87448835
a=' ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17' t=[] for _ in range(int(input())): t.append(input()) c=0 for i in t: if i in a: c+=1 print(c)
28
92
0
19541949
def main(): x = 0 for _ in range(int(input())): s = input() try: x += int(s) < 18 except ValueError: x += s in {"ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"} print(x) if __name__ == '__main__': main()
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
186
307,200
94508715
n=int(input('')) l=['BSINTH','BEER','BRANDY','CHAMPAGNE','GIN','RUM','SAKE','TEQUILA','VODKA','WHISKEY','WINE'] l1=['1','2','3','4','5','6','7','8','9','0'] count=0 for i in range(n): s=input('') if(s in l): # print('if2') count+=1 if(s[0] in l1): temp=int(s) if(temp<18): count+=1 print(count)
28
92
0
136646740
#!/usr/bin/env python # coding=utf-8 ''' Author: Deean Date: 2021-11-23 23:14:03 LastEditTime: 2021-11-23 23:20:43 Description: Bar FilePath: CF56A.py ''' def func(): n = int(input()) alcohol = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"] count = 0 for _ in range(n): visitor = input().strip() if visitor.isdigit(): if int(visitor) < 18: count += 1 else: if visitor in alcohol: count += 1 print(count) if __name__ == '__main__': func()
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
56/A
56
A
Python 3
TESTS
7
186
6,656,000
87487643
a=' ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE' t=[] for _ in range(int(input())): t.append(input()) c=0 for i in t: if i in a or(i.isdigit() and int(i)<18): c+=1 print(c)
28
92
0
136820267
a = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA','WHISKEY', 'WINE'] ans = 0 for i in range(int(input())): s = input() if s.isdigit(): if int(s) < 18: ans += 1 if s in a: ans += 1 print(ans)
Codeforces Beta Round 52 (Div. 2)
CF
2,011
2
256
Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
null
In the sample test the second and fifth clients should be checked.
[{"input": "5\n18\nVODKA\nCOKE\n19\n17", "output": "2"}]
1,000
["implementation"]
28
[{"input": "5\r\n18\r\nVODKA\r\nCOKE\r\n19\r\n17\r\n", "output": "2\r\n"}, {"input": "2\r\n2\r\nGIN\r\n", "output": "2\r\n"}, {"input": "3\r\nWHISKEY\r\n3\r\nGIN\r\n", "output": "3\r\n"}, {"input": "4\r\n813\r\nIORBQITQXMPTFAEMEQDQIKFGKGOTNKTOSZCBRPXJLUKVLVHJYNRUJXK\r\nRUM\r\nRHVRWGODYWWTYZFLFYKCVUFFRTQDINKNWPKFHZBFWBHWINWJW\r\n", "output": "1\r\n"}, {"input": "4\r\nSAKE\r\nSAKE\r\n13\r\n2\r\n", "output": "4\r\n"}, {"input": "2\r\n0\r\n17\r\n", "output": "2\r\n"}, {"input": "1\r\n0\r\n", "output": "1\r\n"}]
false
stdio
null
true
15/C
15
C
Python 3
TESTS
5
184
307,200
99391747
n = int(input()) ans = 0 for _ in range(n): x,m = map(int, input().split()) if x % 4 == 1: ans ^= ((x - 1) ^ (x + 3)) * ((m >> 2) & 1) elif x % 4 == 3: ans ^= ((x - 3) ^ (x + 1)) * ((m >> 2) & 1) # x % 4 == 0 ans ^= 0 * ((m >> 2) &1) # x % 4 == 2 ans ^= 0 * ((m >> 2) &1) for i in range(1, (m % 4) + 1): ans ^= (x + m - i) if ans == 0: print("bolik") else: print("tolik")
25
248
4,505,600
211220136
import sys N = int(sys.stdin.readline().split()[0]) def ff(a: int) -> int: return [0, a - 1, 1, a][a & 3] result = 0 for _ in range(N): x, m = tuple(map(int, sys.stdin.readline().split())) result ^= ff(x) ^ ff(x + m) if result == 0: print('bolik') else: print('tolik')
Codeforces Beta Round 15
ICPC
2,010
2
64
Industrial Nim
There are n stone quarries in Petrograd. Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it. Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses. Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik».
The first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.
Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise.
null
null
[{"input": "2\n2 1\n3 2", "output": "tolik"}, {"input": "4\n1 1\n1 1\n1 1\n1 1", "output": "bolik"}]
2,000
["games"]
25
[{"input": "2\r\n2 1\r\n3 2\r\n", "output": "tolik\r\n"}, {"input": "4\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n", "output": "bolik\r\n"}, {"input": "10\r\n2 3\r\n1 4\r\n5 8\r\n4 10\r\n10 8\r\n7 2\r\n1 2\r\n1 7\r\n4 10\r\n5 3\r\n", "output": "tolik\r\n"}, {"input": "20\r\n8 6\r\n6 3\r\n2 9\r\n7 8\r\n9 1\r\n2 4\r\n3 6\r\n6 3\r\n5 6\r\n5 3\r\n6 5\r\n2 10\r\n2 9\r\n6 3\r\n10 6\r\n10 10\r\n10 7\r\n3 9\r\n16 1\r\n1 3\r\n", "output": "bolik\r\n"}, {"input": "30\r\n53 12\r\n13 98\r\n21 60\r\n76 58\r\n39 5\r\n62 58\r\n73 80\r\n13 75\r\n37 45\r\n44 86\r\n1 85\r\n13 33\r\n17 50\r\n12 26\r\n97 48\r\n52 40\r\n2 71\r\n95 79\r\n38 76\r\n24 54\r\n91 39\r\n97 92\r\n94 80\r\n50 61\r\n33 56\r\n22 91\r\n39 94\r\n31 56\r\n28 16\r\n20 44\r\n", "output": "tolik\r\n"}, {"input": "1\r\n3737203222172202 1\r\n", "output": "tolik\r\n"}, {"input": "1\r\n3737203222172202 1\r\n", "output": "tolik\r\n"}]
false
stdio
null
true
908/C
908
C
Python 3
TESTS
6
46
5,734,400
33794813
import math n,r=map(int,input().split()) x=list(map(int,input().split())) y=[r] def collision(t,a): for i in range(len(t)-1,-1,-1): if (a<=t[i]+2*r and a>=t[i]-2*r): if t[i]==a: return y[i]+2*r else: return(y[i]+2*r*math.sqrt(1-(((a-t[i])**2)/(4*r**2)))) return r for j in range(1,n): y.append(collision(x[0:j],x[j])) for i in y: print(i,end=" ")
15
109
3,891,200
159928880
import math def getDy(r, dx): if 4 * r * r - dx * dx < 0: return None return math.sqrt(4 * r * r - dx * dx) n, r = map(int, input().split(" ")) xs = [int(x) for x in input().split(" ")] disks = [] for x in xs: highestY = -1 for disk in disks: if disk["x"] - 2 * r <= x <= disk["x"] + 2 * r: dy = getDy(r, abs(disk["x"] - x)) if dy is not None: highestY = max(highestY, disk["y"] + dy) if highestY == -1: disks.append({ "x": x, "y": r }) else: disks.append({ "x": x, "y": highestY }) print(" ".join([str(disk["y"]) for disk in disks]))
Good Bye 2017
CF
2,017
2
256
New Year and Curling
Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if $$\frac{|a-b|}{\max(1,b)} \leq 10^{-6}$$ for all coordinates.
null
The final positions of the disks will look as follows: In particular, note the position of the last disk.
[{"input": "6 2\n5 5 6 8 3 12", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613"}]
1,500
["brute force", "geometry", "implementation", "math"]
15
[{"input": "6 2\r\n5 5 6 8 3 12\r\n", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613\r\n"}, {"input": "1 1\r\n5\r\n", "output": "1\r\n"}, {"input": "5 300\r\n939 465 129 611 532\r\n", "output": "300 667.864105343 1164.9596696 1522.27745533 2117.05388391\r\n"}, {"input": "5 1\r\n416 387 336 116 81\r\n", "output": "1 1 1 1 1\r\n"}, {"input": "3 10\r\n1 100 1000\r\n", "output": "10 10 10\r\n"}, {"input": "2 1\r\n2 20\r\n", "output": "1 1\r\n"}, {"input": "3 2\r\n10 10 100\r\n", "output": "2 6.0 2\r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): with open(input_path) as f: n, r = map(int, f.readline().split()) with open(output_path) as f: ref = list(map(float, f.read().strip().split())) with open(submission_path) as f: sub = list(map(float, f.read().strip().split())) if len(ref) != n or len(sub) != n: print(0) return for a, b in zip(sub, ref): error = abs(a - b) denominator = max(1.0, b) if error / denominator > 1e-6: print(0) return print(1) if __name__ == "__main__": input_path, output_path, submission_path = sys.argv[1:4] main(input_path, output_path, submission_path)
true
908/C
908
C
PyPy 3
TESTS
6
155
1,638,400
75567682
n,r=map(int,input().split()) l=list(map(int,input().split())) ans=[] ans.append(r) le=1 for i in range(1,n): f=0 cal=0 for j in range(le,0,-1): if l[i]>=l[j-1]-2*r and l[i]<=l[j-1]+2*r: cal=((4*(r**2))-((abs(l[j-1]-l[i]))**2))**0.5 cal+=ans[j-1] ans.append(cal) f=1 if f==1: break if f==0: ans.append(r) le+=1 for i in ans: print(i,end=" ")
15
109
4,096,000
172994870
n,r=map(int,input().split()) y=[] x=list(map(int,input().split())) for xi in x: yi=r for tx,ty in zip(x,y): if xi-2*r<=tx<=xi+2*r: dy=(4.0*r**2-(tx-xi)**2)**0.5 yi=max(yi,ty+dy) y.append(yi) print(*y) '''def ycor(a,b,x,r): return b+(4.0*r**2-(x-a)**2)**0.5 n,r=map(int,input().split()) c=list(map(int,input().split())) a=[] for i in range(n): x=c[i] var=[-1,-1,-1] if len(a)>0: for j in a: if x-(2*r)<=j[0]<=x+(2*r): y=ycor(j[0],j[1],x,r) inter=(y+j[1])/2 #We are choosing the maximum value for y coordinate of falling circle. We are not choosing maximum value of y coordinate of already fallen circles( obviously only those circles are considered which have potential to touch currently falling circle). If intersection point of falling circle with some circle is higher than intersection point with some other circle, then y coordinate of falling circle will be higher for the higher intersection one. Easy visualization. if inter>var[0]: var[0]=inter var[1]=x var[2]=y if var[0]==-1: a.append([x,r]) else: a.append([var[1],var[2]]) s="" l=len(a) y=[] for i in a: y.append(i[1]) print(*y)'''
Good Bye 2017
CF
2,017
2
256
New Year and Curling
Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if $$\frac{|a-b|}{\max(1,b)} \leq 10^{-6}$$ for all coordinates.
null
The final positions of the disks will look as follows: In particular, note the position of the last disk.
[{"input": "6 2\n5 5 6 8 3 12", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613"}]
1,500
["brute force", "geometry", "implementation", "math"]
15
[{"input": "6 2\r\n5 5 6 8 3 12\r\n", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613\r\n"}, {"input": "1 1\r\n5\r\n", "output": "1\r\n"}, {"input": "5 300\r\n939 465 129 611 532\r\n", "output": "300 667.864105343 1164.9596696 1522.27745533 2117.05388391\r\n"}, {"input": "5 1\r\n416 387 336 116 81\r\n", "output": "1 1 1 1 1\r\n"}, {"input": "3 10\r\n1 100 1000\r\n", "output": "10 10 10\r\n"}, {"input": "2 1\r\n2 20\r\n", "output": "1 1\r\n"}, {"input": "3 2\r\n10 10 100\r\n", "output": "2 6.0 2\r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): with open(input_path) as f: n, r = map(int, f.readline().split()) with open(output_path) as f: ref = list(map(float, f.read().strip().split())) with open(submission_path) as f: sub = list(map(float, f.read().strip().split())) if len(ref) != n or len(sub) != n: print(0) return for a, b in zip(sub, ref): error = abs(a - b) denominator = max(1.0, b) if error / denominator > 1e-6: print(0) return print(1) if __name__ == "__main__": input_path, output_path, submission_path = sys.argv[1:4] main(input_path, output_path, submission_path)
true
908/C
908
C
PyPy 3
TESTS
6
155
1,843,200
75558255
import math def gety(x, y, x1): return (abs(y + math.sqrt(d**2 - (x-x1)**2))) n, r = map(int, input().split()) x = list(map(int, input().split())) y = [r] d = 2*r center = [[x[0], r]] for i in range(1, n): # print(center) c = [] c_temp = list(reversed(center)) for item in c_temp: if abs(item[0]-x[i])<=d: c = item break # print(x[i], "c:", c, "Center: ", center) if len(c)==0: y1 = r else: y1 = gety(c[0], c[1], x[i]) center.append([x[i], y1]) y.append(y1) print(*y)
15
124
3,993,600
202138117
import sys input = lambda: sys.stdin.readline().rstrip() N,R = map(int, input().split()) A = list(map(int, input().split())) side = (R+R)**2 ans=[] for a in A: pre = (a,-R) y1 = R for x,y in ans: if abs(a-x)<=2*R: t = abs(a-x)**2 height = (side-t)**0.5+y y1 = max(y1,height) ans.append((a,y1)) print(*[y for x,y in ans])
Good Bye 2017
CF
2,017
2
256
New Year and Curling
Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if $$\frac{|a-b|}{\max(1,b)} \leq 10^{-6}$$ for all coordinates.
null
The final positions of the disks will look as follows: In particular, note the position of the last disk.
[{"input": "6 2\n5 5 6 8 3 12", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613"}]
1,500
["brute force", "geometry", "implementation", "math"]
15
[{"input": "6 2\r\n5 5 6 8 3 12\r\n", "output": "2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613\r\n"}, {"input": "1 1\r\n5\r\n", "output": "1\r\n"}, {"input": "5 300\r\n939 465 129 611 532\r\n", "output": "300 667.864105343 1164.9596696 1522.27745533 2117.05388391\r\n"}, {"input": "5 1\r\n416 387 336 116 81\r\n", "output": "1 1 1 1 1\r\n"}, {"input": "3 10\r\n1 100 1000\r\n", "output": "10 10 10\r\n"}, {"input": "2 1\r\n2 20\r\n", "output": "1 1\r\n"}, {"input": "3 2\r\n10 10 100\r\n", "output": "2 6.0 2\r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): with open(input_path) as f: n, r = map(int, f.readline().split()) with open(output_path) as f: ref = list(map(float, f.read().strip().split())) with open(submission_path) as f: sub = list(map(float, f.read().strip().split())) if len(ref) != n or len(sub) != n: print(0) return for a, b in zip(sub, ref): error = abs(a - b) denominator = max(1.0, b) if error / denominator > 1e-6: print(0) return print(1) if __name__ == "__main__": input_path, output_path, submission_path = sys.argv[1:4] main(input_path, output_path, submission_path)
true
845/D
845
D
Python 3
TESTS
7
499
0
118584682
n = int(input()) speed = 0 speed_limits = [] overtake = 0 ignore = 0 for i in range(n): event = list(input().split()) if (len(event) == 2): if int(event[0]) == 1: speed = int(event[1]) for i in speed_limits[::-1]: if i < speed: ignore += 1 speed_limits.remove(i) else: if int(event[1]) < speed: ignore += 1 else: speed_limits.append(int(event[1])) else: if int(event[0]) == 2: ignore += overtake overtake = 0 elif int(event[0]) == 4: overtake = 0 elif int(event[0]) == 5: speed_limits = [] else: overtake += 1 print(ignore)
25
608
1,536,000
118281683
n = int(input()) speed_limits = [] obgon = 0 current_speed = 0 count = 0 for i in range(n): event = list(input().split()) if (len(event) == 2): type, x = map(int, event) if type == 1: # 1 изменил скорость на х current_speed = x while len(speed_limits) != 0 and speed_limits[-1] < current_speed: count += 1 speed_limits.pop() elif type == 3: # 3 новый знак ограничение скорости х speed_limits.append(x) if speed_limits[-1] < current_speed: count += 1 speed_limits.pop() else: type = int(event[0]) if type == 2: # 2 совершил обгон if obgon == 0: continue else: count += obgon obgon = 0 elif type == 4: # 4 новый знак обгон разрешен obgon = 0 elif type == 5: # 5 новый знак отмена ограничения скорости speed_limits.clear() elif type == 6: # 6 новый знак обгон запрещен obgon += 1 print(count)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
437/C
437
C
PyPy 3
TESTS
5
155
1,331,200
118749349
import sys, heapq def answer(n, m, v, x, y): adj_list = [[] for _ in range(n+1)] # No node 0. Nodes 1-n visited = [False for _ in range(n+1)] #Do I need this? for i in range(m): adj_list[x[i]].append(y[i]) adj_list[y[i]].append(x[i]) total = 0 for _ in range(n): mx = 0 for node in range(1, n+1): if v[node] > mx: mx = v[node] maddr = node if mx == 0: break for cnode in adj_list[maddr]: total += v[cnode] adj_list[cnode].remove(maddr) v[maddr] = 0 adj_list[maddr] = [] return total def main(): n, m = map(int, sys.stdin.readline().split()) v = [0] v.extend(list(map(int, sys.stdin.readline().split()))) x = [0 for _ in range(m)] y = [0 for _ in range(m)] for i in range(m): x[i], y[i] = map(int, sys.stdin.readline().split()) print(answer(n, m, v, x, y)) return main()
29
46
0
138345955
n,m = map(int, input().split()) ind = list(map(int,input().split())) s = 0 for e in range(m): f,ff = map(int,input().split()) s += min(ind[f-1], ind[ff-1]) print(s)
Codeforces Round 250 (Div. 2)
CF
2,014
1
256
The Child and Toy
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed. Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.
Output the minimum total energy the child should spend to remove all n parts of the toy.
null
One of the optimal sequence of actions in the first sample is: - First, remove part 3, cost of the action is 20. - Then, remove part 2, cost of the action is 10. - Next, remove part 4, cost of the action is 10. - At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum. In the second sample, the child will spend 400 no matter in what order he will remove the parts.
[{"input": "4 3\n10 20 30 40\n1 4\n1 2\n2 3", "output": "40"}, {"input": "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4", "output": "400"}, {"input": "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4", "output": "160"}]
1,400
["graphs", "greedy", "sortings"]
29
[{"input": "4 3\r\n10 20 30 40\r\n1 4\r\n1 2\r\n2 3\r\n", "output": "40\r\n"}, {"input": "4 4\r\n100 100 100 100\r\n1 2\r\n2 3\r\n2 4\r\n3 4\r\n", "output": "400\r\n"}, {"input": "7 10\r\n40 10 20 10 20 80 40\r\n1 5\r\n4 7\r\n4 5\r\n5 2\r\n5 7\r\n6 4\r\n1 6\r\n1 3\r\n4 3\r\n1 4\r\n", "output": "160\r\n"}, {"input": "1 0\r\n23333\r\n", "output": "0\r\n"}, {"input": "5 4\r\n1 2 2 2 2\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n", "output": "4\r\n"}, {"input": "10 30\r\n3 6 17 15 13 15 6 12 9 1\r\n3 8\r\n1 10\r\n4 7\r\n1 7\r\n3 7\r\n2 9\r\n8 10\r\n3 1\r\n3 4\r\n8 6\r\n10 3\r\n3 9\r\n2 3\r\n10 4\r\n2 10\r\n5 8\r\n9 5\r\n6 1\r\n2 1\r\n7 2\r\n7 6\r\n7 10\r\n4 8\r\n5 6\r\n3 6\r\n4 1\r\n8 9\r\n7 9\r\n4 2\r\n5 10\r\n", "output": "188\r\n"}, {"input": "3 3\r\n1 1 1\r\n1 2\r\n2 3\r\n3 1\r\n", "output": "3\r\n"}]
false
stdio
null
true
845/D
845
D
Python 3
TESTS
7
639
0
29659641
n = int(input()) p = 0 speed = -1 speed_limit = float('inf') overtaking = True overtaking_number = 0 speed_limit_number = 0 for _ in range(n): event = list(map(int, input().split())) type = event[0] if type == 1: speed = event[1] if speed > speed_limit: p += speed_limit_number speed_limit_number = 0 elif type == 2: if not overtaking: p += overtaking_number overtaking_number = 0 elif type == 3: if event[1] <= speed_limit: speed_limit_number += 1 else: speed_limit_number = 0 speed_limit = event[1] if speed > speed_limit: p += speed_limit_number speed_limit_number = 0 elif type == 4: overtaking = True overtaking_number = 0 elif type == 5: speed_limit = float('inf') speed_limit_number = 0 elif type == 6: overtaking = False overtaking_number += 1 print(p)
25
764
6,758,400
32743715
import collections n=int(input()) x,v=map(int,input().split()) o=collections.deque() q=0 k=0 for i in range(1,n): s=input() if s[0]=='1': x,v=map(int,s.split()) while len(o)>0 and o[-1]<v: o.pop() k+=1 if s[0]=='2': k+=q q=0 if s[0]=='3': x,y=map(int,s.split()) if v<=y: o.append(y) else: k+=1 if s[0]=='4': q=0 if s[0]=='5': o.clear() if s[0]=='6': q+=1 print(k)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true
2/A
2
A
Python 3
TESTS
13
62
0
210743804
dic={} w="" for i in range(int(input())): a=input().split(" ") dic[a[0]]=dic.get(a[0],0)+int(a[1]) if w=="": w=a[0] elif dic[a[0]]>dic[w]: w=a[0] print(w)
20
62
102,400
216989408
# LUOGU_RID: 118873789 n, k, s = eval(input()), {}, [] for i in range(n): a, b = input().split(' ');k[a] = k.get(a, 0) + int(b);s.append([a, k[a]]) n = max(k.values()) for i, j in s: if k[i] == n and int(j) >= n: print(i);break
Codeforces Beta Round 2
ICPC
2,010
1
64
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Print the name of the winner.
null
null
[{"input": "3\nmike 3\nandrew 5\nmike 2", "output": "andrew"}, {"input": "3\nandrew 3\nandrew 2\nmike 5", "output": "andrew"}]
1,500
["hashing", "implementation"]
20
[{"input": "3\r\nmike 3\r\nandrew 5\r\nmike 2\r\n", "output": "andrew\r\n"}, {"input": "3\r\nandrew 3\r\nandrew 2\r\nmike 5\r\n", "output": "andrew\r\n"}, {"input": "5\r\nkaxqybeultn -352\r\nmgochgrmeyieyskhuourfg -910\r\nkaxqybeultn 691\r\nmgochgrmeyieyskhuourfg -76\r\nkaxqybeultn -303\r\n", "output": "kaxqybeultn\r\n"}, {"input": "7\r\nksjuuerbnlklcfdjeyq 312\r\ndthjlkrvvbyahttifpdewvyslsh -983\r\nksjuuerbnlklcfdjeyq 268\r\ndthjlkrvvbyahttifpdewvyslsh 788\r\nksjuuerbnlklcfdjeyq -79\r\nksjuuerbnlklcfdjeyq -593\r\nksjuuerbnlklcfdjeyq 734\r\n", "output": "ksjuuerbnlklcfdjeyq\r\n"}, {"input": "12\r\natrtthfpcvishmqbakprquvnejr 185\r\natrtthfpcvishmqbakprquvnejr -699\r\natrtthfpcvishmqbakprquvnejr -911\r\natrtthfpcvishmqbakprquvnejr -220\r\nfcgslzkicjrpbqaifgweyzreajjfdo 132\r\nfcgslzkicjrpbqaifgweyzreajjfdo -242\r\nm 177\r\nm -549\r\natrtthfpcvishmqbakprquvnejr -242\r\nm 38\r\natrtthfpcvishmqbakprquvnejr -761\r\nfcgslzkicjrpbqaifgweyzreajjfdo 879\r\n", "output": "fcgslzkicjrpbqaifgweyzreajjfdo\r\n"}, {"input": "15\r\naawtvezfntstrcpgbzjbf 681\r\nzhahpvqiptvksnbjkdvmknb -74\r\naawtvezfntstrcpgbzjbf 661\r\njpdwmyke 474\r\naawtvezfntstrcpgbzjbf -547\r\naawtvezfntstrcpgbzjbf 600\r\nzhahpvqiptvksnbjkdvmknb -11\r\njpdwmyke 711\r\nbjmj 652\r\naawtvezfntstrcpgbzjbf -1000\r\naawtvezfntstrcpgbzjbf -171\r\nbjmj -302\r\naawtvezfntstrcpgbzjbf 961\r\nzhahpvqiptvksnbjkdvmknb 848\r\nbjmj -735\r\n", "output": "aawtvezfntstrcpgbzjbf\r\n"}, {"input": "17\r\nqdplghhx -649\r\nivhgbxiv 424\r\nivhgbxiv -72\r\nivhgbxiv 479\r\nugowfouebkelargxylsxn 83\r\nugowfouebkelargxylsxn -840\r\nivhgbxiv 382\r\nqdplghhx -904\r\nivhgbxiv -710\r\nugowfouebkelargxylsxn -838\r\nqdplghhx -974\r\nqdplghhx 571\r\nivhgbxiv -145\r\nugowfouebkelargxylsxn -788\r\nivhgbxiv 209\r\nivhgbxiv 420\r\nqdplghhx -158\r\n", "output": "ivhgbxiv\r\n"}]
false
stdio
null
true
2/A
2
A
Python 3
TESTS
14
248
307,200
73384445
n = int(input()) names = [] scores = [] for i in range(0, n): name, score = input().split() names.append(name) scores.append(int(score)) # print(names, scores) d = {} for i in range(0, n): name = names[i] score = scores[i] if name not in d: d[name] = [score, [score], [i]] else: d[name][0] = d[name][0] + score d[name][1].append(d[name][0] + score) d[name][2].append(i) maxScore = 0 for k, v in d.items(): if v[0] > maxScore: maxScore = v[0] maxName = "" maxTime = n for k, v in d.items(): # print(k, v) if v[0] == maxScore: for idx in range(0, len(v[1])): s = v[1][idx] t = v[2][idx] if s >= maxScore and t < maxTime: maxName = k maxTime = t print(maxName)
20
62
102,400
218372588
d = {} b = [] for _ in range(int(input())): name,score = input().split() if name not in d: d[name] = 0 d[name] += int(score) b.append((name,d[name])) m = max(d.values()) for name, score in b: if d[name]==m and score>=m: print(name) break
Codeforces Beta Round 2
ICPC
2,010
1
64
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Print the name of the winner.
null
null
[{"input": "3\nmike 3\nandrew 5\nmike 2", "output": "andrew"}, {"input": "3\nandrew 3\nandrew 2\nmike 5", "output": "andrew"}]
1,500
["hashing", "implementation"]
20
[{"input": "3\r\nmike 3\r\nandrew 5\r\nmike 2\r\n", "output": "andrew\r\n"}, {"input": "3\r\nandrew 3\r\nandrew 2\r\nmike 5\r\n", "output": "andrew\r\n"}, {"input": "5\r\nkaxqybeultn -352\r\nmgochgrmeyieyskhuourfg -910\r\nkaxqybeultn 691\r\nmgochgrmeyieyskhuourfg -76\r\nkaxqybeultn -303\r\n", "output": "kaxqybeultn\r\n"}, {"input": "7\r\nksjuuerbnlklcfdjeyq 312\r\ndthjlkrvvbyahttifpdewvyslsh -983\r\nksjuuerbnlklcfdjeyq 268\r\ndthjlkrvvbyahttifpdewvyslsh 788\r\nksjuuerbnlklcfdjeyq -79\r\nksjuuerbnlklcfdjeyq -593\r\nksjuuerbnlklcfdjeyq 734\r\n", "output": "ksjuuerbnlklcfdjeyq\r\n"}, {"input": "12\r\natrtthfpcvishmqbakprquvnejr 185\r\natrtthfpcvishmqbakprquvnejr -699\r\natrtthfpcvishmqbakprquvnejr -911\r\natrtthfpcvishmqbakprquvnejr -220\r\nfcgslzkicjrpbqaifgweyzreajjfdo 132\r\nfcgslzkicjrpbqaifgweyzreajjfdo -242\r\nm 177\r\nm -549\r\natrtthfpcvishmqbakprquvnejr -242\r\nm 38\r\natrtthfpcvishmqbakprquvnejr -761\r\nfcgslzkicjrpbqaifgweyzreajjfdo 879\r\n", "output": "fcgslzkicjrpbqaifgweyzreajjfdo\r\n"}, {"input": "15\r\naawtvezfntstrcpgbzjbf 681\r\nzhahpvqiptvksnbjkdvmknb -74\r\naawtvezfntstrcpgbzjbf 661\r\njpdwmyke 474\r\naawtvezfntstrcpgbzjbf -547\r\naawtvezfntstrcpgbzjbf 600\r\nzhahpvqiptvksnbjkdvmknb -11\r\njpdwmyke 711\r\nbjmj 652\r\naawtvezfntstrcpgbzjbf -1000\r\naawtvezfntstrcpgbzjbf -171\r\nbjmj -302\r\naawtvezfntstrcpgbzjbf 961\r\nzhahpvqiptvksnbjkdvmknb 848\r\nbjmj -735\r\n", "output": "aawtvezfntstrcpgbzjbf\r\n"}, {"input": "17\r\nqdplghhx -649\r\nivhgbxiv 424\r\nivhgbxiv -72\r\nivhgbxiv 479\r\nugowfouebkelargxylsxn 83\r\nugowfouebkelargxylsxn -840\r\nivhgbxiv 382\r\nqdplghhx -904\r\nivhgbxiv -710\r\nugowfouebkelargxylsxn -838\r\nqdplghhx -974\r\nqdplghhx 571\r\nivhgbxiv -145\r\nugowfouebkelargxylsxn -788\r\nivhgbxiv 209\r\nivhgbxiv 420\r\nqdplghhx -158\r\n", "output": "ivhgbxiv\r\n"}]
false
stdio
null
true
845/D
845
D
Python 3
TESTS
7
654
0
30130706
def Task485D(): cur_speed = 0 is_outstrip = 0 err_count = 0 event_speed_limit = [] event_count = int(input()) for a in range(event_count): ev =list(map(int, input().split())) if ev[0] == 1: cur_speed = ev[1] err_count = err_count + len(event_speed_limit) event_speed_limit = [ev for ev in event_speed_limit if ev[1] > cur_speed] err_count = err_count - len(event_speed_limit) if ev[0] == 2: err_count += is_outstrip is_outstrip = 0 if ev[0] == 3: if cur_speed > ev[1]: err_count += 1 else: event_speed_limit.append(ev) if ev[0] == 4: is_outstrip = 0 if ev[0] == 5: event_speed_limit.clear() if ev[0] == 6: is_outstrip += 1 print(err_count) if __name__ == '__main__': Task485D()
25
811
716,800
32199123
n=int(input()) st=[0]*n top=-1 curr_speed=0 ans=0 c=0 while(n>0): n-=1 a=list(map(int,input().split())) if(a[0]==1): curr_speed=a[1] if(top>=0 and curr_speed>st[top]): while(curr_speed>st[top] and top>=0): top-=1 ans+=1 if(a[0]==4): c=0 elif(a[0]==6): c+=1 if(a[0]==5): top=-1 if(a[0]==2): ans+=c c=0 if(a[0]==3): if(curr_speed>a[1]): ans+=1 else: st[top+1]=a[1] top+=1 print(ans)
Educational Codeforces Round 27
ICPC
2,017
2
256
Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. - speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); - overtake is allowed: this sign means that after some car meets it, it can overtake any other car; - no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); - no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well. In the beginning of the ride overtake is allowed and there is no speed limit. You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types: 1. Polycarp changes the speed of his car to specified (this event comes with a positive integer number); 2. Polycarp's car overtakes the other car; 3. Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer); 4. Polycarp's car goes past the "overtake is allowed" sign; 5. Polycarp's car goes past the "no speed limit"; 6. Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified). After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?
The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).
Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.
null
In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120. In the second example Polycarp didn't make any rule violation. In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.
[{"input": "11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "output": "2"}, {"input": "5\n1 100\n3 200\n2\n4\n5", "output": "0"}, {"input": "7\n1 20\n2\n6\n4\n6\n6\n2", "output": "2"}]
1,800
["data structures", "dp", "greedy"]
25
[{"input": "11\r\n1 100\r\n3 70\r\n4\r\n2\r\n3 120\r\n5\r\n3 120\r\n6\r\n1 150\r\n4\r\n3 300\r\n", "output": "2\r\n"}, {"input": "5\r\n1 100\r\n3 200\r\n2\r\n4\r\n5\r\n", "output": "0\r\n"}, {"input": "7\r\n1 20\r\n2\r\n6\r\n4\r\n6\r\n6\r\n2\r\n", "output": "2\r\n"}, {"input": "1\r\n1 100\r\n", "output": "0\r\n"}, {"input": "2\r\n1 100\r\n2\r\n", "output": "0\r\n"}, {"input": "10\r\n1 37\r\n6\r\n5\r\n2\r\n5\r\n6\r\n5\r\n2\r\n4\r\n2\r\n", "output": "2\r\n"}, {"input": "10\r\n1 5\r\n4\r\n5\r\n4\r\n1 21\r\n6\r\n1 10\r\n1 1\r\n2\r\n3 1\r\n", "output": "1\r\n"}]
false
stdio
null
true