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
327/C
327
C
PyPy 3-64
TESTS
4
92
2,150,400
174870955
n=input(); ans= 0;d=int(input()); c = len(n) for x in range(c) : if n[x] == '0' or n[x] == '5' : ans+=2**x; a = x+c for i in range(1,d) : ans+=2**a a+=c print(ans)
33
280
1,740,800
176646198
# 327C - TsunamiNoLetGo s=input() k=int(input()) p=10**9+7 n=len(s) amodp = (pow(2,k*n,p)-1)%p b1modp = pow ( (pow(2,n,p) -1 + p)%p , p-2 , p ) MOD = (amodp*b1modp) % p ans=0 for i in range(len(s)): if(s[i]=='5' or s[i]=='0'): ans+=pow(2,i,10**9+7) Ans=0 Ans+= ans*( MOD ) Ans%=p print(Ans)
Codeforces Round 191 (Div. 2)
CF
2,013
1
256
Magic Five
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros. Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs. Look at the input part of the statement, s is given in a special form.
In the first line you're given a string a (1 ≤ |a| ≤ 105), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.
Print a single integer — the required number of ways modulo 1000000007 (109 + 7).
null
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125. In the second case, remember to concatenate the copies of a. The actual plate is 1399013990. In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
[{"input": "1256\n1", "output": "4"}, {"input": "13990\n2", "output": "528"}, {"input": "555\n2", "output": "63"}]
1,700
["combinatorics", "math"]
33
[{"input": "1256\r\n1\r\n", "output": "4\r\n"}, {"input": "13990\r\n2\r\n", "output": "528\r\n"}, {"input": "555\r\n2\r\n", "output": "63\r\n"}, {"input": "14\r\n178\r\n", "output": "0\r\n"}, {"input": "27755776656210607832788619414635535178188775623838313967013958143619017005079991285469853503718562504927535176713879737569375166451462839457844835806559098448980069427607\r\n151\r\n", "output": "319271478\r\n"}, {"input": "205831218776360805549796263726315728152440389522084825015113219980083245807721536032762703389\r\n161\r\n", "output": "97770312\r\n"}, {"input": "58761716080256287618526160263668449282855983776878138369871377531384\r\n100\r\n", "output": "48078375\r\n"}, {"input": "28626813825922172933379733204622160613220115755143268169598722697537715419\r\n184\r\n", "output": "43220279\r\n"}, {"input": "0\r\n1000000000\r\n", "output": "140625000\r\n"}, {"input": "079797897977\r\n1\r\n", "output": "1\r\n"}]
false
stdio
null
true
327/C
327
C
PyPy 3-64
TESTS
4
310
14,028,800
231272220
import math import random import sys import decimal def solve(): a = str(sys.stdin.readline().strip()) k = int(sys.stdin.readline()) res = 0 mod = 10 ** 9 + 7 for i in range(len(a)): if int(a[i]) % 5 == 0: x = i ll = k - 1 # e = 2 ** (x - 1) * (2 + 2 ** len(a) * (2 ** (ll + 1) - 2)) e = 2 ** (x - 1) * (2 + 2 ** len(a) * (2 ** (ll + 1) - 2)) e1 = pow(2, x - 1, mod) e2 = 2 + pow(2, len(a), mod) * (pow(2, ll + 1, mod) - 2) res = (res + (e1 * e2) % mod) % mod print(res) return if __name__ == "__main__": solve()
33
310
4,812,800
223275637
M=10**9+7 s=[int(e) for e in input()] q=len(s) k=int(input()) b=sum(pow(2,i,M) for i in range(q) if s[i]==0 or s[i]==5)%M Q=pow(2,q,M) print((b*(pow(Q,k,M)-1)*pow(Q-1,-1,M))%M)
Codeforces Round 191 (Div. 2)
CF
2,013
1
256
Magic Five
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros. Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs. Look at the input part of the statement, s is given in a special form.
In the first line you're given a string a (1 ≤ |a| ≤ 105), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.
Print a single integer — the required number of ways modulo 1000000007 (109 + 7).
null
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125. In the second case, remember to concatenate the copies of a. The actual plate is 1399013990. In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
[{"input": "1256\n1", "output": "4"}, {"input": "13990\n2", "output": "528"}, {"input": "555\n2", "output": "63"}]
1,700
["combinatorics", "math"]
33
[{"input": "1256\r\n1\r\n", "output": "4\r\n"}, {"input": "13990\r\n2\r\n", "output": "528\r\n"}, {"input": "555\r\n2\r\n", "output": "63\r\n"}, {"input": "14\r\n178\r\n", "output": "0\r\n"}, {"input": "27755776656210607832788619414635535178188775623838313967013958143619017005079991285469853503718562504927535176713879737569375166451462839457844835806559098448980069427607\r\n151\r\n", "output": "319271478\r\n"}, {"input": "205831218776360805549796263726315728152440389522084825015113219980083245807721536032762703389\r\n161\r\n", "output": "97770312\r\n"}, {"input": "58761716080256287618526160263668449282855983776878138369871377531384\r\n100\r\n", "output": "48078375\r\n"}, {"input": "28626813825922172933379733204622160613220115755143268169598722697537715419\r\n184\r\n", "output": "43220279\r\n"}, {"input": "0\r\n1000000000\r\n", "output": "140625000\r\n"}, {"input": "079797897977\r\n1\r\n", "output": "1\r\n"}]
false
stdio
null
true
792/F
792
F
Python 3
TESTS
4
498
12,083,200
88761570
#site : https://codeforces.com/contest/792/problem/F #Spells characterized by 2 values : x[i] and y[i] #Doesn't have to use spell for int(x) amounts of seconds #x = damage , y = mana cost , z = seconds #deals x * z damage spends y * z mana #If no mana is left , canUseSpell = False #Can fight monsters : t[j] and h[j] . t = time to kill vova's char , h = monster's hp #After fight , mana is refilled #if dealt h[j] damage no more than t[j] seconds using his spells , monster j dies and vova's mana refills (and if monster's health becomes exactly 0 in t[j] , the same thing happens) #Program : #Vova learns a new spell dealing x dps and y mps (mana per second(s) ) #Fights a monster which kills him in t seconds and has h hp #(Vova doesn't know any spell at the beginning) #What to do ? #You have to determine if vova's able to win the fight or no #Input : #First line : #q -> the number of queries , m -> amount of mana at the beginning of fight #2 =< q <= 10 ** 5 , 1 <= m <= 10 ** 12 #then for i=1 in range(1, q) do this : #input 3 int values : 1 <= k[i] <= 2 , 1 <= a[i] and b[i] <= 10 ** 6 #k is basically the action you want to do . either 1 or 2 . 1 means character learns a spell with x (dps) = (a[i] + j (the last monster you fought with) ) % (10 ** 6) + 1 <- for limiting it to be less than 10 ** 6 #and 2 means if character is able to win against the monster or no (output = "YES" or "NO") with time to kill of t = (a[i] + j) % (10 ** 6) + 1 and hp of h = (b[i] + j) % (10 ** 6) + 1 #inputs must be in input file in the same directory of this file #Start of code : x = 0 y = 0 j = 0 t, h = 0,0 q, m = 0, 0 def get_input(): global q, m k, a, b = [],[],[] values = input() q, m = int(values.split(" ")[0]), int(values.split(" ")[1]) for i in range(0,q): inp = input() k.append(int(inp.split(" ")[0])) a.append(int(inp.split(" ")[1])) b.append(int(inp.split(" ")[2]) % 10 ** 6) value = [k,a,b] return value k, a, b = get_input() for i in range(q): if k[i] == 1: x = (a[i] + j) % 10 ** 6 + 1 y = (b[i] + j) % 10 ** 6 + 1 elif k[i] == 2: t = (a[i] + j) % 10 ** 6 + 1 h = (b[i] + j) % 10 ** 6 + 1 j += 1 if x * t >= h and y * t <= m * 2: print("YES") else: print("NO")
36
873
15,564,800
37535361
#!/usr/bin/env python3 # solution after hint # (instead of best hit/mana spell store convex hull of spells) # O(n^2) instead of O(n log n) [q, m] = map(int, input().strip().split()) qis = [tuple(map(int, input().strip().split())) for _ in range(q)] mod = 10**6 j = 0 spell_chull = [(0, 0)] # lower hull _/ def is_right(xy0, xy1, xy): (x0, y0) = xy0 (x1, y1) = xy1 (x, y) = xy return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y) def in_chull(x, y): i = 0 if x > spell_chull[-1][0]: return False while spell_chull[i][0] < x: i += 1 if spell_chull[i][0] == x: return spell_chull[i][1] <= y else: return is_right(spell_chull[i - 1], spell_chull[i], (x, y)) def add_spell(x, y): global spell_chull if in_chull(x, y): return i_left = 0 while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)): i_left += 1 i_right = i_left + 1 while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)): i_right += 1 if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]: i_right += 1 spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:] for i, qi in enumerate(qis): (k, a, b) = qi x = (a + j) % mod + 1 y = (b + j) % mod + 1 if k == 1: add_spell(x, y) else: #2 if in_chull(y / x, m / x): print ('YES') j = i + 1 else: print ('NO')
Educational Codeforces Round 18
ICPC
2,017
2
256
Mages and Monsters
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells. Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal x·z damage and spend y·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously. Also Vova can fight monsters. Every monster is characterized by two values tj and hj — monster kills Vova's character in tj seconds and has hj health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones. Vova's character kills a monster, if he deals hj damage to it in no more than tj seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in tj seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight. You have to write a program which can answer two types of queries: - 1 x y — Vova's character learns new spell which deals x damage per second and costs y mana per second. - 2 t h — Vova fights the monster which kills his character in t seconds and has h health points. Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game. For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
The first line contains two integer numbers q and m (2 ≤ q ≤ 105, 1 ≤ m ≤ 1012) — the number of queries and the amount of mana at the beginning of every fight. i-th of each next q lines contains three numbers ki, ai and bi (1 ≤ ki ≤ 2, 1 ≤ ai, bi ≤ 106). Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these). - If ki = 1, then character learns spell with x = (ai + j) mod 106 + 1, y = (bi + j) mod 106 + 1. - If ki = 2, then you have to determine if Vova is able to win the fight against monster with t = (ai + j) mod 106 + 1, h = (bi + j) mod 106 + 1.
For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.
null
In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana.
[{"input": "3 100\n1 4 9\n2 19 49\n2 19 49", "output": "YES\nNO"}]
3,100
["data structures", "geometry"]
36
[{"input": "3 100\r\n1 4 9\r\n2 19 49\r\n2 19 49\r\n", "output": "YES\r\nNO\r\n"}, {"input": "10 442006988299\r\n2 10 47\r\n1 9 83\r\n1 15 24\r\n2 19 47\r\n2 75 99\r\n2 85 23\r\n2 8 33\r\n2 9 82\r\n1 86 49\r\n2 71 49\r\n", "output": "NO\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\n"}, {"input": "2 424978864039\r\n2 7 3\r\n2 10 8\r\n", "output": "NO\r\nNO\r\n"}, {"input": "2 1000000000000\r\n1 235726 255577\r\n1 959304 206090\r\n", "output": ""}, {"input": "3 10\r\n1 1 1\r\n2 1 1\r\n2 999999 999999\r\n", "output": "YES\r\nYES\r\n"}, {"input": "12 100\r\n1 8 8\r\n2 200 101\r\n2 10 99\r\n1 9 9\r\n2 10 99\r\n2 200 101\r\n1 14 4\r\n2 194 195\r\n2 194 194\r\n2 990 290\r\n2 999991 11\r\n2 999991 10\r\n", "output": "NO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\n"}, {"input": "15 100\r\n1 8 8\r\n2 200 101\r\n2 10 99\r\n1 9 9\r\n2 10 99\r\n2 200 101\r\n1 14 4\r\n2 194 195\r\n2 194 194\r\n2 990 290\r\n1 2 999992\r\n2 6 256\r\n2 7 256\r\n1 2 999988\r\n2 2 252\r\n", "output": "NO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nYES\r\n"}, {"input": "3 12\r\n1 99 9\r\n1 49 1\r\n2 1 149\r\n", "output": "YES\r\n"}]
false
stdio
null
true
327/C
327
C
Python 3
TESTS
4
124
0
175006786
import sys n = input() ans = 0; r = 2**len(n); c = len(n) d = int(sys.stdin.readline()) for x in range(c) : if int(n[x])%5 == 0 : ans += ((1-(r**(d))) // (1-r) * 2**x) % 1000000007 print(ans )
33
342
3,481,600
209220368
MOD = 1000000007 def power(x, n): result = 1 while n > 0: if n % 2 == 1: result = (result * x) % MOD x = (x * x) % MOD n //= 2 return result S = input().strip() k = int(input()) len_s = len(S) ans = 0 tmp = 0 for i in range(len_s - 1, -1, -1): if S[i] == '0' or S[i] == '5': ans += power(2, i) ans %= MOD tmp = (power(2, k * len_s) % MOD - 1) % MOD tmp = (tmp * power(power(2, len_s) - 1, MOD - 2)) % MOD ans = (ans * tmp) % MOD print(ans) ''' El código primero resive los valores de S y k, lee una cadena y un entero desde la entrada. Luego, realiza cálculos basados en la cadena y el entero; teorema de Fermat y exponenciación binaria(power); y finalmente imprime el resultado. '''
Codeforces Round 191 (Div. 2)
CF
2,013
1
256
Magic Five
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros. Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs. Look at the input part of the statement, s is given in a special form.
In the first line you're given a string a (1 ≤ |a| ≤ 105), containing digits only. In the second line you're given an integer k (1 ≤ k ≤ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|·k.
Print a single integer — the required number of ways modulo 1000000007 (109 + 7).
null
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125. In the second case, remember to concatenate the copies of a. The actual plate is 1399013990. In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
[{"input": "1256\n1", "output": "4"}, {"input": "13990\n2", "output": "528"}, {"input": "555\n2", "output": "63"}]
1,700
["combinatorics", "math"]
33
[{"input": "1256\r\n1\r\n", "output": "4\r\n"}, {"input": "13990\r\n2\r\n", "output": "528\r\n"}, {"input": "555\r\n2\r\n", "output": "63\r\n"}, {"input": "14\r\n178\r\n", "output": "0\r\n"}, {"input": "27755776656210607832788619414635535178188775623838313967013958143619017005079991285469853503718562504927535176713879737569375166451462839457844835806559098448980069427607\r\n151\r\n", "output": "319271478\r\n"}, {"input": "205831218776360805549796263726315728152440389522084825015113219980083245807721536032762703389\r\n161\r\n", "output": "97770312\r\n"}, {"input": "58761716080256287618526160263668449282855983776878138369871377531384\r\n100\r\n", "output": "48078375\r\n"}, {"input": "28626813825922172933379733204622160613220115755143268169598722697537715419\r\n184\r\n", "output": "43220279\r\n"}, {"input": "0\r\n1000000000\r\n", "output": "140625000\r\n"}, {"input": "079797897977\r\n1\r\n", "output": "1\r\n"}]
false
stdio
null
true
792/F
792
F
Python 3
TESTS
33
701
15,872,000
37261618
#!/usr/bin/env python3 [q, m] = map(int, input().strip().split()) qis = [tuple(map(int, input().strip().split())) for _ in range(q)] mod = 10**6 j = 0 (xb, yb) = (0, 1) for i, qi in enumerate(qis): (k, a, b) = qi x = (a + j) % mod + 1 y = (b + j) % mod + 1 if k == 1: if x * yb > y * xb: (xb, yb) = (x, y) else: #2 if min(m, x * yb) * xb >= y * yb: print ('YES') j = i + 1 else: print ('NO')
36
873
15,564,800
37535361
#!/usr/bin/env python3 # solution after hint # (instead of best hit/mana spell store convex hull of spells) # O(n^2) instead of O(n log n) [q, m] = map(int, input().strip().split()) qis = [tuple(map(int, input().strip().split())) for _ in range(q)] mod = 10**6 j = 0 spell_chull = [(0, 0)] # lower hull _/ def is_right(xy0, xy1, xy): (x0, y0) = xy0 (x1, y1) = xy1 (x, y) = xy return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y) def in_chull(x, y): i = 0 if x > spell_chull[-1][0]: return False while spell_chull[i][0] < x: i += 1 if spell_chull[i][0] == x: return spell_chull[i][1] <= y else: return is_right(spell_chull[i - 1], spell_chull[i], (x, y)) def add_spell(x, y): global spell_chull if in_chull(x, y): return i_left = 0 while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)): i_left += 1 i_right = i_left + 1 while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)): i_right += 1 if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]: i_right += 1 spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:] for i, qi in enumerate(qis): (k, a, b) = qi x = (a + j) % mod + 1 y = (b + j) % mod + 1 if k == 1: add_spell(x, y) else: #2 if in_chull(y / x, m / x): print ('YES') j = i + 1 else: print ('NO')
Educational Codeforces Round 18
ICPC
2,017
2
256
Mages and Monsters
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells. Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal x·z damage and spend y·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously. Also Vova can fight monsters. Every monster is characterized by two values tj and hj — monster kills Vova's character in tj seconds and has hj health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones. Vova's character kills a monster, if he deals hj damage to it in no more than tj seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in tj seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight. You have to write a program which can answer two types of queries: - 1 x y — Vova's character learns new spell which deals x damage per second and costs y mana per second. - 2 t h — Vova fights the monster which kills his character in t seconds and has h health points. Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game. For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
The first line contains two integer numbers q and m (2 ≤ q ≤ 105, 1 ≤ m ≤ 1012) — the number of queries and the amount of mana at the beginning of every fight. i-th of each next q lines contains three numbers ki, ai and bi (1 ≤ ki ≤ 2, 1 ≤ ai, bi ≤ 106). Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these). - If ki = 1, then character learns spell with x = (ai + j) mod 106 + 1, y = (bi + j) mod 106 + 1. - If ki = 2, then you have to determine if Vova is able to win the fight against monster with t = (ai + j) mod 106 + 1, h = (bi + j) mod 106 + 1.
For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.
null
In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana.
[{"input": "3 100\n1 4 9\n2 19 49\n2 19 49", "output": "YES\nNO"}]
3,100
["data structures", "geometry"]
36
[{"input": "3 100\r\n1 4 9\r\n2 19 49\r\n2 19 49\r\n", "output": "YES\r\nNO\r\n"}, {"input": "10 442006988299\r\n2 10 47\r\n1 9 83\r\n1 15 24\r\n2 19 47\r\n2 75 99\r\n2 85 23\r\n2 8 33\r\n2 9 82\r\n1 86 49\r\n2 71 49\r\n", "output": "NO\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\n"}, {"input": "2 424978864039\r\n2 7 3\r\n2 10 8\r\n", "output": "NO\r\nNO\r\n"}, {"input": "2 1000000000000\r\n1 235726 255577\r\n1 959304 206090\r\n", "output": ""}, {"input": "3 10\r\n1 1 1\r\n2 1 1\r\n2 999999 999999\r\n", "output": "YES\r\nYES\r\n"}, {"input": "12 100\r\n1 8 8\r\n2 200 101\r\n2 10 99\r\n1 9 9\r\n2 10 99\r\n2 200 101\r\n1 14 4\r\n2 194 195\r\n2 194 194\r\n2 990 290\r\n2 999991 11\r\n2 999991 10\r\n", "output": "NO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\n"}, {"input": "15 100\r\n1 8 8\r\n2 200 101\r\n2 10 99\r\n1 9 9\r\n2 10 99\r\n2 200 101\r\n1 14 4\r\n2 194 195\r\n2 194 194\r\n2 990 290\r\n1 2 999992\r\n2 6 256\r\n2 7 256\r\n1 2 999988\r\n2 2 252\r\n", "output": "NO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nYES\r\n"}, {"input": "3 12\r\n1 99 9\r\n1 49 1\r\n2 1 149\r\n", "output": "YES\r\n"}]
false
stdio
null
true
272/D
272
D
PyPy 3
TESTS
2
154
0
117479770
n=int(input()) a=sorted([[i,1] for i in list(map(int,input().split()))]+[[i,2] for i in list(map(int,input().split()))]) m=int(input()) d=f=0 e=1 for i in range(1,2*n): if a[i][0]!=a[i-1][0]: b=1 for j in range(f-d+1,i-d+1): b*=j if j-f+d-1<=i-f: b/=j-f+d else: b=round(b)%m e*=round(b) e%=m d=i f=i elif a[i][1]!=a[i-1][1]: f=i b=1 for j in range(f-d+1,2*n-d+1): b*=j if j-f+d-1<=2*n-f: b/=j-f+d else: b=round(b)%m e*=round(b) print(e%m)
51
654
15,769,600
106221161
from sys import stdin,stdout nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) for _ in range(1):#nmbr()): n=nmbr() a=lst() b=lst() M=nmbr() tot={} ans=1 mp={} for v,v1 in zip(a,b): tot[v]=tot.get(v,0)+1 tot[v1]=tot.get(v1,0)+1 if v==v1: mp[v]=mp.get(v,0)+1 for k,same_category in tot.items(): fact=1 for v in range(1,same_category+1): new=v while new&1==0 and mp.get(k,0)>0: new>>=1 mp[k]-=1 fact=(fact*new)%M ans=(ans*fact)%M print(ans)
Codeforces Round 167 (Div. 2)
CF
2,013
2
256
Dima and Two Sequences
Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n). Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence. Dima considers two assembled sequences (p1, q1), (p2, q2), ..., (p2·n, q2·n) and (x1, y1), (x2, y2), ..., (x2·n, y2·n) distinct, if there is such i (1 ≤ i ≤ 2·n), that (pi, qi) ≠ (xi, yi). As the answer can be rather large, print the remainder from dividing the answer by number m.
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 109). The numbers in the lines are separated by spaces. The last line contains integer m (2 ≤ m ≤ 109 + 7).
In the single line print the remainder after dividing the answer to the problem by number m.
null
In the first sample you can get only one sequence: (1, 1), (2, 1). In the second sample you can get such sequences : (1, 1), (2, 2), (2, 1), (3, 2); (1, 1), (2, 1), (2, 2), (3, 2). Thus, the answer is 2.
[{"input": "1\n1\n2\n7", "output": "1"}, {"input": "2\n1 2\n2 3\n11", "output": "2"}]
1,600
["combinatorics", "math", "sortings"]
51
[{"input": "1\r\n1\r\n2\r\n7\r\n", "output": "1\r\n"}, {"input": "2\r\n1 2\r\n2 3\r\n11\r\n", "output": "2\r\n"}, {"input": "2\r\n1 2\r\n1 2\r\n4\r\n", "output": "1\r\n"}, {"input": "4\r\n1 2 3 4\r\n4 3 2 1\r\n1009\r\n", "output": "16\r\n"}, {"input": "5\r\n1 2 3 3 5\r\n1 2 3 5 3\r\n12\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n1000000000\r\n2\r\n", "output": "1\r\n"}, {"input": "2\r\n1 2\r\n2 2\r\n4\r\n", "output": "3\r\n"}]
false
stdio
null
true
272/D
272
D
PyPy 3
TESTS
4
216
0
117491376
n=int(input()) y=list(map(int,input().split())) z=list(map(int,input().split())) a=sorted([[y[i],i] for i in range(n)]+[[z[i],i] for i in range(n)]) f=0 for i in range(1,2*n): if a[i]==a[i-1]: f+=1 m=int(input()) c=1 b=[] for i in range(1,2*n+1): c*=i c%=m b.append(c) e=1/(2**f) d=0 for i in range(1,2*n): if a[i][0]!=a[i-1][0]: e*=b[i-d-1] if e>1: e%=m d=i e*=b[2*n-d-1] print(round(e%m))
51
778
47,718,400
124594862
n = int(input()) #tamaño de las sucesiones a_n = input().split() #sucesion a_n b_n = input().split() #sucesion b_n k = int(input()) #numero para obtener un resultado de la forma km + r con 0 <= r < k def solution(n, a_n, b_n, k): c_n = {} #sucesion c_n que representa la union de a_n con b_n d_n = {} #sucesion d_n que representa la intercepcion de a_n con b_n result = 1 #resultado de la operacion for a_i, b_i in zip(a_n, b_n): #recorremos a_n y b_n al mismo tiempo if a_i == b_i: #si ambos elementos son iguales quiere decir que su par <x,y> es el mismo d_n[a_i] = d_n.get(a_i,0) + 2 #ya que estamos iterando por la misma posicion en ambas sucesiones #luego estos elementos pertenecen a la sucesion d_n c_n[a_i] = c_n.get(a_i,0) + 1 c_n[b_i] = c_n.get(b_i,0) + 1 #añadimos ambos elementos a la sucesion c_n #procedemos a allar el valor del resultado, este seria la combinacion de todas las posibles #combinaciones de cada uno de los elementos que tengan el mismo valor: c_1*c_2*...*c_n #por ende recorremos la sucesion c_n completa for c_i, cant in c_n.items(): #ahora debemos de hallar las posibles combinaciones de c_i, estas se dividen en 2 #las que pertenecen a d_n y las que no pertenecen a d_n; notemos que si esta repetida #significa que las posibles combinaciones entre ellas se van a repetir por 2, #ya que solo existen un maximo de 2 elementos repetidos por cada d_i cant_rep = d_n.get(c_i,0) #hallamos las combinaciones de los elementos repetidos como #la combinacion sin repeticion de todos los elementos entre 2 for i in range(cant - cant_rep + 1, cant, 2): result = (result * i * (i + 1) // 2) % k #hallamos las combinaciones de los elementos no repetidos como #la combinacion sin repeticion de todos los elementos for i in range(1, cant - cant_rep + 1): result = (result * i) % k #repetimos el proceso hasta el final de c_n; nocese que se multiplica directamente #el valor del resultado y que en cada multiplicacion se aplica el resto de la misma #esto es porque en la ecuacion general de: combin = km + r; setiene que si multiplicamos #la ecuacion por un c quedaria: c*combin = c*km + c*r => combin' = km' + c*r => en la #proxima multiplicacion solo queda hallar de nuevo el % k del resto c*r que queda y seria: #combin' = km' + km'' + r' => combin' = k(m' + m'') + r'; y r' seria nuestro nuevo resto return result print(solution(n, a_n, b_n, k))
Codeforces Round 167 (Div. 2)
CF
2,013
2
256
Dima and Two Sequences
Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n). Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence. Dima considers two assembled sequences (p1, q1), (p2, q2), ..., (p2·n, q2·n) and (x1, y1), (x2, y2), ..., (x2·n, y2·n) distinct, if there is such i (1 ≤ i ≤ 2·n), that (pi, qi) ≠ (xi, yi). As the answer can be rather large, print the remainder from dividing the answer by number m.
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 109). The numbers in the lines are separated by spaces. The last line contains integer m (2 ≤ m ≤ 109 + 7).
In the single line print the remainder after dividing the answer to the problem by number m.
null
In the first sample you can get only one sequence: (1, 1), (2, 1). In the second sample you can get such sequences : (1, 1), (2, 2), (2, 1), (3, 2); (1, 1), (2, 1), (2, 2), (3, 2). Thus, the answer is 2.
[{"input": "1\n1\n2\n7", "output": "1"}, {"input": "2\n1 2\n2 3\n11", "output": "2"}]
1,600
["combinatorics", "math", "sortings"]
51
[{"input": "1\r\n1\r\n2\r\n7\r\n", "output": "1\r\n"}, {"input": "2\r\n1 2\r\n2 3\r\n11\r\n", "output": "2\r\n"}, {"input": "2\r\n1 2\r\n1 2\r\n4\r\n", "output": "1\r\n"}, {"input": "4\r\n1 2 3 4\r\n4 3 2 1\r\n1009\r\n", "output": "16\r\n"}, {"input": "5\r\n1 2 3 3 5\r\n1 2 3 5 3\r\n12\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n1000000000\r\n2\r\n", "output": "1\r\n"}, {"input": "2\r\n1 2\r\n2 2\r\n4\r\n", "output": "3\r\n"}]
false
stdio
null
true
272/D
272
D
PyPy 3
TESTS
2
186
0
117869009
n=int(input()) y=list(map(int,input().split())) z=list(map(int,input().split())) a=sorted([[y[i],i] for i in range(n)]+[[z[i],i] for i in range(n)]) f=0 for i in range(1,2*n): if a[i]==a[i-1]: f+=1 m=int(input()) d=0 e=1 for i in range(1,2*n): if a[i][0]!=a[i-1][0]: for j in range(1,i-d+1): e*=j while f>0 and e%2==0: e//=2 f-=1 e%=m d=i for j in range(1,i-d+1): e*=j while f>0 and e%2==0: e//=2 f-=1 e%=m print(e%m)
51
872
23,244,800
94951314
from math import sqrt,ceil,gcd from collections import defaultdict def modInverse(b,m): g = gcd(b, m) if (g != 1): # print("Inverse doesn't exist") return -1 else: # If b and m are relatively prime, # then modulo inverse is b^(m-2) mode m return pow(b, m - 2, m) def sol(n,m,rep): r = 1 for i in range(2,n+1): j = i while j%2 == 0 and rep>0: j//=2 rep-=1 r*=j r%=m return r def solve(): n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) m = int(input()) hash = defaultdict(int) e = defaultdict(int) for i in range(n): hash[a[i]]+=1 hash[b[i]]+=1 if a[i] == b[i]: e[a[i]]+=1 ans = 1 for i in hash: z1 = hash[i] z2 = e[i] ans*=sol(z1,m,z2) ans%=m print(ans) # t = int(input()) # for _ in range(t): solve()
Codeforces Round 167 (Div. 2)
CF
2,013
2
256
Dima and Two Sequences
Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n). Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence. Dima considers two assembled sequences (p1, q1), (p2, q2), ..., (p2·n, q2·n) and (x1, y1), (x2, y2), ..., (x2·n, y2·n) distinct, if there is such i (1 ≤ i ≤ 2·n), that (pi, qi) ≠ (xi, yi). As the answer can be rather large, print the remainder from dividing the answer by number m.
The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 109). The numbers in the lines are separated by spaces. The last line contains integer m (2 ≤ m ≤ 109 + 7).
In the single line print the remainder after dividing the answer to the problem by number m.
null
In the first sample you can get only one sequence: (1, 1), (2, 1). In the second sample you can get such sequences : (1, 1), (2, 2), (2, 1), (3, 2); (1, 1), (2, 1), (2, 2), (3, 2). Thus, the answer is 2.
[{"input": "1\n1\n2\n7", "output": "1"}, {"input": "2\n1 2\n2 3\n11", "output": "2"}]
1,600
["combinatorics", "math", "sortings"]
51
[{"input": "1\r\n1\r\n2\r\n7\r\n", "output": "1\r\n"}, {"input": "2\r\n1 2\r\n2 3\r\n11\r\n", "output": "2\r\n"}, {"input": "2\r\n1 2\r\n1 2\r\n4\r\n", "output": "1\r\n"}, {"input": "4\r\n1 2 3 4\r\n4 3 2 1\r\n1009\r\n", "output": "16\r\n"}, {"input": "5\r\n1 2 3 3 5\r\n1 2 3 5 3\r\n12\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n1000000000\r\n2\r\n", "output": "1\r\n"}, {"input": "2\r\n1 2\r\n2 2\r\n4\r\n", "output": "3\r\n"}]
false
stdio
null
true
620/D
620
D
PyPy 3
TESTS
2
93
0
29683053
def SortByFirst(input): return input[0] def Find_2_Nearest(input,left,right,value): if right == left: return [input[right - 1],input[right],input[right + 1]] if right - left == 1: if input[left][0] == value: return [input[left],input[left]] elif input[right][0] == value: return [input[right],input[right]] else: return [input[left],input[right]] if input[(right + left) // 2][0] >= value: return Find_2_Nearest(input,left,(right + left) // 2,value) else: return Find_2_Nearest(input,(right + left) // 2,right,value) n = int(input()) a = [int(k) for k in (input()).split(' ')] m = int(input()) b = [int(k) for k in (input()).split(' ')] sa = sum(a) sb = sum(b) i1 = 0 j1 = 0 i2 = [] j2 = [] curval0 = abs(sa - sb) curval1 = abs(sa - sb) curval2 = curval1 sum_storage = [] for i in range(len(a)): for j in range(len(b)): if curval1 > abs(sa - sb - 2 * (a[i] - b[j])): i1 = i j1 = j curval1 = abs(sa - sb - 2 * (a[i] - b[j])) for i in range(len(a)): for i1 in range(i + 1,len(a)): sum_storage.append([2*(a[i] + a[i1]),[i,i1]]) sum_storage.sort(key = SortByFirst) for jb in range(len(b)): for jb1 in range(jb + 1,len(b)): value = sa - sb + 2 * (b[jb] + b[jb1]) res = Find_2_Nearest(sum_storage,0,len(sum_storage) - 1,value) for t in res: if curval2 > abs(t[0] - value): curval2 = abs(t[0] - value) i2 = t[1] j2 = [jb,jb1] print(min(curval0,curval1,curval2)) if curval0 == min(curval0,curval1,curval2): print('0') elif curval1 == min(curval0,curval1,curval2): print('1') print(str(i1+1) + ' ' + str(j1+1)) else: print('2') print(str(i2[0] + 1) + ' ' + str(j2[0] + 1)) print(str(i2[1] + 1) + ' ' + str(j2[1] + 1))
24
2,995
152,166,400
92182162
from bisect import bisect_left n = int(input()) a = list(map(int, input().split())) m = int(input()) b = list(map(int, input().split())) sum_a, sum_b = sum(a), sum(b) delta = sum_b - sum_a ans = abs(delta) ans_swap = [] for i in range(n): for j in range(m): if abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j])) < ans: ans = abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j])) ans_swap = [(i+1, j+1)] d = dict() for i in range(m): for j in range(i+1, m): d[b[i]+b[j]] = (i+1, j+1) minf, inf = -10**13, 10**13 val = [minf, minf] + sorted(d.keys()) + [inf, inf] for i in range(n): for j in range(i+1, n): ap = a[i] + a[j] req = (delta + ap*2) >> 1 k = bisect_left(val, req) for k in range(k-1, k+2): if abs(delta + ap*2 - val[k]*2) < ans: ans = abs(delta + ap*2 - val[k]*2) ans_swap = [(i+1, d[val[k]][0]), (j+1, d[val[k]][1])] print(ans) print(len(ans_swap)) for x, y in ans_swap: print(x, y)
Educational Codeforces Round 6
ICPC
2,016
3
256
Professor GukiZ and Two Arrays
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|. In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5, 1, 3, 2, 4] and the array b is [3, 3, 2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2, 1, 3, 2, 4] and the new array b [3, 3, 5]. Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.
The first line contains integer n (1 ≤ n ≤ 2000) — the number of elements in the array a. The second line contains n integers ai ( - 109 ≤ ai ≤ 109) — the elements of the array a. The third line contains integer m (1 ≤ m ≤ 2000) — the number of elements in the array b. The fourth line contains m integers bj ( - 109 ≤ bj ≤ 109) — the elements of the array b.
In the first line print the minimal value v = |sa - sb| that can be got with no more than two swaps. The second line should contain the number of swaps k (0 ≤ k ≤ 2). Each of the next k lines should contain two integers xp, yp (1 ≤ xp ≤ n, 1 ≤ yp ≤ m) — the index of the element in the array a and the index of the element in the array b in the p-th swap. If there are several optimal solutions print any of them. Print the swaps in order the professor did them.
null
null
[{"input": "5\n5 4 3 2 1\n4\n1 1 1 1", "output": "1\n2\n1 1\n4 2"}, {"input": "5\n1 2 3 4 5\n1\n15", "output": "0\n0"}, {"input": "5\n1 2 3 4 5\n4\n1 2 3 4", "output": "1\n1\n3 1"}]
2,200
["binary search", "two pointers"]
24
[{"input": "5\r\n5 4 3 2 1\r\n4\r\n1 1 1 1\r\n", "output": "1\r\n2\r\n1 1\r\n4 2\r\n"}, {"input": "5\r\n1 2 3 4 5\r\n1\r\n15\r\n", "output": "0\r\n0\r\n"}, {"input": "5\r\n1 2 3 4 5\r\n4\r\n1 2 3 4\r\n", "output": "1\r\n1\r\n3 1\r\n"}, {"input": "1\r\n-42\r\n1\r\n-86\r\n", "output": "44\r\n0\r\n"}, {"input": "1\r\n-21\r\n10\r\n-43 6 -46 79 -21 93 -36 -38 -67 1\r\n", "output": "1\r\n1\r\n1 3\r\n"}, {"input": "10\r\n87 -92 -67 -100 -88 80 -82 -59 81 -72\r\n10\r\n-50 30 30 77 65 92 -60 -76 -29 -15\r\n", "output": "0\r\n2\r\n4 4\r\n9 6\r\n"}, {"input": "6\r\n1 2 3 4 5 11\r\n1\r\n3\r\n", "output": "7\r\n1\r\n6 1\r\n"}, {"input": "2\r\n-2 -17\r\n2\r\n11 -9\r\n", "output": "5\r\n1\r\n1 1\r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): # Read input with open(input_path) as f: n = int(f.readline().strip()) a = list(map(int, f.readline().strip().split())) m = int(f.readline().strip()) b = list(map(int, f.readline().strip().split())) # Read reference output to get correct minimal v with open(output_path) as f: ref_v = int(f.readline().strip()) # Read submission output with open(submission_path) as f: lines = [line.strip() for line in f if line.strip()] if not lines: print(0) return # Parse submission's v try: sub_v = int(lines[0]) except ValueError: print(0) return if sub_v != ref_v: print(0) return # Parse number of swaps if len(lines) < 2: print(0) return try: k = int(lines[1]) except ValueError: print(0) return if k < 0 or k > 2: print(0) return if len(lines) != 2 + k: print(0) return # Parse swaps swaps = [] for i in range(2, 2 + k): parts = lines[i].split() if len(parts) != 2: print(0) return try: x = int(parts[0]) y = int(parts[1]) except ValueError: print(0) return if x < 1 or x > n or y < 1 or y > m: print(0) return swaps.append((x, y)) # Apply swaps current_a = a.copy() current_b = b.copy() for x, y in swaps: i = x - 1 j = y - 1 current_a[i], current_b[j] = current_b[j], current_a[i] # Compute sum difference sum_a = sum(current_a) sum_b = sum(current_b) computed_v = abs(sum_a - sum_b) if computed_v == sub_v: print(1) else: print(0) if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: checker.py input_path output_path submission_output_path") sys.exit(1) main(sys.argv[1], sys.argv[2], sys.argv[3])
true
340/E
340
E
PyPy 3
TESTS
2
748
61,849,600
85542541
#lahub and Permutations import sys readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 mod = 10**9+7 def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗) res = 1 while p > 0: if p % 2 == 0: n = n ** 2 % mod p //= 2 else: res = res * n % mod p -= 1 return res % mod def factrial_memo(n=10**6,mod=mod): fact = [1, 1] for i in range(2, n + 1): fact.append((fact[-1] * i) % mod) return fact fact = factrial_memo() def permutation(n,r): #nPr return fact[n]*pow(fact[n-r],mod-2)%mod def combination(n,r): #nCr return permutation(n,r)*pow(fact[r],mod-2)%mod #return fact[n]*pow(fact[n-r],mod-2)*pow(fact[r],mod-2) def homogeneous(n,r): #nHr return combination(n+r-1,r)%mod #return fact[n+m-1]*pow(fact[n-1],mod-2)*pow(fact[r],mod-2) n = int(readline()) lst1 = list(map(int,readline().split())) ct = 0 lst2 = [0]*2_001 for i in range(n): if i+1 == lst1[i]: print(0) exit() if lst1[i] == -1: ct += 1 else: lst2[lst1[i]] = 1 ct2 = 0 for i in range(1,n+1): if lst2[i] == 0: ct2 += 1 #lst2:その場所が埋まってないindex #lst3:その数字が使われてるindex #何個入れちゃいけない位置に入れるかで数え上げる #入れちゃいけないものはct2個って、 #ct-ct2個のものはどこに入れても要件を満たす ans = 0 for i in range(ct2+1): ans += pow(-1,i)*combination(ct2,i)*fact[ct-i] ans %= mod print(ans)
18
154
3,379,200
232103838
M=10**9+7 R=10**4 Fact=[1]*(R+1) for i in range(2,R+1): Fact[i]=(i*Fact[i-1])%M Facthyp=[1]*(R+1) Facthyp[R]=pow(Fact[R],M-2,M) for i in range(R-1,-1,-1): Facthyp[i]=((i+1)*Facthyp[i+1])%M def C(n,k): if n<k or n<0 or k<0: return 0 return (Fact[n]*Facthyp[n-k]*Facthyp[k])%M n=int(input()) a=[int(e)-1 for e in input().split()] iu=[0]*n xu=[0]*n for i in range(n): if a[i]!=-2: iu[i]=1 xu[a[i]]=1 k=sum(not (iu[I] or xu[I]) for I in range(n)) n-=sum(iu) y=0 for i in range(k+1): y+=(-1 if i%2 else 1)*C(k,i)*Fact[n-i] y%=M print(y)
Codeforces Round 198 (Div. 2)
CF
2,013
1
256
Iahub and Permutations
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).
The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.
Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).
null
For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
[{"input": "5\n-1 -1 4 3 -1", "output": "2"}]
2,000
["combinatorics", "math"]
18
[{"input": "5\r\n-1 -1 4 3 -1\r\n", "output": "2\r\n"}, {"input": "8\r\n2 4 5 3 -1 8 -1 6\r\n", "output": "1\r\n"}, {"input": "7\r\n-1 -1 4 -1 7 1 6\r\n", "output": "4\r\n"}, {"input": "6\r\n-1 -1 -1 -1 -1 -1\r\n", "output": "265\r\n"}, {"input": "2\r\n-1 -1\r\n", "output": "1\r\n"}, {"input": "10\r\n4 10 -1 1 6 8 9 2 -1 -1\r\n", "output": "4\r\n"}, {"input": "20\r\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\r\n", "output": "927799753\r\n"}]
false
stdio
null
true
340/E
340
E
Python 3
TESTS
2
186
307,200
102144502
M =pow(10,9) + 7 def iahub_and_permutations(n,p): k = len([i for i in p if i == -1]) f = factorial(k) s =[f[k]] for i in range(1,k+1): s_i =(c(k,i,f) * f[k-i]) % M s.append(s_i) r = 1 result = 0 for t in s: result = (result + (r * t)) % M r *= -1 return result def c(n,k,f): _,inv_n,_ = extended_euclidean_alg(f[k],M) _,inv_n_k,_ = extended_euclidean_alg(f[n-k],M) return (((f[n] * (inv_n % M)) % M) * (inv_n_k % M)) % M def factorial(m): facts = [1 for _ in range(m+1)] for n in range(1,m+1): facts[n] = (facts[n-1] * n) % M return facts def extended_euclidean_alg(a,b): if not b: return 0,1,0 u0,u1 = 1,0 v0,v1 = 0,1 while b: q = a//b r = a - b * q u = u0 - q * u1 v = v0 - q * v1 #Update a,b a = b b = r #Update for next iteration u0 = u1 u1 = u v0 = v1 v1 = v return a, u0, v0 def main(): n = int(input()) perm = [int(i) for i in input().split()] result = iahub_and_permutations(n,perm) print(result) main()
18
186
2,252,800
141588352
'''Author- Akshit Monga''' from sys import stdin, stdout input = stdin.readline mod=1000000007 N = MAXN = 2005 factorialNumInverse = [None] * (N + 1) naturalNumInverse = [None] * (N + 1) fact = [None] * (N + 1) def InverseofNumber(p): naturalNumInverse[0] = naturalNumInverse[1] = 1 for i in range(2, N + 1, 1): naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - int(p / i)) % p) def InverseofFactorial(p): factorialNumInverse[0] = factorialNumInverse[1] = 1 for i in range(2, N + 1, 1): factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p def factorial(p): fact[0] = 1 for i in range(1, N + 1): fact[i] = (fact[i - 1] * i) % p def Binomial(N, R, p): if N<R: return 0 ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p return ans InverseofNumber(mod) InverseofFactorial(mod) factorial(mod) t = 1 for _ in range(t): n=int(input()) a=[int(x) for x in input().split()] inside=set(a) x=y=0 for i in range(1,n+1): if a[i-1]==-1: x+=1 if i not in inside: y+=1 ans=fact[x] for i in range(1,y+1): ans+=((-1)**(i%2))*(Binomial(y,i,mod)*fact[x-i]) ans%=mod print(ans)
Codeforces Round 198 (Div. 2)
CF
2,013
1
256
Iahub and Permutations
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).
The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.
Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).
null
For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
[{"input": "5\n-1 -1 4 3 -1", "output": "2"}]
2,000
["combinatorics", "math"]
18
[{"input": "5\r\n-1 -1 4 3 -1\r\n", "output": "2\r\n"}, {"input": "8\r\n2 4 5 3 -1 8 -1 6\r\n", "output": "1\r\n"}, {"input": "7\r\n-1 -1 4 -1 7 1 6\r\n", "output": "4\r\n"}, {"input": "6\r\n-1 -1 -1 -1 -1 -1\r\n", "output": "265\r\n"}, {"input": "2\r\n-1 -1\r\n", "output": "1\r\n"}, {"input": "10\r\n4 10 -1 1 6 8 9 2 -1 -1\r\n", "output": "4\r\n"}, {"input": "20\r\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\r\n", "output": "927799753\r\n"}]
false
stdio
null
true
340/E
340
E
Python 3
TESTS
2
62
0
141893249
n = int(input()) p = list(map(int,input().split())) k= p.count(-1) dp = [0]*(10001) dp[1]=0 dp[2]=1 dp[3]=2 for i in range(4,n+1): dp[i]=(dp[i-1]*(i-1)+dp[i-2]*(i-1))%1000000007 print(dp[k]) # Fri Jan 07 2022 09:35:54 GMT+0000 (Coordinated Universal Time)
18
216
4,812,800
153656474
import sys def fact(be, en): res, res2 = [1] * (en + 1), [1] * (en + 1) for i in range(be, en + 1): res[i] = mult(res[i - 1], i) res2[i] = inv(res[i]) return res, res2 def ncr(n, r): if n < r: return 0 return mult(mult(facs[n], invs[n - r]), invs[r]) mod = 10 ** 9 + 7 add = lambda a, b: (a + b) % mod mult = lambda a, b: (a * b) % mod div = lambda a, b: mult(a, inv(b)) inv = lambda a: pow(a, mod - 2, mod) n, a = int(input()), [int(x) for x in sys.stdin.readline().split()] facs, invs = fact(1, n) vis, negs = set(a), a.count(-1) for i in range(n): if a[i] != -1 or i + 1 in vis: n -= 1 ans = facs[negs] for i in range(1, n + 1): ext = mult(facs[negs - i], ncr(n, i)) ans = add(ans, mult(pow(-1, i & 1), ext)) print(ans)
Codeforces Round 198 (Div. 2)
CF
2,013
1
256
Iahub and Permutations
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).
The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.
Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).
null
For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
[{"input": "5\n-1 -1 4 3 -1", "output": "2"}]
2,000
["combinatorics", "math"]
18
[{"input": "5\r\n-1 -1 4 3 -1\r\n", "output": "2\r\n"}, {"input": "8\r\n2 4 5 3 -1 8 -1 6\r\n", "output": "1\r\n"}, {"input": "7\r\n-1 -1 4 -1 7 1 6\r\n", "output": "4\r\n"}, {"input": "6\r\n-1 -1 -1 -1 -1 -1\r\n", "output": "265\r\n"}, {"input": "2\r\n-1 -1\r\n", "output": "1\r\n"}, {"input": "10\r\n4 10 -1 1 6 8 9 2 -1 -1\r\n", "output": "4\r\n"}, {"input": "20\r\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\r\n", "output": "927799753\r\n"}]
false
stdio
null
true
690/D1
690
D1
PyPy 3
TESTS
5
124
20,172,800
86081750
h,w = list(map(int,input().split())) arr = [] for i in range(h): arr.append(list(input())) c = 1 if ("B" in arr[h-1]): for i in range(arr[h-1].index("B"),w - arr[h-1][::-1].index("B")): s = 0 for g in range(h): if arr[g][i] != ".": s+=1 if s == 0: c+=1 print(c) else: print(0)
119
46
0
140331902
n, m = map(int, input().split()) a = [input() for i in range(n)] ans = 0 i = 0 while i < m: if a[n-1][i] == "B": ans += 1 while i < m and a[n-1][i] == "B": i += 1 i += 1 print(ans)
Helvetic Coding Contest 2016 online mirror (teams, unrated)
ICPC
2,016
0.5
256
The Wall (easy)
"The zombies are lurking outside. Waiting. Moaning. And when they come..." "When they come?" "I hope the Wall is high enough." Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are. The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: - each of the R lines contains a string of length C, - the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The number of wall segments in the input configuration.
null
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
[{"input": "3 7\n.......\n.......\n.BB.B..", "output": "2"}, {"input": "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "output": "2"}, {"input": "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "output": "1"}, {"input": "1 1\nB", "output": "1"}, {"input": "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "output": "3"}, {"input": "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB", "output": "2"}]
1,200
[]
119
[{"input": "3 7\r\n.......\r\n.......\r\n.BB.B..\r\n", "output": "2\r\n"}, {"input": "4 5\r\n..B..\r\n..B..\r\nB.B.B\r\nBBB.B\r\n", "output": "2\r\n"}, {"input": "4 6\r\n..B...\r\nB.B.BB\r\nBBB.BB\r\nBBBBBB\r\n", "output": "1\r\n"}, {"input": "1 1\r\nB\r\n", "output": "1\r\n"}, {"input": "10 7\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n...B...\r\nB.BB.B.\r\n", "output": "3\r\n"}, {"input": "8 8\r\n........\r\n........\r\n........\r\n........\r\n.B......\r\n.B.....B\r\n.B.....B\r\n.BB...BB\r\n", "output": "2\r\n"}]
false
stdio
null
true
690/F1
690
F1
Python 3
TESTS
5
31
102,400
223515608
def solve(): n=int(input()) adj=[[] for i in range(n+1)] for _ in range(n-1): a,b=[int(x) for x in input().split()] adj[a].append(b) adj[b].append(a) """for i in range(1,n): print(i,adj[i],end=" ")""" ans=0 for i in range(1,n): val=len(adj[i]) val=val*(val-1)//2 ans+=val print(ans) return op=0 for i in range(1,n+1): children=0 childchild=0 for child in adj[i]: children+=1 childchild+=len(adj[child]) val=(children*(children-1))//2 val=(val+childchild) op+=val print(i,val) print(op) solve()
19
61
204,800
146886555
o = {} n = int(input()) for _ in range(n-1): one, two = map(int, input().split()) if o.get(one): o[one] += 1 else: o[one] = 1 if o.get(two): o[two] += 1 else: o[two] = 1 # print(o) trees = 0 for key, value in o.items(): trees += int(((value-1)/2)*(1+(value-1))) print(trees)
Helvetic Coding Contest 2016 online mirror (teams, unrated)
ICPC
2,016
2
256
Tree of Life (easy)
Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies. On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges). To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree – these are paths of length 2, i.e., consisting of two edges. Help her!
The first line of the input contains a single integer n – the number of vertices in the tree (1 ≤ n ≤ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b – the labels of the vertices connected by the edge (1 ≤ a < b ≤ n). It is guaranteed that the input represents a tree.
Print one integer – the number of lifelines in the tree.
null
In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5.
[{"input": "4\n1 2\n1 3\n1 4", "output": "3"}, {"input": "5\n1 2\n2 3\n3 4\n3 5", "output": "4"}]
1,300
[]
19
[{"input": "4\r\n1 2\r\n1 3\r\n1 4\r\n", "output": "3"}, {"input": "5\r\n1 2\r\n2 3\r\n3 4\r\n3 5\r\n", "output": "4"}, {"input": "2\r\n1 2\r\n", "output": "0"}, {"input": "3\r\n2 1\r\n3 2\r\n", "output": "1"}, {"input": "10\r\n5 1\r\n1 2\r\n9 3\r\n10 5\r\n6 3\r\n8 5\r\n2 7\r\n2 3\r\n9 4\r\n", "output": "11"}]
false
stdio
null
true
690/D1
690
D1
PyPy 3
TESTS
5
93
0
119584876
n,m=map(int,input().split()) k1=[] for i in range(n): k=list(map(str,input())) k1.append(k) k2=[0]*m l=m r=0 for i in range(n): for j in range(m): if k1[i][j]=="B": k2[j]+=1 if j<l: l=j if j>r: r=j print(k2[l:r+1].count(0)+1)
119
46
0
144044966
r,c=list(map(int,input().split())) for i in range(r): walls=input() count=0 for i in range(c): if i==0 and walls[i]=='.': continue elif i==0 and walls[i]=='B': count+=1 elif walls[i]=='B' and walls[i-1]=='.': count+=1 else: continue print(count)
Helvetic Coding Contest 2016 online mirror (teams, unrated)
ICPC
2,016
0.5
256
The Wall (easy)
"The zombies are lurking outside. Waiting. Moaning. And when they come..." "When they come?" "I hope the Wall is high enough." Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are. The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: - each of the R lines contains a string of length C, - the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The number of wall segments in the input configuration.
null
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
[{"input": "3 7\n.......\n.......\n.BB.B..", "output": "2"}, {"input": "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "output": "2"}, {"input": "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "output": "1"}, {"input": "1 1\nB", "output": "1"}, {"input": "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "output": "3"}, {"input": "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB", "output": "2"}]
1,200
[]
119
[{"input": "3 7\r\n.......\r\n.......\r\n.BB.B..\r\n", "output": "2\r\n"}, {"input": "4 5\r\n..B..\r\n..B..\r\nB.B.B\r\nBBB.B\r\n", "output": "2\r\n"}, {"input": "4 6\r\n..B...\r\nB.B.BB\r\nBBB.BB\r\nBBBBBB\r\n", "output": "1\r\n"}, {"input": "1 1\r\nB\r\n", "output": "1\r\n"}, {"input": "10 7\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n...B...\r\nB.BB.B.\r\n", "output": "3\r\n"}, {"input": "8 8\r\n........\r\n........\r\n........\r\n........\r\n.B......\r\n.B.....B\r\n.B.....B\r\n.BB...BB\r\n", "output": "2\r\n"}]
false
stdio
null
true
689/D
689
D
Python 3
TESTS
2
31
102,400
192806177
import sys from types import GeneratorType from collections import defaultdict import math inf = float("inf") 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 SparseTable1: def __init__(self, lst, fun="max"): self.fun = fun self.n = len(lst) self.lst = lst self.f = [[0] * (int(math.log2(self.n)) + 1) for _ in range(self.n+1)] self.gen_sparse_table() return def gen_sparse_table(self): for i in range(1, self.n + 1): self.f[i][0] = self.lst[i - 1] for j in range(1, int(math.log2(self.n)) + 1): for i in range(1, self.n - (1 << j) + 2): a = self.f[i][j - 1] b = self.f[i + (1 << (j - 1))][j - 1] if self.fun == "max": self.f[i][j] = a if a > b else b elif self.fun == "min": self.f[i][j] = a if a < b else b else: self.f[i][j] = math.gcd(a, b) return def query(self, left, right): # 查询数组的索引 left 和 right 从 1 开始 k = int(math.log2(right - left + 1)) a = self.f[left][k] b = self.f[right - (1 << k) + 1][k] if self.fun == "max": return a if a > b else b elif self.fun == "min": return a if a < b else b else: return math.gcd(a, b) def main(ac=FastIO()): n = ac.read_int() a = ac.read_list_ints() b = ac.read_list_ints() sta = SparseTable1(a, "max") stb = SparseTable1(b, "min") ans = 0 for i in range(n): j, k = i, n-1 while j < k - 1: mid = j+(k-j)//2 if sta.query(i+1, mid+1) >= stb.query(i+1, mid+1): k = mid else: j = mid left = j if sta.query(i+1, j+1) == stb.query(i+1, j+1) else k j, k = i, n-1 while j < k - 1: mid = j+(k-j)//2 if sta.query(i+1, mid+1) >= stb.query(i+1, mid+1): j = mid else: k = mid right = k if sta.query(i+1, k+1) == stb.query(i+1, k+1) else j if left <= right and sta.query(i+1, left+1) == stb.query(i+1, left+1): ans += right-left+1 ac.st(ans) return main()
94
982
456,908,800
159169002
dx=[[0]*(1<<20) for _ in range(20)] dy=[[0]*(1<<20) for _ in range(20)] lg=[0]*(1<<20) def mx(l,r): p=lg[r-l+1] return max(dx[p][l],dx[p][r-(1<<p)+1]) def mn(l,r): p=lg[r-l+1] return min(dy[p][l],dy[p][r-(1<<p)+1]) if __name__ == '__main__': n=int(input()) dx[0][1:n]=[int(x) for x in input().split()] dy[0][1:n]=[int(x) for x in input().split()] for p in range(1,20): if (1<<p)>n: break for i in range(1,n+2-(1<<p)): dx[p][i]=max(dx[p-1][i],dx[p-1][i+(1<<(p-1))]) dy[p][i]=min(dy[p-1][i],dy[p-1][i+(1<<(p-1))]) for i in range(2,n+1): lg[i]=lg[i>>1]+1 ans=0 for i in range(1,n+1): if mx(i,i)<=mn(i,i): l=i-1 r=i p=1<<lg[n-i+1] while p: if p+l<=n and mx(i,l+p)<mn(i,l+p):l+=p if p+r<=n and mx(i,r+p)<=mn(i,r+p):r+=p p>>=1 ans+=r-l print(ans)
Codeforces Round 361 (Div. 2)
CF
2,016
2
512
Friends and Subsequences
Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows? Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r), Mike can instantly tell the value of $$\max_{i=l}^{r} a_i$$ while !Mike can instantly tell the value of $$\min_{i=l} b_i$$. Now suppose a robot (you!) asks them all possible different queries of pairs of integers (l, r) (1 ≤ l ≤ r ≤ n) (so he will make exactly n(n + 1) / 2 queries) and counts how many times their answers coincide, thus for how many pairs $$\max_{i=l}^{r}a_i = \min_{i=l}^{r}b_i$$ is satisfied. How many occasions will the robot count?
The first line contains only integer n (1 ≤ n ≤ 200 000). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the sequence a. The third line contains n integer numbers b1, b2, ..., bn ( - 109 ≤ bi ≤ 109) — the sequence b.
Print the only integer number — the number of occasions the robot will count, thus for how many pairs $$\max_{i=l}^{r}a_i = \min_{i=l}^{r}b_i$$ is satisfied.
null
The occasions in the first sample case are: 1.l = 4,r = 4 since max{2} = min{2}. 2.l = 4,r = 5 since max{2, 1} = min{2, 3}. There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always answer 1.
[{"input": "6\n1 2 3 2 1 4\n6 7 1 2 3 2", "output": "2"}, {"input": "3\n3 3 3\n1 1 1", "output": "0"}]
2,100
["binary search", "data structures"]
94
[{"input": "6\r\n1 2 3 2 1 4\r\n6 7 1 2 3 2\r\n", "output": "2\r\n"}, {"input": "3\r\n3 3 3\r\n1 1 1\r\n", "output": "0\r\n"}, {"input": "17\r\n714413739 -959271262 714413739 -745891378 926207665 -404845105 -404845105 -959271262 -189641729 -670860364 714413739 -189641729 192457837 -745891378 -670860364 536388097 -959271262\r\n-417715348 -959271262 -959271262 714413739 -189641729 571055593 571055593 571055593 -417715348 -417715348 192457837 -745891378 536388097 571055593 -189641729 571055593 -670860364\r\n", "output": "1\r\n"}, {"input": "1\r\n509658558\r\n509658558\r\n", "output": "1\r\n"}, {"input": "1\r\n509658558\r\n-544591380\r\n", "output": "0\r\n"}, {"input": "3\r\n1 1 1\r\n2 2 2\r\n", "output": "0\r\n"}]
false
stdio
null
true
796/D
796
D
Python 3
TESTS
4
1,575
60,416,000
194891184
from collections import deque, defaultdict def answer(police_locations, hashmap, d, city): result, visited, queue = set(), set(), deque() for police in police_locations: queue.append((police, d)) while queue: curr, distance = queue.popleft() if distance == 0: continue if curr in visited: result.add(curr-1) continue visited.add(curr) for nei in hashmap[curr]: if nei not in visited: queue.append((nei, distance-1)) print(len(result)) print(*result) city, police, d = map(int, input().split()) police_locations = list(map(int, input().split())) hashmap = defaultdict(list) for i in range(city-1): x,y = map(int, input().split()) hashmap[x].append(y) hashmap[y].append(x) answer(police_locations, hashmap, d, city)
135
1,184
107,827,200
127039977
import io, os, sys from collections import deque pypyin = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline cpyin = sys.stdin.readline input = pypyin if 'PyPy' in sys.version else cpyin def strput(): return input().decode() if 'PyPy' in sys.version else input() # code starts here def main(): n, k, d = [int(x) for x in input().split()] root = [int(x) for x in input().split()] g = [[] for x in range (n + 1)] for i in range(n - 1): u, v = [int(x) for x in input().split()] g[u].append((v, i + 1)) g[v].append((u, i + 1)) to_keep = [False] * n del_cnt = n - 1 queue = deque([(x, - 1) for x in root]) vis = set() ans = [] while queue: u, par = queue.popleft() if u in vis: continue vis.add(u) for v, idx in g[u]: if v == par: continue if v not in vis: del_cnt -= 1 queue.append((v, u)) else: ans.append(idx) print(len(ans)) print(*ans) if __name__ == "__main__": main()
Codeforces Round 408 (Div. 2)
CF
2,017
2
256
Police Stations
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own. Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most d kilometers along the roads. There are n cities in the country, numbered from 1 to n, connected only by exactly n - 1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has k police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city. However, Zane feels like having as many as n - 1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible. Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.
The first line contains three integers n, k, and d (2 ≤ n ≤ 3·105, 1 ≤ k ≤ 3·105, 0 ≤ d ≤ n - 1) — the number of cities, the number of police stations, and the distance limitation in kilometers, respectively. The second line contains k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — each denoting the city each police station is located in. The i-th of the following n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities directly connected by the road with index i. It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within d kilometers.
In the first line, print one integer s that denotes the maximum number of roads that can be shut down. In the second line, print s distinct integers, the indices of such roads, in any order. If there are multiple answers, print any of them.
null
In the first sample, if you shut down road 5, all cities can still reach a police station within k = 4 kilometers. In the second sample, although this is the only largest valid set of roads that can be shut down, you can print either 4 5 or 5 4 in the second line.
[{"input": "6 2 4\n1 6\n1 2\n2 3\n3 4\n4 5\n5 6", "output": "1\n5"}, {"input": "6 3 2\n1 5 6\n1 2\n1 3\n1 4\n1 5\n5 6", "output": "2\n4 5"}]
2,100
["constructive algorithms", "dfs and similar", "dp", "graphs", "shortest paths", "trees"]
135
[{"input": "6 2 4\r\n1 6\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n", "output": "1\r\n3 "}, {"input": "6 3 2\r\n1 5 6\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n5 6\r\n", "output": "2\r\n4 5 "}, {"input": "10 1 5\r\n5\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n7 8\r\n8 9\r\n9 10\r\n", "output": "0\r\n"}, {"input": "11 1 5\r\n6\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n7 8\r\n8 9\r\n9 10\r\n10 11\r\n", "output": "0\r\n"}, {"input": "2 1 1\r\n1\r\n1 2\r\n", "output": "0\r\n"}]
false
stdio
null
true
796/D
796
D
PyPy 3-64
TESTS
4
1,591
119,808,000
154001304
from sys import stdin,stdout from collections import deque n,k,d = map(int,stdin.readline().split()) #value of d does not matter here stations = map(lambda x: int(x) - 1, stdin.readline().split()) #offset by 1 due to zero indexing adjList = [[] for _ in range(n)] for i in range(n-1): a,b = map(int,stdin.readline().split()) a -= 1; b -= 1; adjList[a].append((b,i+1)) #road number is stored as right attribute adjList[b].append((a,i+1)) visited,frontier,removedRoads = [False for _ in range(n)],deque([]),set() for vertex in stations: visited[vertex] = True frontier.append((vertex,0)) #right attribute keeps track of predecessor while frontier: #BFS with time complexity O(n) since there are n vertices and n - 1 edges u,p = frontier.popleft() for v,r in adjList[u]: if not visited[v]: visited[v] = True frontier.append((v,u)) elif v != p: #already visited and not the same vertex is predecessor removedRoads.add(r) stdout.write(f'{len(removedRoads)}\n') stdout.write(' '.join(str(r) for r in removedRoads))
135
1,325
54,374,400
83862601
import math import sys input = sys.stdin.readline inf = int(1e9) n, m, d = map(int, input().split()) l = [0] * (n - 1) r = [0] * (n - 1) g = [[] for _ in range(n)] station = [int(_) - 1 for _ in input().split()] for i in range(n - 1): l[i], r[i] = map(lambda i : int(i) - 1 , input().split()) g[l[i]].append(i) g[r[i]].append(i) queue = [] dist = [inf] * n need = [True] * (n - 1) for i in station: queue.append(i) dist[i] = 0 cur = 0 while cur < len(queue): x, cur = queue[cur], cur + 1 for edge in g[x]: y = l[edge] ^ r[edge] ^ x if dist[y] > 1 + dist[x]: dist[y] = 1 + dist[x] queue.append(y) need[edge] = False print(sum(need)) edgeList = [] for i in range(n - 1): if need[i]: edgeList.append(str(i + 1)) print(' '.join(edgeList))
Codeforces Round 408 (Div. 2)
CF
2,017
2
256
Police Stations
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own. Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most d kilometers along the roads. There are n cities in the country, numbered from 1 to n, connected only by exactly n - 1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has k police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city. However, Zane feels like having as many as n - 1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible. Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.
The first line contains three integers n, k, and d (2 ≤ n ≤ 3·105, 1 ≤ k ≤ 3·105, 0 ≤ d ≤ n - 1) — the number of cities, the number of police stations, and the distance limitation in kilometers, respectively. The second line contains k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — each denoting the city each police station is located in. The i-th of the following n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities directly connected by the road with index i. It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within d kilometers.
In the first line, print one integer s that denotes the maximum number of roads that can be shut down. In the second line, print s distinct integers, the indices of such roads, in any order. If there are multiple answers, print any of them.
null
In the first sample, if you shut down road 5, all cities can still reach a police station within k = 4 kilometers. In the second sample, although this is the only largest valid set of roads that can be shut down, you can print either 4 5 or 5 4 in the second line.
[{"input": "6 2 4\n1 6\n1 2\n2 3\n3 4\n4 5\n5 6", "output": "1\n5"}, {"input": "6 3 2\n1 5 6\n1 2\n1 3\n1 4\n1 5\n5 6", "output": "2\n4 5"}]
2,100
["constructive algorithms", "dfs and similar", "dp", "graphs", "shortest paths", "trees"]
135
[{"input": "6 2 4\r\n1 6\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n", "output": "1\r\n3 "}, {"input": "6 3 2\r\n1 5 6\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n5 6\r\n", "output": "2\r\n4 5 "}, {"input": "10 1 5\r\n5\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n7 8\r\n8 9\r\n9 10\r\n", "output": "0\r\n"}, {"input": "11 1 5\r\n6\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n7 8\r\n8 9\r\n9 10\r\n10 11\r\n", "output": "0\r\n"}, {"input": "2 1 1\r\n1\r\n1 2\r\n", "output": "0\r\n"}]
false
stdio
null
true
537/D
538
D
Python 3
PRETESTS
0
46
4,710,400
10891729
import sys n = int(input()) s = [input() for i in range(n)] a = [[1] * (2 * n) for i in range(2 * n)] for i in range(n): for j in range(n): if s[i][j] != 'o': continue for x in range(n): for y in range(n): if s[x][y] == '.': a[n + x - i][n + y - j] = 0 for i in range(n): for j in range(n): if s[i][j] != 'x': continue c = 0 for x in range(n): for y in range(n): if s[x][y] == 'o' and a[n + i - x][n + j - y] == 1: c = 1 break if c == 1: break if c == 0: print('NO') sys.exit(0) print('YES') for i in range(1, 2 * n): for j in range(1, 2 * n): if i == n and j == n: print('o', end=' ') elif a[i][j] == 1: print('x', end=' ') else: print('.', end=' ') print('')
41
1,138
1,024,000
62668650
import math from sys import stdin from math import ceil import sys if __name__ == '__main__': n = int(input()) table = list() # newT = list() for i in range(n): table.append(input()) # for i in range(2 * n): # newT.append(1) # table = [input() for i in range(n)] newT = [[1] * (2 * n) for i in range(2 * n)] for i in range(n): for j in range(n): if table[i][j] != 'o': continue for a in range(n): for b in range(n): if table[a][b] == '.': newT[n + a - i][n + b - j] = 0 for i in range(n): for j in range(n): if table[i][j] != 'x': continue piece = 0 for a in range(n): for b in range(n): if table[a][b] == 'o' and newT[n + i -a][n + j - b] == 1: piece = 1 break if piece == 1: break if piece == 0: print("NO") exit() print("YES") for i in range( 1, 2 * n): for j in range( 1, 2 * n): if i == n and j == n: print('o', end = '') elif newT[i][j] == 1: print('x', end = '') else: print('.', end = '') print('')
VK Cup 2015 - Wild Card Round 2
IOI
2,015
2
256
Weird Chess
Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous. Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves. Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x, y) — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx, dy); using this move, the piece moves from the field (x, y) to the field (x + dx, y + dy). You can perform the move if the cell (x + dx, y + dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x, y) and (x + dx, y + dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess). Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.
The first line contains a single integer n (1 ≤ n ≤ 50). The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values: - o — in this case the field (i, j) is occupied by a piece and the field may or may not be attacked by some other piece; - x — in this case field (i, j) is attacked by some piece; - . — in this case field (i, j) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board.
If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n - 1) × (2n - 1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'.
null
In the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight.
[{"input": "5\noxxxx\nx...x\nx...x\nx...x\nxxxxo", "output": "YES\n....x....\n....x....\n....x....\n....x....\nxxxxoxxxx\n....x....\n....x....\n....x....\n....x...."}, {"input": "6\n.x.x..\nx.x.x.\n.xo..x\nx..ox.\n.x.x.x\n..x.x.", "output": "YES\n...........\n...........\n...........\n....x.x....\n...x...x...\n.....o.....\n...x...x...\n....x.x....\n...........\n...........\n..........."}, {"input": "3\no.x\noxx\no.x", "output": "NO"}]
1,800
["brute force", "constructive algorithms", "implementation"]
41
[{"input": "5\r\noxxxx\r\nx...x\r\nx...x\r\nx...x\r\nxxxxo\r\n", "output": "YES\r\nxxxxxxxxx\r\nx...xxxxx\r\nx...xxxxx\r\nx...xxxxx\r\nxxxxoxxxx\r\nxxxxx...x\r\nxxxxx...x\r\nxxxxx...x\r\nxxxxxxxxx\r\n"}, {"input": "6\r\n.x.x..\r\nx.x.x.\r\n.xo..x\r\nx..ox.\r\n.x.x.x\r\n..x.x.\r\n", "output": "YES\r\nxxxxxxxxxxx\r\nxxxxxxxxxxx\r\nxx.x.x..xxx\r\nxxx.x.x..xx\r\nxx.x...x.xx\r\nxxx..o..xxx\r\nxx.x...x.xx\r\nxx..x.x.xxx\r\nxxx..x.x.xx\r\nxxxxxxxxxxx\r\nxxxxxxxxxxx\r\n"}, {"input": "3\r\no.x\r\noxx\r\no.x\r\n", "output": "NO\r\n"}, {"input": "1\r\no\r\n", "output": "YES\r\no\r\n"}, {"input": "2\r\nox\r\n.o\r\n", "output": "YES\r\nxxx\r\n.ox\r\nx.x\r\n"}, {"input": "5\r\n.xxo.\r\n..oxo\r\nx.oxo\r\no..xo\r\noooox\r\n", "output": "NO\r\n"}, {"input": "8\r\n..xox.xo\r\n..xxx.xx\r\n........\r\n........\r\n........\r\n........\r\n........\r\n........\r\n", "output": "YES\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\n..xx..xox.xxxxx\r\n..xx..xxx.xxxxx\r\n............xxx\r\n............xxx\r\n............xxx\r\n............xxx\r\n............xxx\r\n............xxx\r\n"}, {"input": "8\r\n..x.xxx.\r\nx.x.xxxx\r\nxxxxxxox\r\nxxoxxxxx\r\n.xxxx.x.\r\nx.xxx.x.\r\n..x..xx.\r\n.xx...x.\r\n", "output": "YES\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxx..x.xxx.xx\r\nx..x.x.x.xxxxxx\r\nxx.x.xxxxxxxxxx\r\nxxxxxxxoxxxxxxx\r\nxxxxx.xxxx.x.xx\r\nx.xxxx.x.x.x.xx\r\nxx.xx..x..xx.xx\r\nx..x..xx...x.xx\r\nx.xx...x.xxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\n"}, {"input": "8\r\noxxxxxxx\r\nxoxxxoxx\r\nxx...x..\r\nxx...x..\r\nxx...x..\r\nxx...x..\r\noxxxxxxx\r\nxx...x..\r\n", "output": "YES\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxx...x..\r\nxxxxxxxxx...x..\r\nxxxxxxxxx...x..\r\nxxxxxxxxx...x..\r\nxxxxxxxoxxxxxxx\r\nxxxx...x.......\r\nxxxx...x.......\r\nxxxx...x.......\r\nxxxx...x.......\r\nxxxxxxxxx...x..\r\nxxxx...x...x..x\r\nxxxxxxxxx...x..\r\n"}, {"input": "8\r\nx.......\r\n.x.....x\r\nx.x...x.\r\nxx.x.x..\r\nxxx.x..x\r\n.xxx.xxx\r\n..oxxxx.\r\n.x.xoo.o\r\n", "output": "YES\r\nx..........xxxx\r\n.x...........xx\r\nx.x.........xxx\r\nxx.x.......x.xx\r\nxxx.x.....x..xx\r\n.x...x...x..xxx\r\n......x.x..xxxx\r\n.x.....o..xx.xx\r\nxxxxx.x.xxx.xxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\n"}, {"input": "8\r\n........\r\n........\r\n........\r\n..xxxx..\r\n.xx..xx.\r\n..xoox..\r\noxx..xx.\r\n..xxox..\r\n", "output": "YES\r\nxxx........xxxx\r\nxxx............\r\nxxx............\r\nxxx............\r\nxxx.........x..\r\nxxx...x.x...xx.\r\nxxx..x...x..x..\r\nxxx...xox...xx.\r\nxxxxxx...x..x..\r\nxxx...xxx...xxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\nxxxxxxxxxxxxxxx\r\n"}, {"input": "8\r\n....o...\r\n..o.x...\r\n..x..o..\r\n.....oo.\r\n.....xx.\r\n........\r\n.o...o..\r\n.x...x.o\r\n", "output": "YES\r\n....x...xxxxxxx\r\n..........x...x\r\n..........x...x\r\n...........x..x\r\n...........xx.x\r\n...........xx.x\r\n..............x\r\n.......o......x\r\nx......x.....xx\r\nx..........x.xx\r\nx..........x.xx\r\nx............xx\r\nxx...........xx\r\nxxx.x.......xxx\r\nxxx.x...x.xxxxx\r\n"}, {"input": "8\r\n.o....o.\r\n.....x..\r\n.....o..\r\n..x.....\r\n..o...x.\r\n...x..o.\r\n...oxx..\r\n....oo..\r\n", "output": "YES\r\nxx.........xxxx\r\nxx..........xxx\r\nx...........xxx\r\nx............xx\r\nx............xx\r\nx............xx\r\nx......x.....xx\r\nx......o......x\r\nx.............x\r\nx.............x\r\nx.............x\r\nx...........x.x\r\nx...........x.x\r\nx...xx...xxx..x\r\nx....x....xx..x\r\n"}, {"input": "10\r\n...o.xxx.x\r\n..ooxxxxxx\r\n.x..x.x...\r\nx.xxx..ox.\r\nxx.xoo.xxx\r\n.......xxx\r\n.x.x.xx...\r\nxo..xo..xx\r\n....x....o\r\n.ox.xxx..x\r\n", "output": "YES\r\nxxxxxxxx...x.xxx.xx\r\n...x.xxx..xxxxxxxxx\r\n..xx...x......x...x\r\n.x....x...xxx..xx.x\r\nx.xx..............x\r\nxx.x...........xx.x\r\n.......x.x.x.x....x\r\n.x..............xxx\r\nxx................x\r\n....x....o..xx...xx\r\n.xx..............xx\r\nxx........x......xx\r\nxx.x.x........x.xxx\r\nxxxx..........xxxxx\r\nxx...............xx\r\nxx.xx..x...x....xxx\r\nxxxxxx..........xxx\r\nxxxxxx..........xxx\r\nxxxxxx.xx.xxx..xxxx\r\n"}, {"input": "10\r\no....o....\r\n..........\r\nx.........\r\n...o......\r\n..o.......\r\no..oo....x\r\n..........\r\nx....x....\r\n.o........\r\n.....oo...\r\n", "output": "YES\r\nxxxx..........xxxxx\r\nxxx...............x\r\nxxxx..............x\r\nxxx...............x\r\nxxx................\r\nxxxx...............\r\nxxx................\r\nxxxx...............\r\nxxx................\r\nxxx......o.........\r\nxxxx...............\r\nxxxxx..............\r\nxxxx...............\r\nxxxx...............\r\nxxxxx.............x\r\nxxxx...............\r\nxxxxx....x....x....\r\nxxxx.x.............\r\nxxxx..........xx...\r\n"}, {"input": "13\r\n.............\r\n.....o.......\r\n......o......\r\n.............\r\n...o........o\r\no............\r\n.............\r\n..o..........\r\n..........ooo\r\n.............\r\n..o...o.....o\r\n.............\r\n.o........o..\r\n", "output": "YES\nxx......................x\nxx.....x........x.......x\n........................x\n........................x\n.......................xx\n........................x\n........................x\n.........................\n.........................\n.........................\n.........................\n........................x\n............o............\n.........................\n.........................\n......................xxx\n.........................\n........................x\n..x......................\n......................x..\n.x....................xxx\nxxxxxx.............xxxxxx\nxxxxxx..............xxxxx\nxxxxxxx.x........x..xxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxx\n"}, {"input": "20\r\nxxxxxx.xxxxxxxxxxxxx\r\n.xx.x.x.xx.xxxxxxxxx\r\nxxxxxx.xx.xx.xxx.xxx\r\nxx.xxxoxxx..xxxxxxxx\r\nxoxx.x..xx.xx.xo.xox\r\n.xxxxxxxxx.xxxxxxxxx\r\no.xxxxxoxxx..xx.oxox\r\nxxx.xxxx....xxx.xx.x\r\nxxxxxxo.xoxxoxxxxxxx\r\n.x..xx.xxxx...xx..xx\r\nxxxxxxxxxxxx..xxxxxx\r\nxxx.x.xxxxxxxx..xxxx\r\nxxxxxxx.xxoxxxx.xxx.\r\nx.x.xx.xxx.xxxxxxxx.\r\no.xxxx.xx.oxxxxx..xx\r\nx.oxxxxxx.x.xx.xx.x.\r\n.xoxx.xxxx..xx...x.x\r\nxxxx.x.xxxxxoxxxoxxx\r\noxx.xxxxx.xxxxxxxxx.\r\nxxxxxxoxxxxxx.xxxxxx\r\n", "output": "NO\r\n"}, {"input": "20\r\n.xooxo.oxx.xo..xxox.\r\nox.oo.xoox.xxo.xx.x.\r\noo..o.o.xoo.oox....o\r\nooo.ooxox.ooxox..oox\r\n.o.xx.x.ox.xo.xxoox.\r\nxooo.oo.xox.o.o.xxxo\r\noxxoox...oo.oox.xo.x\r\no.oxoxxx.oo.xooo..o.\r\no..xoxox.xo.xoooxo.x\r\n.oxoxxoo..o.xxoxxo..\r\nooxxooooox.o.x.x.ox.\r\noxxxx.oooooox.oxxxo.\r\nxoo...xoxoo.xx.x.oo.\r\noo..xxxox.xo.xxoxoox\r\nxxxoo..oo...ox.xo.o.\r\no..ooxoxo..xoo.xxxxo\r\no....oo..x.ox..oo.xo\r\n.x.xox.xo.o.oo.oxo.o\r\nooxoxoxxxox.x..xx.x.\r\n.xooxx..xo.xxoo.oo..\r\n", "output": "NO\r\n"}]
false
stdio
import sys def read_grid(path, n): with open(path, 'r') as f: lines = [line.strip() for line in f.readlines()] return [list(line) for line in lines] def main(): input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] # Read input with open(input_path, 'r') as f: n = int(f.readline()) input_grid = [list(f.readline().strip()) for _ in range(n)] # Read submission output with open(submission_path, 'r') as f: lines = [line.strip() for line in f.readlines() if line.strip()] if not lines: print(0) return first_line = lines[0] if first_line == 'NO': # Compare with reference output with open(output_path, 'r') as f: ref_first_line = f.readline().strip() print(1 if ref_first_line == 'NO' else 0) return elif first_line != 'YES': print(0) return # Check submission's grid submission_grid = [] if len(lines) < 1 + (2*n -1): print(0) return submission_grid_lines = lines[1:1+(2*n-1)] if len(submission_grid_lines) != 2*n-1: print(0) return submission_grid = [list(line) for line in submission_grid_lines] # Validate submission grid size if len(submission_grid) != 2*n -1: print(0) return for row in submission_grid: if len(row) != 2*n -1: print(0) return # Check center 'o' center = n-1 if submission_grid[center][center] != 'o': print(0) return # Collect moves (dx, dy) moves = [] for i in range(2*n -1): for j in range(2*n -1): if i == center and j == center: continue if submission_grid[i][j] == 'x': dx = j - center dy = i - center moves.append( (dx, dy) ) # Get 'o' positions o_positions = [] for y in range(n): for x in range(n): if input_grid[y][x] == 'o': o_positions.append( (x+1, y+1) ) # Compute attacked cells attacked = set() for (x, y) in o_positions: for (dx, dy) in moves: new_x = x + dx new_y = y + dy if 1 <= new_x <= n and 1 <= new_y <= n: input_y_idx = new_y - 1 input_x_idx = new_x - 1 if 0 <= input_y_idx < n and 0 <= input_x_idx < n: if input_grid[input_y_idx][input_x_idx] != 'o': attacked.add( (new_x, new_y) ) # Validate input cells for y in range(n): for x in range(n): cell = input_grid[y][x] px, py = x + 1, y + 1 if cell == 'x': if (px, py) not in attacked: print(0) return elif cell == '.': if (px, py) in attacked: print(0) return print(1) if __name__ == "__main__": main()
true
690/D1
690
D1
PyPy 3-64
TESTS
2
61
0
179829691
n, m = list(map(int, input().split())) grid = [] for _ in range(n): grid.append([i for i in input()]) def hole(row, col): if row > 0 and col > 0 and grid[row - 1][col - 1] == "B": grid[row - 1][col - 1] = "." hole(row - 1, col - 1) if row > 0 and grid[row - 1][col] == 'B': grid[row - 1][col] = "." hole(row - 1, col) if col > 0 and grid[row][col - 1] == 'B': grid[row][col - 1] = "." hole(row, col - 1) if col > 0 and row < n - 1 and grid[row + 1][col - 1] == 'B': grid[row + 1][col - 1] = "." hole(row + 1, col - 1) if row < n - 1 and grid[row + 1][col] == "B": grid[row + 1][col] = "." hole(row + 1, col) if col < m - 1 and grid[row][col + 1] == "B": grid[row][col + 1] = "." hole(row, col + 1) if col < m - 1 and row > 0 and grid[row - 1][col + 1] == "B": grid[row - 1][col + 1] = "." hole(row - 1, col + 1) if col < m - 1 and row < n - 1 and grid[row + 1][col + 1] == "B": grid[row + 1][col + 1] = "." hole(row + 1, col - 1) ans = 0 for row in range(n): for col in range(m): if grid[row][col] == "B": ans += 1 hole(row, col) print(ans)
119
46
0
159638169
a , b = map(int , input().split()) for i in range(a): l = list(map(str , input().split())) if i == a-1: l = str(l) l = l.replace('.' , ' '); l = l.replace('[' , ' '); l = l.replace(']' , ' '); l = l.replace("'" , ' '); fragments = list(map(str , l.split())) print(len(fragments))
Helvetic Coding Contest 2016 online mirror (teams, unrated)
ICPC
2,016
0.5
256
The Wall (easy)
"The zombies are lurking outside. Waiting. Moaning. And when they come..." "When they come?" "I hope the Wall is high enough." Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are. The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: - each of the R lines contains a string of length C, - the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The number of wall segments in the input configuration.
null
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
[{"input": "3 7\n.......\n.......\n.BB.B..", "output": "2"}, {"input": "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "output": "2"}, {"input": "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "output": "1"}, {"input": "1 1\nB", "output": "1"}, {"input": "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "output": "3"}, {"input": "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB", "output": "2"}]
1,200
[]
119
[{"input": "3 7\r\n.......\r\n.......\r\n.BB.B..\r\n", "output": "2\r\n"}, {"input": "4 5\r\n..B..\r\n..B..\r\nB.B.B\r\nBBB.B\r\n", "output": "2\r\n"}, {"input": "4 6\r\n..B...\r\nB.B.BB\r\nBBB.BB\r\nBBBBBB\r\n", "output": "1\r\n"}, {"input": "1 1\r\nB\r\n", "output": "1\r\n"}, {"input": "10 7\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n...B...\r\nB.BB.B.\r\n", "output": "3\r\n"}, {"input": "8 8\r\n........\r\n........\r\n........\r\n........\r\n.B......\r\n.B.....B\r\n.B.....B\r\n.BB...BB\r\n", "output": "2\r\n"}]
false
stdio
null
true
690/D1
690
D1
Python 3
TESTS
3
31
0
189108883
row, column = [*map(int, input().split())] str = '' Sum = 0 for i in range(row): str = input() if i == row - 1: for j in range(column - 1): if j == 0 and str[j] == "B": Sum += 1 elif str[j] == "." and str[j + 1] == "B": Sum += 1 print(Sum)
119
46
0
180058226
m,n=map(int,input().split()) for rows in range(m): row = input() row="."+row print(row.count(".B"))
Helvetic Coding Contest 2016 online mirror (teams, unrated)
ICPC
2,016
0.5
256
The Wall (easy)
"The zombies are lurking outside. Waiting. Moaning. And when they come..." "When they come?" "I hope the Wall is high enough." Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are. The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: - each of the R lines contains a string of length C, - the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The number of wall segments in the input configuration.
null
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
[{"input": "3 7\n.......\n.......\n.BB.B..", "output": "2"}, {"input": "4 5\n..B..\n..B..\nB.B.B\nBBB.B", "output": "2"}, {"input": "4 6\n..B...\nB.B.BB\nBBB.BB\nBBBBBB", "output": "1"}, {"input": "1 1\nB", "output": "1"}, {"input": "10 7\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n.......\n...B...\nB.BB.B.", "output": "3"}, {"input": "8 8\n........\n........\n........\n........\n.B......\n.B.....B\n.B.....B\n.BB...BB", "output": "2"}]
1,200
[]
119
[{"input": "3 7\r\n.......\r\n.......\r\n.BB.B..\r\n", "output": "2\r\n"}, {"input": "4 5\r\n..B..\r\n..B..\r\nB.B.B\r\nBBB.B\r\n", "output": "2\r\n"}, {"input": "4 6\r\n..B...\r\nB.B.BB\r\nBBB.BB\r\nBBBBBB\r\n", "output": "1\r\n"}, {"input": "1 1\r\nB\r\n", "output": "1\r\n"}, {"input": "10 7\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n.......\r\n...B...\r\nB.BB.B.\r\n", "output": "3\r\n"}, {"input": "8 8\r\n........\r\n........\r\n........\r\n........\r\n.B......\r\n.B.....B\r\n.B.....B\r\n.BB...BB\r\n", "output": "2\r\n"}]
false
stdio
null
true
690/C3
690
C3
Python 3
TESTS
3
374
5,632,000
35531302
class Brain: def __init__(self, valor, parent): self.value = valor self.childs = [] self.parent = parent def addChild(self, child): self.childs.append(child) def getChilds(self): return self.childs class Zombie: def __init__(self): self.firstBrain = Brain(1, None) self.listBrains = [self.firstBrain] self.numNodes = 1 def attachNewBrainTo(self, brain): self.numNodes += 1 nodePare = self.listBrains[brain-1] nouNode = Brain(self.numNodes, nodePare) nodePare.addChild(nouNode) self.listBrains.append(nouNode) def maxDistanceFromInner(self, node): if len(node.childs) == 0: return 1; distances = [] for c in node.childs: distances.append(self.maxDistanceFromInner(c)) return max(distances) + 1 def maxDistanceFrom(self, b): distances = [] for c in self.firstBrain.getChilds(): distances.append(self.maxDistanceFromInner(c)) distances.sort() return sum(distances[-2:]) def __str__(self): return "{name}" z = Zombie() numBrains = int(input('')) i = 0 listDistances = [] while i < numBrains - 1: b = int(input('')) z.attachNewBrainTo(b) i += 1 listDistances.append(z.maxDistanceFrom(i+1)) for d in listDistances: print(str(d)+" ",end="",flush=True) print("")
18
951
178,073,600
165319619
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict class SparseTable: def __init__(self, A, F): self.A = A self.F = F self.buildLG() self.buildST() def buildLG(self): self.LG = [] lg, V = 0, 1 for e in range(len(self.A) + 1): if V * 2 <= e: V *= 2 lg += 1 self.LG.append(lg) def buildST(self): n = len(self.A) self.ST = [] length = 1 while length <= n: if length == 1: self.ST.append(self.A) else: self.ST.append([self.F(self.ST[-1][s], self.ST[-1][s + length//2]) for s in range(n - length + 1)]) length <<= 1 def query(self, l, r): if l == r: return self.ST[0][l] if l > r: l, r = r, l e = self.LG[r - l + 1] return self.F(self.ST[e][l], self.ST[e][r - 2**e + 1]) def dfs(G, root, dst, H): Q = [(root, root, 0)] while Q: e, parent, h = Q.pop() if e not in H: H[e] = h dst.append(e) dst.append(parent) for x in G[e]: if x != parent: Q.append((x, e, h + 1)) n = int(input()) G = defaultdict(set) for i in range(2, n + 1): e = int(input()) G[e].add(i) H = {} lcaDfs = [] dfs(G, 1, lcaDfs, H) lcaFirst = [-1] * (n + 1) for i in range(len(lcaDfs)): if lcaFirst[lcaDfs[i]] == -1: lcaFirst[lcaDfs[i]] = i ST = SparseTable([(H[e], e) for e in lcaDfs], min) latency, u, v = 1, 1, 2 L = [latency] for e in range(3, n + 1): h1, v1 = ST.query(lcaFirst[u], lcaFirst[e]) latency1 = H[e] + H[u] - 2*h1 if latency1 > latency: latency = latency1 u, v = u, e else: h2, v2 = ST.query(lcaFirst[v], lcaFirst[e]) latency2 = H[e] + H[v] - 2*h2 if latency2 > latency: latency = latency2 u, v = e, v L.append(latency) print(" ".join(str(l) for l in L))
Helvetic Coding Contest 2016 online mirror (teams, unrated)
ICPC
2,016
2
256
Brain Network (hard)
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
The first line of the input contains one number n – the number of brains in the final nervous system (2 ≤ n ≤ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain $$p_k \in \{1, 2, \ldots, k-1\}$$.
Output n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
null
null
[{"input": "6\n1\n2\n2\n1\n5", "output": "1 2 2 3 4"}]
2,200
["trees"]
18
[{"input": "2\r\n1\r\n", "output": "1 "}, {"input": "3\r\n1\r\n2\r\n", "output": "1 2 "}, {"input": "10\r\n1\r\n1\r\n1\r\n1\r\n3\r\n3\r\n7\r\n5\r\n5\r\n", "output": "1 2 2 2 3 3 4 5 5 "}, {"input": "120\r\n1\r\n1\r\n2\r\n2\r\n3\r\n3\r\n4\r\n4\r\n5\r\n5\r\n6\r\n6\r\n7\r\n7\r\n8\r\n8\r\n9\r\n9\r\n10\r\n10\r\n11\r\n11\r\n12\r\n12\r\n13\r\n13\r\n14\r\n14\r\n15\r\n15\r\n16\r\n16\r\n17\r\n17\r\n18\r\n18\r\n19\r\n19\r\n20\r\n20\r\n21\r\n21\r\n22\r\n22\r\n23\r\n23\r\n24\r\n24\r\n25\r\n25\r\n26\r\n26\r\n27\r\n27\r\n28\r\n28\r\n29\r\n29\r\n30\r\n30\r\n31\r\n31\r\n32\r\n32\r\n33\r\n33\r\n34\r\n34\r\n35\r\n35\r\n36\r\n36\r\n37\r\n37\r\n38\r\n38\r\n39\r\n39\r\n40\r\n40\r\n41\r\n41\r\n42\r\n42\r\n43\r\n43\r\n44\r\n44\r\n45\r\n45\r\n46\r\n46\r\n47\r\n47\r\n48\r\n48\r\n49\r\n49\r\n50\r\n50\r\n51\r\n51\r\n52\r\n52\r\n53\r\n53\r\n54\r\n54\r\n55\r\n55\r\n56\r\n56\r\n57\r\n57\r\n58\r\n58\r\n59\r\n59\r\n60\r\n", "output": "1 2 3 3 4 4 5 5 5 5 6 6 6 6 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 "}, {"input": "6\r\n1\r\n2\r\n2\r\n1\r\n5\r\n", "output": "1 2 2 3 4 "}]
false
stdio
null
true
796/D
796
D
PyPy 3
TESTS
5
1,091
110,592,000
189014057
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def bfs(p): q, k = list(p), 0 color = [0] * (n + 1) for i in p: color[i] = i e = [] for k in range(n): i = q[k] ci = color[i] for j in G[i]: if not color[j]: q.append(j) color[j] = ci elif ci ^ color[j]: e.append((i, j)) return e n, k, d = map(int, input().split()) p = list(map(int, input().split())) G = [[] for _ in range(n + 1)] d = dict() for i in range(n - 1): u, v = map(int, input().split()) G[u].append(v) G[v].append(u) d[(u, v)], d[(v, u)] = i + 1, i + 1 e = bfs(p) s = set([d[i] for i in e]) ans = list(s) s = len(ans) print(s) sys.stdout.write(" ".join(map(str, ans)))
135
1,372
73,932,800
126162316
import math import sys input = sys.stdin.readline inf = int(1e9) n, m, d = map(int, input().split()) l = [0] * (n - 1) r = [0] * (n - 1) g = [[] for _ in range(n)] station = [int(_) - 1 for _ in input().split()] for i in range(n - 1): l[i], r[i] = map(lambda i : int(i) - 1 , input().split()) g[l[i]].append(i) g[r[i]].append(i) queue = [] dist = [inf] * n need = [True] * (n - 1) for i in station: queue.append(i) dist[i] = 0 cur = 0 while cur < len(queue): x, cur = queue[cur], cur + 1 for edge in g[x]: y = l[edge] ^ r[edge] ^ x if dist[y] > 1 + dist[x]: dist[y] = 1 + dist[x] queue.append(y) need[edge] = False print(sum(need)) edgeList = [] for i in range(n - 1): if need[i]: edgeList.append(str(i + 1)) print(' '.join(edgeList))
Codeforces Round 408 (Div. 2)
CF
2,017
2
256
Police Stations
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own. Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most d kilometers along the roads. There are n cities in the country, numbered from 1 to n, connected only by exactly n - 1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has k police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city. However, Zane feels like having as many as n - 1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible. Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.
The first line contains three integers n, k, and d (2 ≤ n ≤ 3·105, 1 ≤ k ≤ 3·105, 0 ≤ d ≤ n - 1) — the number of cities, the number of police stations, and the distance limitation in kilometers, respectively. The second line contains k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — each denoting the city each police station is located in. The i-th of the following n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities directly connected by the road with index i. It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within d kilometers.
In the first line, print one integer s that denotes the maximum number of roads that can be shut down. In the second line, print s distinct integers, the indices of such roads, in any order. If there are multiple answers, print any of them.
null
In the first sample, if you shut down road 5, all cities can still reach a police station within k = 4 kilometers. In the second sample, although this is the only largest valid set of roads that can be shut down, you can print either 4 5 or 5 4 in the second line.
[{"input": "6 2 4\n1 6\n1 2\n2 3\n3 4\n4 5\n5 6", "output": "1\n5"}, {"input": "6 3 2\n1 5 6\n1 2\n1 3\n1 4\n1 5\n5 6", "output": "2\n4 5"}]
2,100
["constructive algorithms", "dfs and similar", "dp", "graphs", "shortest paths", "trees"]
135
[{"input": "6 2 4\r\n1 6\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n", "output": "1\r\n3 "}, {"input": "6 3 2\r\n1 5 6\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n5 6\r\n", "output": "2\r\n4 5 "}, {"input": "10 1 5\r\n5\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n7 8\r\n8 9\r\n9 10\r\n", "output": "0\r\n"}, {"input": "11 1 5\r\n6\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n7 8\r\n8 9\r\n9 10\r\n10 11\r\n", "output": "0\r\n"}, {"input": "2 1 1\r\n1\r\n1 2\r\n", "output": "0\r\n"}]
false
stdio
null
true
690/C3
690
C3
Python 3
TESTS
3
1,060
5,017,600
25767481
n = int(input()) dep = [0] * n anc = [[0] * 18 for _ in range(n)] def dist(x, y): s = dep[x] + dep[y] if dep[x] > dep[y]: x, y = y, x diff = dep[y] - dep[x] i = 0 while diff > 0: if diff % 2 == 1: y = anc[y][i] diff /= 2 i += 1 if x == y: return s - dep[x] * 2 for i in range(17, -1, -1): if anc[x][i] != anc[y][i]: x, y = anc[x][i], anc[y][i] return s - (dep[x] - 1) * 2 a, b, d = 0, 0, 0 ans = [] for v in range(1, n): par = int(input()) - 1 dep[v] = dep[par] + 1 anc[v][0] = par for i in range(1, 18): x = anc[v][i - 1] anc[v][i] = anc[x][i - 1] cur = dist(a, v) if cur > d: a, b, d = a, v, cur cur = dist(b, v) if cur > d: a, b, d = b, v, cur ans.append(d) print(' '.join(map(str, ans)))
18
951
178,073,600
165319619
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict class SparseTable: def __init__(self, A, F): self.A = A self.F = F self.buildLG() self.buildST() def buildLG(self): self.LG = [] lg, V = 0, 1 for e in range(len(self.A) + 1): if V * 2 <= e: V *= 2 lg += 1 self.LG.append(lg) def buildST(self): n = len(self.A) self.ST = [] length = 1 while length <= n: if length == 1: self.ST.append(self.A) else: self.ST.append([self.F(self.ST[-1][s], self.ST[-1][s + length//2]) for s in range(n - length + 1)]) length <<= 1 def query(self, l, r): if l == r: return self.ST[0][l] if l > r: l, r = r, l e = self.LG[r - l + 1] return self.F(self.ST[e][l], self.ST[e][r - 2**e + 1]) def dfs(G, root, dst, H): Q = [(root, root, 0)] while Q: e, parent, h = Q.pop() if e not in H: H[e] = h dst.append(e) dst.append(parent) for x in G[e]: if x != parent: Q.append((x, e, h + 1)) n = int(input()) G = defaultdict(set) for i in range(2, n + 1): e = int(input()) G[e].add(i) H = {} lcaDfs = [] dfs(G, 1, lcaDfs, H) lcaFirst = [-1] * (n + 1) for i in range(len(lcaDfs)): if lcaFirst[lcaDfs[i]] == -1: lcaFirst[lcaDfs[i]] = i ST = SparseTable([(H[e], e) for e in lcaDfs], min) latency, u, v = 1, 1, 2 L = [latency] for e in range(3, n + 1): h1, v1 = ST.query(lcaFirst[u], lcaFirst[e]) latency1 = H[e] + H[u] - 2*h1 if latency1 > latency: latency = latency1 u, v = u, e else: h2, v2 = ST.query(lcaFirst[v], lcaFirst[e]) latency2 = H[e] + H[v] - 2*h2 if latency2 > latency: latency = latency2 u, v = e, v L.append(latency) print(" ".join(str(l) for l in L))
Helvetic Coding Contest 2016 online mirror (teams, unrated)
ICPC
2,016
2
256
Brain Network (hard)
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
The first line of the input contains one number n – the number of brains in the final nervous system (2 ≤ n ≤ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain $$p_k \in \{1, 2, \ldots, k-1\}$$.
Output n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
null
null
[{"input": "6\n1\n2\n2\n1\n5", "output": "1 2 2 3 4"}]
2,200
["trees"]
18
[{"input": "2\r\n1\r\n", "output": "1 "}, {"input": "3\r\n1\r\n2\r\n", "output": "1 2 "}, {"input": "10\r\n1\r\n1\r\n1\r\n1\r\n3\r\n3\r\n7\r\n5\r\n5\r\n", "output": "1 2 2 2 3 3 4 5 5 "}, {"input": "120\r\n1\r\n1\r\n2\r\n2\r\n3\r\n3\r\n4\r\n4\r\n5\r\n5\r\n6\r\n6\r\n7\r\n7\r\n8\r\n8\r\n9\r\n9\r\n10\r\n10\r\n11\r\n11\r\n12\r\n12\r\n13\r\n13\r\n14\r\n14\r\n15\r\n15\r\n16\r\n16\r\n17\r\n17\r\n18\r\n18\r\n19\r\n19\r\n20\r\n20\r\n21\r\n21\r\n22\r\n22\r\n23\r\n23\r\n24\r\n24\r\n25\r\n25\r\n26\r\n26\r\n27\r\n27\r\n28\r\n28\r\n29\r\n29\r\n30\r\n30\r\n31\r\n31\r\n32\r\n32\r\n33\r\n33\r\n34\r\n34\r\n35\r\n35\r\n36\r\n36\r\n37\r\n37\r\n38\r\n38\r\n39\r\n39\r\n40\r\n40\r\n41\r\n41\r\n42\r\n42\r\n43\r\n43\r\n44\r\n44\r\n45\r\n45\r\n46\r\n46\r\n47\r\n47\r\n48\r\n48\r\n49\r\n49\r\n50\r\n50\r\n51\r\n51\r\n52\r\n52\r\n53\r\n53\r\n54\r\n54\r\n55\r\n55\r\n56\r\n56\r\n57\r\n57\r\n58\r\n58\r\n59\r\n59\r\n60\r\n", "output": "1 2 3 3 4 4 5 5 5 5 6 6 6 6 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 12 "}, {"input": "6\r\n1\r\n2\r\n2\r\n1\r\n5\r\n", "output": "1 2 2 3 4 "}]
false
stdio
null
true
261/A
261
A
Python 3
TESTS
3
92
102,400
160215420
import dis def solve(_,q,n,a): q.sort(key=lambda a:-a) discount = 0 for d in q: if n>=d: discount = d break a.sort(key=lambda a:-a) discount2 = discount3 = discount discount+=2 boxNum = n//d sum=0 i=0 while n>i: if discount2 == 0: i+=2 discount2 = discount3 continue sum+=a[i] discount2-=1 i+=1 print(sum) m = int(input()) q = list(map(int, input().split())) n = int(input()) a = list(map(int,input().split())) solve(m,q,n,a)
45
310
7,680,000
111177282
I=lambda:map(int,input().split()) m,q,n,a,r,k=int(input()),min(I()),int(input())-1,sorted(I()),0,0 while n>-1: r+=a[n] k+=1 if k==q:n-=3;k=0 else:n-=1 print(r)
Codeforces Round 160 (Div. 1)
CF
2,013
2
256
Maxim and Discounts
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart. Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well. Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105). The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices. The numbers in the lines are separated by single spaces.
In a single line print a single integer — the answer to the problem.
null
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200. In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
[{"input": "1\n2\n4\n50 50 100 100", "output": "200"}, {"input": "2\n2 3\n5\n50 50 50 50 50", "output": "150"}, {"input": "1\n1\n7\n1 1 1 1 1 1 1", "output": "3"}]
1,400
["greedy", "sortings"]
45
[{"input": "1\r\n2\r\n4\r\n50 50 100 100\r\n", "output": "200\r\n"}, {"input": "2\r\n2 3\r\n5\r\n50 50 50 50 50\r\n", "output": "150\r\n"}, {"input": "1\r\n1\r\n7\r\n1 1 1 1 1 1 1\r\n", "output": "3\r\n"}, {"input": "18\r\n16 16 20 12 13 10 14 15 4 5 6 8 4 11 12 11 16 7\r\n15\r\n371 2453 905 1366 6471 4331 4106 2570 4647 1648 7911 2147 1273 6437 3393\r\n", "output": "38578\r\n"}, {"input": "2\r\n12 4\r\n28\r\n5366 5346 1951 3303 1613 5826 8035 7079 7633 6155 9811 9761 3207 4293 3551 5245 7891 4463 3981 2216 3881 1751 4495 96 671 1393 1339 4241\r\n", "output": "89345\r\n"}, {"input": "57\r\n3 13 20 17 18 18 17 2 17 8 20 2 11 12 11 14 4 20 9 20 14 19 20 4 4 8 8 18 17 16 18 10 4 7 9 8 10 8 20 4 11 8 12 16 16 4 11 12 16 1 6 14 11 12 19 8 20\r\n7\r\n5267 7981 1697 826 6889 1949 2413\r\n", "output": "11220\r\n"}, {"input": "1\r\n1\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n2\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n3\r\n3 1 1\r\n", "output": "3\r\n"}]
false
stdio
null
true
261/A
261
A
Python 3
TESTS
3
122
0
30185746
m = int(input()) q = [int(i) for i in input().split()] n = int(input()) a = [int(i) for i in input().split()] c = min(q) a.sort() price = 0 for i in range(n-c, 0, -2*c): for j in range(c): price += a[i+j] for j in range(n%c): price += a[j] print(price)
45
342
9,523,200
186268165
m = int(input()) q = list(map(int,input().split())) n = int(input()) a = list(map(int,input().split())) q = sorted(q) a = sorted(a,reverse = True) count = 0 i = 0 cost = 0 while i<n: if count==q[0]: i+=2 count = 0 else: count+=1 cost+=a[i] i+=1 print(cost)
Codeforces Round 160 (Div. 1)
CF
2,013
2
256
Maxim and Discounts
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart. Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well. Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105). The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices. The numbers in the lines are separated by single spaces.
In a single line print a single integer — the answer to the problem.
null
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200. In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
[{"input": "1\n2\n4\n50 50 100 100", "output": "200"}, {"input": "2\n2 3\n5\n50 50 50 50 50", "output": "150"}, {"input": "1\n1\n7\n1 1 1 1 1 1 1", "output": "3"}]
1,400
["greedy", "sortings"]
45
[{"input": "1\r\n2\r\n4\r\n50 50 100 100\r\n", "output": "200\r\n"}, {"input": "2\r\n2 3\r\n5\r\n50 50 50 50 50\r\n", "output": "150\r\n"}, {"input": "1\r\n1\r\n7\r\n1 1 1 1 1 1 1\r\n", "output": "3\r\n"}, {"input": "18\r\n16 16 20 12 13 10 14 15 4 5 6 8 4 11 12 11 16 7\r\n15\r\n371 2453 905 1366 6471 4331 4106 2570 4647 1648 7911 2147 1273 6437 3393\r\n", "output": "38578\r\n"}, {"input": "2\r\n12 4\r\n28\r\n5366 5346 1951 3303 1613 5826 8035 7079 7633 6155 9811 9761 3207 4293 3551 5245 7891 4463 3981 2216 3881 1751 4495 96 671 1393 1339 4241\r\n", "output": "89345\r\n"}, {"input": "57\r\n3 13 20 17 18 18 17 2 17 8 20 2 11 12 11 14 4 20 9 20 14 19 20 4 4 8 8 18 17 16 18 10 4 7 9 8 10 8 20 4 11 8 12 16 16 4 11 12 16 1 6 14 11 12 19 8 20\r\n7\r\n5267 7981 1697 826 6889 1949 2413\r\n", "output": "11220\r\n"}, {"input": "1\r\n1\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n2\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n3\r\n3 1 1\r\n", "output": "3\r\n"}]
false
stdio
null
true
546/B
546
B
Python 3
TESTS
3
31
0
228056871
n = int(input()) a = list(map(int,(input().split()))) c = [] counter = 0 for i in a: if i not in c: c.append(i) else: while i in c: i -= 1 counter += 1 print(counter)
49
62
307,200
11214027
n = int(input()) a = list(map(int,input().split())) a.sort() c = 0 for i in range(1,n): if a[i] > a[i-1]: continue c += a[i-1] + 1 - a[i] a[i]= a[i-1] + 1 print(c)
Codeforces Round 304 (Div. 2)
CF
2,015
3
256
Soldier and Badges
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors. Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.
First line of input consists of one integer n (1 ≤ n ≤ 3000). Next line consists of n integers ai (1 ≤ ai ≤ n), which stand for coolness factor of each badge.
Output single integer — minimum amount of coins the colonel has to pay.
null
In first sample test we can increase factor of first badge by 1. In second sample test we can increase factors of the second and the third badge by 1.
[{"input": "4\n1 3 1 4", "output": "1"}, {"input": "5\n1 2 3 2 5", "output": "2"}]
1,200
["brute force", "greedy", "implementation", "sortings"]
49
[{"input": "4\r\n1 3 1 4\r\n", "output": "1"}, {"input": "5\r\n1 2 3 2 5\r\n", "output": "2"}, {"input": "5\r\n1 5 3 2 4\r\n", "output": "0"}, {"input": "10\r\n1 1 2 3 4 5 6 7 8 9\r\n", "output": "9"}, {"input": "11\r\n9 2 10 3 1 5 7 1 4 8 6\r\n", "output": "10"}, {"input": "4\r\n4 3 2 2\r\n", "output": "3"}, {"input": "1\r\n1\r\n", "output": "0"}, {"input": "50\r\n49 37 30 2 18 48 14 48 50 27 1 43 46 5 21 28 44 2 24 17 41 38 25 18 43 28 25 21 28 23 26 27 4 31 50 18 23 11 13 28 44 47 1 26 43 25 22 46 32 45\r\n", "output": "170"}, {"input": "50\r\n37 31 19 46 45 1 9 37 15 19 15 10 17 16 38 13 26 25 36 13 7 21 12 41 46 19 3 50 14 49 49 40 29 41 47 29 3 42 13 21 10 21 9 33 38 30 24 40 5 26\r\n", "output": "135"}, {"input": "50\r\n18 13 50 12 23 29 31 44 28 29 33 31 17 38 27 37 36 34 40 4 27 2 8 27 50 27 21 28 11 13 47 25 15 26 9 15 22 3 22 45 9 12 5 5 46 44 23 34 12 25\r\n", "output": "138"}, {"input": "50\r\n24 44 39 44 11 20 6 43 4 21 43 12 41 3 25 25 24 7 16 36 32 2 2 29 34 30 33 9 18 3 14 28 26 49 29 5 5 36 44 21 36 37 1 25 46 10 10 24 10 39\r\n", "output": "128"}, {"input": "50\r\n7 5 18 2 7 12 8 20 41 4 7 3 7 10 22 1 19 9 20 10 23 3 6 3 30 13 6 18 3 3 18 38 9 7 2 1 2 5 25 10 13 1 8 34 1 26 13 8 13 2\r\n", "output": "699"}, {"input": "50\r\n2 19 24 3 12 4 14 9 10 19 6 1 26 6 11 1 4 34 17 1 3 35 17 2 17 17 5 5 12 1 24 35 2 5 43 23 21 4 18 3 11 5 1 21 3 3 3 1 10 10\r\n", "output": "692"}, {"input": "50\r\n2 2 4 19 5 7 2 35 3 12 1 18 17 16 40 4 15 36 1 11 13 3 14 1 4 10 1 12 43 7 9 9 4 3 28 9 12 12 1 33 3 23 11 24 20 20 2 4 26 4\r\n", "output": "660"}, {"input": "50\r\n5 3 25 6 30 6 39 15 3 19 1 38 1 3 17 3 8 13 4 10 14 3 2 3 20 1 21 21 27 31 6 6 14 28 3 13 49 8 12 6 17 13 45 1 6 18 12 7 31 14\r\n", "output": "574"}, {"input": "50\r\n10 25 27 13 28 35 40 39 3 6 18 29 44 1 26 2 45 36 9 46 41 12 33 19 8 22 15 48 34 20 11 32 1 47 43 23 7 5 14 30 31 21 38 42 24 49 4 37 16 17\r\n", "output": "49"}, {"input": "50\r\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "1225"}, {"input": "50\r\n50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50\r\n", "output": "1225"}, {"input": "3\r\n1 3 3\r\n", "output": "1"}, {"input": "10\r\n4 4 4 4 4 4 5 5 5 5\r\n", "output": "41"}, {"input": "4\r\n1 4 4 4\r\n", "output": "3"}, {"input": "3\r\n1 1 1\r\n", "output": "3"}, {"input": "3\r\n3 3 3\r\n", "output": "3"}]
false
stdio
null
true
543/D
543
D
Python 3
TESTS
3
93
8,704,000
124454470
import bisect import copy import decimal import fractions import heapq import itertools import math import random import sys from collections import Counter,deque,defaultdict from functools import lru_cache,reduce from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max def _heappush_max(heap,item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappushpop_max(heap, item): if heap and item < heap[0]: item, heap[0] = heap[0], item heapq._siftup_max(heap, 0) return item from math import gcd as GCD, modf read=sys.stdin.read readline=sys.stdin.readline readlines=sys.stdin.readlines class Graph: def __init__(self,V,edges=False,graph=False,directed=False,weighted=False): self.V=V self.directed=directed self.weighted=weighted if not graph: self.edges=edges self.graph=[[] for i in range(self.V)] if weighted: for i,j,d in self.edges: self.graph[i].append((j,d)) if not self.directed: self.graph[j].append((i,d)) else: for i,j in self.edges: self.graph[i].append(j) if not self.directed: self.graph[j].append(i) else: self.graph=graph self.edges=[] for i in range(self.V): if self.weighted: for j,d in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j,d)) else: for j in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j)) def SS_BFS(self,s,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V seen[s]=True if linked_components: lc=[s] if parents: ps=[None]*self.V ps[s]=s if unweighted_dist or bipartite_graph: uwd=[float('inf')]*self.V uwd[s]=0 if weighted_dist: wd=[float('inf')]*self.V wd[s]=0 queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if linked_components: lc.append(y) if parents: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d if bipartite_graph: bg=[[],[]] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if type(uwd[i])==float or type(uwd[j])==float: continue if not uwd[i]%2^uwd[j]%2: bg=False break else: for x in range(self.V): if type(uwd[x])==float: continue bg[uwd[x]%2].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if unweighted_dist: tpl+=(uwd,) if weighted_dist: tpl+=(wd,) if len(tpl)==1: tpl=tpl[0] return tpl def AP_BFS(self,bipartite_graph=False,linked_components=False,parents=False): seen=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if linked_components: lc=[] if parents: ps=[None]*self.V for s in range(self.V): if seen[s]: continue seen[s]=True if bipartite_graph: cnt+=1 bg[s]=(cnt,s&2) if linked_components: lc.append([s]) if parents: ps[s]=s queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if linked_components: lc[-1].append(y) if parents: ps[y]=x if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if len(tpl)==1: tpl=tpl[0] return tpl def SS_DFS(self,s,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,subtree_size=False,topological_sort=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V finished=[False]*self.V if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if parents or cycle_detection or subtree_size: ps=[None]*self.V ps[s]=s if postorder or topological_sort: post=[] if preorder: pre=[] if subtree_size: ss=[1]*self.V if unweighted_dist or bipartite_graph: uwd=[float('inf')]*self.V uwd[s]=0 if weighted_dist: wd=[float('inf')]*self.V wd[s]=0 stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc.append(x) if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if parents or cycle_detection or subtree_size: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d elif not finished[y]: if (directed_acyclic or cycle_detection or topological_sort) and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if postorder or topological_sort: post.append(x) if subtree_size: for y in self.graph[x]: if y==ps[x]: continue ss[x]+=ss[y] if bipartite_graph: bg=[[],[]] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if type(uwd[i])==float or type(uwd[j])==float: continue if not uwd[i]%2^uwd[j]%2: bg=False break else: for x in range(self.V): if type(uwd[x])==float: continue bg[uwd[x]%2].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) tpl+=(cd,) if directed_acyclic: tpl+=(dag,) if euler_tour: tpl+=(et,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if postorder: tpl+=(post,) if preorder: tpl+=(pre,) if subtree_size: tpl+=(ss,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] tpl+=(tp_sort,) if unweighted_dist: tpl+=(uwd,) if weighted_dist: tpl+=(wd,) if len(tpl)==1: tpl=tpl[0] return tpl def AP_DFS(self,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,topological_sort=False): seen=[False]*self.V finished=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if parents or cycle_detection: ps=[None]*self.V if postorder or topological_sort: post=[] if preorder: pre=[] for s in range(self.V): if seen[s]: continue if bipartite_graph: cnt+=1 bg[s]=(cnt,s&2) if linked_components: lc.append([]) if parents: ps[s]=s stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc[-1].append(x) if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if parents or cycle_detection: ps[y]=x elif not finished[y]: if directed_acyclic and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if postorder or topological_sort: post.append(x) if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) tpl+=(cd,) if directed_acyclic: tpl+=(dag,) if euler_tour: tpl+=(et,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if postorder: tpl+=(post,) if preorder: tpl+=(pre,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] tpl+=(tp_sort,) if len(tpl)==1: tpl=tpl[0] return tpl def Tree_Diameter(self,weighted=False): def Farthest_Point(u): dist=self.SS_BFS(u,weighted_dist=True) if weighted else self.SS_BFS(u,unweighted_dist=True) fp=0 for i in range(self.V): if dist[fp]<dist[i]: fp=i return fp,dist[fp] u,d=Farthest_Point(0) v,d=Farthest_Point(u) return u,v,d def SCC(self): reverse_graph=[[] for i in range(self.V)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl reverse_graph[j].append(i) postorder=self.AP_DFS(postorder=True) scc=[] seen=[False]*self.V for s in postorder[::-1]: if seen[s]: continue queue=deque([s]) seen[s]=True lst=[] while queue: x=queue.popleft() lst.append(x) for y in reverse_graph[x]: if self.weighted: y=y[0] if not seen[y]: seen[y]=True queue.append(y) scc.append(lst) return scc def Build_LCA(self,s): self.euler_tour,self.parents,depth=self.SS_DFS(s,euler_tour=True,parents=True,unweighted_dist=True) self.dfs_in_index=[None]*self.V self.dfs_out_index=[None]*self.V for i,x in enumerate(self.euler_tour): if x>=0: self.dfs_in_index[x]=i else: self.dfs_out_index[~x]=i self.ST=Segment_Tree(2*self.V,lambda x,y:min(x,y),float('inf')) lst=[None]*2*self.V for i in range(2*self.V): if self.euler_tour[i]>=0: lst[i]=depth[self.euler_tour[i]] else: lst[i]=depth[self.parents[~self.euler_tour[i]]] self.ST.Build(lst) def LCA(self,a,b): m=min(self.dfs_in_index[a],self.dfs_in_index[b]) M=max(self.dfs_in_index[a],self.dfs_in_index[b]) x=self.euler_tour[self.ST.Fold_Index(m,M+1)] if x>=0: return x else: return self.parents[~x] def Dijkstra(self,s,route_restoration=False): dist=[float('inf')]*self.V dist[s]=0 hq=[(0,s)] if route_restoration: parents=[None]*self.V parents[s]=s while hq: dx,x=heapq.heappop(hq) if dist[x]<dx: continue for y,dy in self.graph[x]: if dist[y]>dx+dy: dist[y]=dx+dy if route_restoration: parents[y]=x heapq.heappush(hq,(dist[y],y)) if route_restoration: return dist,parents else: return dist def Bellman_Ford(self,s,route_restoration=False): dist=[float('inf')]*self.V dist[s]=0 if route_restoration: parents=[s]*self.V for _ in range(self.V-1): for i,j,d in self.edges: if dist[j]>dist[i]+d: dist[j]=dist[i]+d if route_restoration: parents[j]=i if not self.directed and dist[i]>dist[j]+d: dist[i]=dist[j]+d if route_restoration: parents[i]=j negative_cycle=[] for i,j,d in self.edges: if dist[j]>dist[i]+d: negative_cycle.append(j) if not self.directed and dist[i]>dist[j]+d: negative_cycle.append(i) if negative_cycle: is_negative_cycle=[False]*self.V for i in negative_cycle: if is_negative_cycle[i]: continue else: queue=deque([i]) is_negative_cycle[i]=True while queue: x=queue.popleft() for y,d in self.graph[x]: if not is_negative_cycle[y]: queue.append(y) is_negative_cycle[y]=True if route_restoration: parents[y]=x for i in range(self.V): if is_negative_cycle[i]: dist[i]=-float('inf') if route_restoration: return dist,parents else: return dist def Warshall_Floyd(self,route_restoration=False): dist=[[float('inf')]*self.V for i in range(self.V)] for i in range(self.V): dist[i][i]=0 if route_restoration: parents=[[j for j in range(self.V)] for i in range(self.V)] for i,j,d in self.edges: if dist[i][j]>d: dist[i][j]=d if route_restoration: parents[i][j]=i if not self.directed and dist[j][i]>d: dist[j][i]=d if route_restoration: parents[j][i]=j for k in range(self.V): for i in range(self.V): for j in range(self.V): if dist[i][j]>dist[i][k]+dist[k][j]: dist[i][j]=dist[i][k]+dist[k][j] if route_restoration: parents[i][j]=parents[k][j] for i in range(self.V): if dist[i][i]<0: for j in range(self.V): if dist[i][j]!=float('inf'): dist[i][j]=-float('inf') if route_restoration: return dist,parents else: return dist def Route_Restoration(self,s,g,parents): route=[g] while s!=g and parents[g]!=g: g=parents[g] route.append(g) route=route[::-1] return route def Kruskal(self): UF=UnionFind(self.V) sorted_edges=sorted(self.edges,key=lambda x:x[2]) minimum_spnning_tree=[] for i,j,d in sorted_edges: if not UF.Same(i,j): UF.Union(i,j) minimum_spnning_tree.append((i,j,d)) return minimum_spnning_tree def Ford_Fulkerson(self,s,t): max_flow=0 residual_graph=[defaultdict(int) for i in range(self.V)] if self.weighted: for i,j,d in self.edges: if not d: continue residual_graph[i][j]+=d if not self.directed: residual_graph[j][i]+=d else: for i,j in self.edges: residual_graph[i][j]+=1 if not self.directed: residual_graph[j][i]+=1 while True: parents=[None]*self.V parents[s]=s seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in residual_graph[x].keys(): if not seen[y]: seen[y]=True queue.append(y) parents[y]=x if y==t: tt=t while tt!=s: residual_graph[parents[tt]][tt]-=1 residual_graph[tt][parents[tt]]+=1 if not residual_graph[parents[tt]][tt]: residual_graph[parents[tt]].pop(tt) tt=parents[tt] max_flow+=1 break else: continue break else: break return max_flow def BFS(self,s): seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) return def DFS(self,s): seen=[False]*self.V finished=[False]*self.V stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) elif not finished[x]: finished[x]=True return N=int(readline()) edges=[] parents=[0]+[p-1 for p in list(map(int,readline().split()))] for i in range(1,N): edges.append((i,parents[i])) G=Graph(N,edges=edges) mod=10**9+7 dp=[1]*N postorder=G.SS_DFS(0,postorder=True) for x in postorder: for y in G.graph[x]: if y==parents[x]: continue dp[x]*=(1+dp[y]) dp[x]%=mod dp_=[1]*N for x in postorder[::-1]: lst=[y for y in G.graph[x] if y!=parents[x]] l=len(lst) lst_l=[1]*(l+1) lst_r=[1]*(l+1) for i in range(1,l+1): lst_l[i]=lst_l[i-1]*(dp[lst[i-1]]+1)%mod for i in range(l-1,-1,-1): lst_r[i]=lst_r[i+1]*(dp[lst[i]]+1)%mod for i in range(l): if x: dp_[lst[i]]*=dp_[parents[x]]+1 dp_[lst[i]]*=lst_l[i]*lst_r[i+1] dp_[lst[i]]+=1 dp_[lst[i]]%=mod ans_lst=[dp[x]*dp_[x]%mod for x in range(N)] print(*ans_lst)
42
514
72,294,400
199415564
import sys from typing import Callable, Generic, List, TypeVar T = TypeVar("T") class Rerooting(Generic[T]): __slots__ = ("adjList", "_n", "_decrement") def __init__(self, n: int, decrement: int = 0): self.adjList = [[] for _ in range(n)] self._n = n self._decrement = decrement def addEdge(self, u: int, v: int) -> None: u -= self._decrement v -= self._decrement self.adjList[u].append(v) self.adjList[v].append(u) def rerooting( self, e: Callable[[int], T], op: Callable[[T, T], T], composition: Callable[[T, int, int, int], T], root=0, ) -> List["T"]: root -= self._decrement assert 0 <= root < self._n parents = [-1] * self._n order = [root] stack = [root] while stack: cur = stack.pop() for next in self.adjList[cur]: if next == parents[cur]: continue parents[next] = cur order.append(next) stack.append(next) dp1 = [e(i) for i in range(self._n)] dp2 = [e(i) for i in range(self._n)] for cur in order[::-1]: res = e(cur) for next in self.adjList[cur]: if parents[cur] == next: continue dp2[next] = res res = op(res, composition(dp1[next], cur, next, 0)) res = e(cur) for next in self.adjList[cur][::-1]: if parents[cur] == next: continue dp2[next] = op(res, dp2[next]) res = op(res, composition(dp1[next], cur, next, 0)) dp1[cur] = res for newRoot in order[1:]: parent = parents[newRoot] dp2[newRoot] = composition(op(dp2[newRoot], dp2[parent]), parent, newRoot, 1) dp1[newRoot] = op(dp1[newRoot], dp2[newRoot]) return dp1 input = lambda: sys.stdin.readline().rstrip("\r\n") INF = int(4e18) MOD = int(1e9 + 7) if __name__ == "__main__": n = int(input()) edges = [] parents = list(map(int, input().split())) for i in range(1, n): p = parents[i - 1] - 1 edges.append((p, i)) E = int def e(root: int) -> E: return 1 def op(childRes1: E, childRes2: E) -> E: return childRes1 * childRes2 % MOD def composition(fromRes: E, parent: int, cur: int, direction: int) -> E: """direction: 0: cur -> parent, 1: parent -> cur""" return fromRes + 1 R = Rerooting(n) for u, v in edges: R.addEdge(u, v) dp = R.rerooting(e=e, op=op, composition=composition, root=0) print(*dp)
Codeforces Round 302 (Div. 1)
CF
2,015
2
256
Road Improvement
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive. All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road. Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).
The first line of the input contains a single integer n (2 ≤ n ≤ 2·105) — the number of cities in the country. Next line contains n - 1 positive integers p2, p3, p4, ..., pn (1 ≤ pi ≤ i - 1) — the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i.
Print n integers a1, a2, ..., an, where ai is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (109 + 7), if the capital of the country is at city number i.
null
null
[{"input": "3\n1 1", "output": "4 3 3"}, {"input": "5\n1 2 3 4", "output": "5 8 9 8 5"}]
2,300
["dp", "trees"]
42
[{"input": "3\r\n1 1\r\n", "output": "4 3 3"}, {"input": "5\r\n1 2 3 4\r\n", "output": "5 8 9 8 5"}, {"input": "31\r\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "73741817 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913"}, {"input": "29\r\n1 2 2 4 4 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28\r\n", "output": "191 380 191 470 236 506 254 506 504 500 494 486 476 464 450 434 416 396 374 350 324 296 266 234 200 164 126 86 44"}, {"input": "70\r\n1 2 2 4 4 6 6 8 9 9 11 11 13 13 15 15 17 17 19 19 21 22 22 24 24 26 27 27 29 29 31 31 33 34 34 36 37 37 39 39 41 42 42 44 44 46 47 47 49 50 50 52 52 54 54 56 57 57 59 60 60 62 63 63 65 65 67 68 68\r\n", "output": "0 1000000005 0 499999996 249999999 749999986 374999994 874999963 999999938 499999970 62499881 531249945 93749781 546874895 109374581 554687295 117186681 558593345 121092131 560546070 123043656 124995179 562497594 125968539 562984274 126450416 126932291 563466150 127163621 563581815 127260071 563630040 127269866 127279659 563639834 127207694 127135727 563567868 126946019 563473014 126543716 126141411 563070710 125325359 562662684 123687534 122049707 561024858 118771194 115492679 557746344 108934221 554467115 95816591 547908300 69580974 43345355 521672682 990873947 938402530 469201266 833459609 728516686 364258344 518630798 259315400 98859001 679087209 839543609 839543609 "}, {"input": "59\r\n1 2 2 4 4 5 7 7 8 8 10 10 11 11 15 15 9 18 18 20 20 21 23 22 22 26 6 6 28 30 30 31 31 33 34 34 32 32 38 40 39 39 29 44 44 45 47 47 46 46 50 52 52 54 51 51 57 58\r\n", "output": "0 1000000005 0 499999996 499259752 500131906 498519506 453903141 456877573 963122521 230821046 981561265 981561265 115410524 784656845 892328427 892328427 415235638 207617820 331951678 748963765 998815735 165975843 582987926 999407872 332543823 666271916 492735403 494450227 485338898 330005231 366989446 553336825 864004193 776668417 932002101 932002101 775242091 893591565 183494727 591747368 946795787 946795787 488768546 73973791 454675898 659179041 829589525 829589525 147841416 181934138 841006939 920503474 227337959 613668984 90967070 636450610 90967073 545483541 "}, {"input": "2\r\n1\r\n", "output": "2 2"}, {"input": "3\r\n1 2\r\n", "output": "3 4 3"}, {"input": "69\r\n1 1 3 3 5 5 7 8 8 10 10 12 12 14 14 16 16 18 18 20 21 21 23 23 25 26 26 28 28 30 30 32 33 33 35 36 36 38 38 40 41 41 43 43 45 46 46 48 49 49 51 51 53 53 55 56 56 58 59 59 61 62 62 64 64 66 67 67\r\n", "output": "1000000006 500000004 499999999 750000004 749999993 875000001 874999978 999999961 999999985 62499920 31249961 93749852 46874927 109374716 54687359 117186944 58593473 121092650 60546326 123044687 124996722 62498362 125971106 62985554 126455031 126938954 63469478 127174380 63587191 127279022 63639512 127305201 127331378 63665690 127292181 127252982 63626492 127128810 63564406 126857579 126586346 63293174 126032438 63016220 124918901 123805362 61902682 121575425 119345486 59672744 114884180 57442091 105960854 52980428 88113845 70266834 35133418 34572635 998878441 999439225 927489952 856101461 928050735 713324437 856662223 427770368 142216297 571108153 571108153 "}, {"input": "137\r\n1 1 3 3 5 5 7 8 8 10 10 12 12 14 14 16 16 18 18 20 21 21 23 23 25 26 26 28 28 30 30 32 33 33 35 36 36 38 38 40 41 41 43 43 45 46 46 48 49 49 51 51 53 53 55 56 56 58 59 59 61 62 62 64 64 66 67 67 1 1 71 71 73 73 75 76 76 78 78 80 80 82 82 84 84 86 86 88 89 89 91 91 93 94 94 96 96 98 98 100 101 101 103 104 104 106 106 108 109 109 111 111 113 114 114 116 117 117 119 119 121 121 123 124 124 126 127 127 129 130 130 132 132 134 135 135\r\n", "output": "1 500000005 500000005 750000007 750000007 875000008 875000008 0 1 62499998 31250000 93749994 46874998 109374986 54687494 117187470 58593736 121093688 60546845 123046749 124999808 62499905 125976240 62988121 126464261 126952280 63476141 127195898 63597950 127316924 63658463 127375871 127434816 63717409 127461155 127487492 63743747 127494392 63747197 127485305 127476216 63738109 127446596 63723299 127381635 127316672 63658337 127183887 127051100 63525551 126784098 63392050 126249380 63124691 125179587 124109792 62054897 121970025 119830256 59915129 115550631 111271004 55635503 102711708 51355855 85593095 68474480 34237241 34237241 500000005 500000005 750000007 750000007 875000008 875000008 0 1 62499998 31250000 93749994 46874998 109374986 54687494 117187470 58593736 121093688 60546845 123046749 124999808 62499905 125976240 62988121 126464261 126952280 63476141 127195898 63597950 127316924 63658463 127375871 127434816 63717409 127461155 127487492 63743747 127494392 63747197 127485305 127476216 63738109 127446596 63723299 127381635 127316672 63658337 127183887 127051100 63525551 126784098 63392050 126249380 63124691 125179587 124109792 62054897 121970025 119830256 59915129 115550631 111271004 55635503 102711708 51355855 85593095 68474480 34237241 34237241 "}, {"input": "150\r\n1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 14 15 15 15 16 16 16 17 17 17 18 18 18 19 19 19 20 20 20 21 21 21 22 22 22 23 23 23 24 24 24 25 25 25 26 26 26 27 27 27 28 28 28 28 29 29 29 29 30 30 30 30 31 31 31 31 31 32 32 32 32 32 33 33 33 33 33 33 34 34 34 34 34 34 35 35 35 35 35 35 35 36 36 36 36 36 36 36 37 37 37 37 37 37 37 37 37\r\n", "output": "0 1000000005 0 0 0 0 800000008 800000008 800000008 800000008 800000008 800000008 800000008 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 705882372 705882372 705882372 878787915 878787915 61538524 61538524 596899355 596899355 196881603 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 939393962 939393962 939393962 939393962 939393962 939393962 939393962 939393962 939393962 939393962 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 598440806 598440806 598440806 598440806 598440806 598440806 598440806 598440806 598440806 "}]
false
stdio
null
true
543/D
543
D
PyPy 3-64
TESTS
2
61
614,400
178102723
def rerooting(): dp=[[E]*len(edge[v]) for v in range(n)] # dfs1 memo=[E]*n for v in order[::-1]: res=E for i in range(len(edge[v])): if edge[v][i]==par[v]: continue dp[v][i]=memo[edge[v][i]] res=merge(res,f(dp[v][i],edge[v][i])) memo[v]=g(res,v) # dfs2 memo2=[E]*n for v in order: for i in range(len(edge[v])): if edge[v][i]==par[v]: dp[v][i]=memo2[v] s=len(edge[v]) cumR=[E]*(s+1) cumR[s]=E for i in range(s,0,-1): cumR[i-1]=merge(cumR[i],f(dp[v][i-1],v)) cumL=E for i in range(s): if edge[v][i]!=par[v]: val=val=merge(cumL,cumR[i+1]) memo2[edge[v][i]]=g(val,v) cumL=merge(cumL,f(dp[v][i],edge[v][i])) ans=[E for i in range(n)] for v in range(n): res=E for i in range(len(edge[v])): res=merge(res,f(dp[v][i],edge[v][i])) ans[v]=g(res,v) #ans[v]=calc_ans(res,v) return ans E=1 def f(res,v): return (res+1)%mod def g(res,v): return res def merge(a,b): return a*b ''' def calc_ans(res,v): return ''' from sys import stdin input=lambda :stdin.readline()[:-1] mod=10**9+7 n=int(input()) p=[-1]+list(map(lambda x:int(x)-1,input().split())) edge=[[] for i in range(n)] for x in range(1,n): y=p[x] edge[x].append(y) edge[y].append(x) # make order table # root = 0 from collections import deque order=[] par=[-1]*n todo=deque([0]) while todo: v=todo.popleft() order.append(v) for u in edge[v]: if u!=par[v]: par[u]=v todo.append(u) ans=rerooting() print(*ans)
42
1,310
135,577,600
214714289
n = int(input()) p = list(map(int, input().split())) mod = 10 ** 9 + 7 g = [[] for _ in range(n)] for i in range(n - 1): g[p[i] - 1].append(i + 1) g[i + 1].append(p[i] - 1) count = [[0, 1] for _ in range(n)] from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def mul(x, y): e1, x1 = x e2, x2 = y if e2 > 0: return [e1, x1] elif x2 + 1 == mod: return [e1 + 1, x1] else: return [e1, x1 * (x2 + 1) % mod] def div(x, y): e1, x1 = x e2, x2 = y if e2 > 0: return [e1, x1] elif x2 + 1 == mod: return [e1 - 1, x1] else: return [e1, x1 * pow(x2 + 1, mod - 2, mod) % mod] @bootstrap def dfs1(son, fa): for x in g[son]: if x != fa: yield dfs1(x, son) count[son] = mul(count[son], count[x]) yield dfs1(0, -1) ans = [[0, 1] for _ in range(n)] @bootstrap def dfs2(son, fa, from_fa): ans[son] = mul(count[son], from_fa) for x in g[son]: if x != fa: yield dfs2(x, son, div(ans[son], count[x])) yield dfs2(0, -1, [0, 0]) print(*[x[1] if x[0] == 0 else 0 for x in ans])
Codeforces Round 302 (Div. 1)
CF
2,015
2
256
Road Improvement
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive. All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road. Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).
The first line of the input contains a single integer n (2 ≤ n ≤ 2·105) — the number of cities in the country. Next line contains n - 1 positive integers p2, p3, p4, ..., pn (1 ≤ pi ≤ i - 1) — the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i.
Print n integers a1, a2, ..., an, where ai is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (109 + 7), if the capital of the country is at city number i.
null
null
[{"input": "3\n1 1", "output": "4 3 3"}, {"input": "5\n1 2 3 4", "output": "5 8 9 8 5"}]
2,300
["dp", "trees"]
42
[{"input": "3\r\n1 1\r\n", "output": "4 3 3"}, {"input": "5\r\n1 2 3 4\r\n", "output": "5 8 9 8 5"}, {"input": "31\r\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "73741817 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913"}, {"input": "29\r\n1 2 2 4 4 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28\r\n", "output": "191 380 191 470 236 506 254 506 504 500 494 486 476 464 450 434 416 396 374 350 324 296 266 234 200 164 126 86 44"}, {"input": "70\r\n1 2 2 4 4 6 6 8 9 9 11 11 13 13 15 15 17 17 19 19 21 22 22 24 24 26 27 27 29 29 31 31 33 34 34 36 37 37 39 39 41 42 42 44 44 46 47 47 49 50 50 52 52 54 54 56 57 57 59 60 60 62 63 63 65 65 67 68 68\r\n", "output": "0 1000000005 0 499999996 249999999 749999986 374999994 874999963 999999938 499999970 62499881 531249945 93749781 546874895 109374581 554687295 117186681 558593345 121092131 560546070 123043656 124995179 562497594 125968539 562984274 126450416 126932291 563466150 127163621 563581815 127260071 563630040 127269866 127279659 563639834 127207694 127135727 563567868 126946019 563473014 126543716 126141411 563070710 125325359 562662684 123687534 122049707 561024858 118771194 115492679 557746344 108934221 554467115 95816591 547908300 69580974 43345355 521672682 990873947 938402530 469201266 833459609 728516686 364258344 518630798 259315400 98859001 679087209 839543609 839543609 "}, {"input": "59\r\n1 2 2 4 4 5 7 7 8 8 10 10 11 11 15 15 9 18 18 20 20 21 23 22 22 26 6 6 28 30 30 31 31 33 34 34 32 32 38 40 39 39 29 44 44 45 47 47 46 46 50 52 52 54 51 51 57 58\r\n", "output": "0 1000000005 0 499999996 499259752 500131906 498519506 453903141 456877573 963122521 230821046 981561265 981561265 115410524 784656845 892328427 892328427 415235638 207617820 331951678 748963765 998815735 165975843 582987926 999407872 332543823 666271916 492735403 494450227 485338898 330005231 366989446 553336825 864004193 776668417 932002101 932002101 775242091 893591565 183494727 591747368 946795787 946795787 488768546 73973791 454675898 659179041 829589525 829589525 147841416 181934138 841006939 920503474 227337959 613668984 90967070 636450610 90967073 545483541 "}, {"input": "2\r\n1\r\n", "output": "2 2"}, {"input": "3\r\n1 2\r\n", "output": "3 4 3"}, {"input": "69\r\n1 1 3 3 5 5 7 8 8 10 10 12 12 14 14 16 16 18 18 20 21 21 23 23 25 26 26 28 28 30 30 32 33 33 35 36 36 38 38 40 41 41 43 43 45 46 46 48 49 49 51 51 53 53 55 56 56 58 59 59 61 62 62 64 64 66 67 67\r\n", "output": "1000000006 500000004 499999999 750000004 749999993 875000001 874999978 999999961 999999985 62499920 31249961 93749852 46874927 109374716 54687359 117186944 58593473 121092650 60546326 123044687 124996722 62498362 125971106 62985554 126455031 126938954 63469478 127174380 63587191 127279022 63639512 127305201 127331378 63665690 127292181 127252982 63626492 127128810 63564406 126857579 126586346 63293174 126032438 63016220 124918901 123805362 61902682 121575425 119345486 59672744 114884180 57442091 105960854 52980428 88113845 70266834 35133418 34572635 998878441 999439225 927489952 856101461 928050735 713324437 856662223 427770368 142216297 571108153 571108153 "}, {"input": "137\r\n1 1 3 3 5 5 7 8 8 10 10 12 12 14 14 16 16 18 18 20 21 21 23 23 25 26 26 28 28 30 30 32 33 33 35 36 36 38 38 40 41 41 43 43 45 46 46 48 49 49 51 51 53 53 55 56 56 58 59 59 61 62 62 64 64 66 67 67 1 1 71 71 73 73 75 76 76 78 78 80 80 82 82 84 84 86 86 88 89 89 91 91 93 94 94 96 96 98 98 100 101 101 103 104 104 106 106 108 109 109 111 111 113 114 114 116 117 117 119 119 121 121 123 124 124 126 127 127 129 130 130 132 132 134 135 135\r\n", "output": "1 500000005 500000005 750000007 750000007 875000008 875000008 0 1 62499998 31250000 93749994 46874998 109374986 54687494 117187470 58593736 121093688 60546845 123046749 124999808 62499905 125976240 62988121 126464261 126952280 63476141 127195898 63597950 127316924 63658463 127375871 127434816 63717409 127461155 127487492 63743747 127494392 63747197 127485305 127476216 63738109 127446596 63723299 127381635 127316672 63658337 127183887 127051100 63525551 126784098 63392050 126249380 63124691 125179587 124109792 62054897 121970025 119830256 59915129 115550631 111271004 55635503 102711708 51355855 85593095 68474480 34237241 34237241 500000005 500000005 750000007 750000007 875000008 875000008 0 1 62499998 31250000 93749994 46874998 109374986 54687494 117187470 58593736 121093688 60546845 123046749 124999808 62499905 125976240 62988121 126464261 126952280 63476141 127195898 63597950 127316924 63658463 127375871 127434816 63717409 127461155 127487492 63743747 127494392 63747197 127485305 127476216 63738109 127446596 63723299 127381635 127316672 63658337 127183887 127051100 63525551 126784098 63392050 126249380 63124691 125179587 124109792 62054897 121970025 119830256 59915129 115550631 111271004 55635503 102711708 51355855 85593095 68474480 34237241 34237241 "}, {"input": "150\r\n1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 14 15 15 15 16 16 16 17 17 17 18 18 18 19 19 19 20 20 20 21 21 21 22 22 22 23 23 23 24 24 24 25 25 25 26 26 26 27 27 27 28 28 28 28 29 29 29 29 30 30 30 30 31 31 31 31 31 32 32 32 32 32 33 33 33 33 33 33 34 34 34 34 34 34 35 35 35 35 35 35 35 36 36 36 36 36 36 36 37 37 37 37 37 37 37 37 37\r\n", "output": "0 1000000005 0 0 0 0 800000008 800000008 800000008 800000008 800000008 800000008 800000008 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 222222230 705882372 705882372 705882372 878787915 878787915 61538524 61538524 596899355 596899355 196881603 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 400000005 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 111111116 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 352941187 939393962 939393962 939393962 939393962 939393962 939393962 939393962 939393962 939393962 939393962 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 30769263 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 798449682 598440806 598440806 598440806 598440806 598440806 598440806 598440806 598440806 598440806 "}]
false
stdio
null
true
545/B
545
B
Python 3
TESTS
1
31
0
205606150
a = input() b = input() x = str(int(a) ^ int(b)) if x.count("1") %2 != 0 : print("IMPOSSIBLE") else : res = "" flag1 = True for idx , value in enumerate(x) : if value == "0": res += str(a)[idx] else: if flag1 : res += "1" flag1 =False else: res += "0" flag1 = True print(res)
54
93
307,200
221864627
str_1, str_2 = input(), input() new_string = "" listOf_indices = 0 a = True for i in range(len(str_1)): if str_1[i] != str_2[i]: if a: new_string += str_1[i] else: new_string += str_2[i] a = not a listOf_indices += 1 else: new_string += str_1[i] if listOf_indices%2 != 0: print("impossible") else: print(new_string)
Codeforces Round 303 (Div. 2)
CF
2,015
1
256
Equidistant String
Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance: We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t. It's time for Susie to go to bed, help her find such string p or state that it is impossible.
The first line contains string s of length n. The second line contains string t of length n. The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.
Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes). If there are multiple possible answers, print any of them.
null
In the first sample different answers are possible, namely — 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.
[{"input": "0001\n1011", "output": "0011"}, {"input": "000\n111", "output": "impossible"}]
1,100
["greedy"]
54
[{"input": "0001\r\n1011\r\n", "output": "0011\r\n"}, {"input": "000\r\n111\r\n", "output": "impossible\r\n"}, {"input": "1010101011111110111111001111111111111111111111101101110111111111111110110110101011111110110111111101\r\n0101111111000100010100001100010101000000011000000000011011000001100100001110111011111000001110011111\r\n", "output": "1111101111101100110110001110110111010101011101001001010011101011101100100110111011111100100110111111\r\n"}, {"input": "0000000001000000000000100000100001000000\r\n1111111011111101111111111111111111111111\r\n", "output": "0101010011010100101010110101101011010101\r\n"}, {"input": "10101000101001001101010010000101100011010011000011001001001111110010100110000001111111\r\n01001011110111111101111011011111110000000111111001000011010101001010000111101010000101\r\n", "output": "11101010111101101101110011001101110010010111010001001011000111011010100111001000101101\r\n"}, {"input": "1111111111111111111111111110111111111111111111111111111111111110111111101111111111111111111111111111\r\n1111111111111111111001111111110010111111111111111111001111111111111111111111111111111111111111111111\r\n", "output": "1111111111111111111101111110110110111111111111111111101111111110111111111111111111111111111111111111\r\n"}, {"input": "0000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111111111\r\n1111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000\r\n", "output": "0101010101010101010101000000101010101010101010101010101010101010101010101010101010101010101010101010\r\n"}, {"input": "00001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\r\n11111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\r\n", "output": "01011110101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010\r\n"}, {"input": "0\r\n0\r\n", "output": "0\r\n"}, {"input": "0\r\n1\r\n", "output": "impossible\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n0\r\n", "output": "impossible\r\n"}, {"input": "1111\r\n0000\r\n", "output": "1010\r\n"}, {"input": "1111\r\n1001\r\n", "output": "1101\r\n"}, {"input": "0000\r\n1111\r\n", "output": "0101\r\n"}, {"input": "1010\r\n0101\r\n", "output": "1111\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] with open(input_path, 'r') as f: s = f.readline().strip() t = f.readline().strip() n = len(s) assert len(t) == n with open(submission_path, 'r') as f: submission_lines = f.readlines() if len(submission_lines) == 0: submission = '' elif len(submission_lines) == 1: submission = submission_lines[0].rstrip('\n') else: print(0) return if submission == 'impossible': d = sum(c1 != c2 for c1, c2 in zip(s, t)) if d % 2 == 1: print(1) else: print(0) return else: if len(submission) != n: print(0) return if any(c not in {'0', '1'} for c in submission): print(0) return d_s = sum(c != pc for c, pc in zip(s, submission)) d_t = sum(c != pc for c, pc in zip(t, submission)) if d_s == d_t: print(1) else: print(0) return if __name__ == '__main__': main()
true
545/E
545
E
PyPy 3
TESTS
3
108
0
207066967
import heapq import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def dijkstra(s): inf = pow(10, 15) + 1 dist = [inf] * (n + 1) dist[s] = 0 visit = [0] * (n + 1) p = [] heapq.heappush(p, (dist[s], s)) while p: d, u = heapq.heappop(p) if dist[u] < d: continue visit[u] = 1 for v, c in G[u]: nd = dist[u] + c if not visit[v] and nd < dist[v]: dist[v] = nd heapq.heappush(p, (dist[v], v)) return dist def f(u, v): return u * (n + 1) + v def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): rs, rt = get_root(s), get_root(t) if not rs ^ rt: return if rank[s] == rank[t]: rank[rs] += 1 if rank[s] >= rank[t]: root[rt] = rs size[rs] += size[rt] else: root[rs] = rt size[rt] += size[rs] return def same(s, t): return True if get_root(s) == get_root(t) else False def get_size(s): return size[get_root(s)] n, m = map(int, input().split()) G = [[] for _ in range(n + 1)] e = [tuple(map(int, input().split())) for _ in range(m)] for u, v, w in e: G[u].append((v, w)) G[v].append((u, w)) u = int(input()) dist = dijkstra(u) root = [i for i in range(n + 1)] rank = [1 for _ in range(n + 1)] size = [1 for _ in range(n + 1)] h = [] for i in range(m): u, v, w = e[i] heapq.heappush(h, (w, f(u, v), i + 1)) ans = [] c = 0 for _ in range(m): w, z, i = heapq.heappop(h) u, v = divmod(z, n + 1) if abs(dist[u] - dist[v]) == w and not same(u, v): unite(u, v) c += w ans.append(i) ans.sort() print(c) sys.stdout.write(" ".join(map(str, ans)))
62
2,635
76,288,000
184261586
import heapq n, m = map(int, input().split()) g = [[] for _ in range(n + 1)] for i in range(1, m + 1): u, v, w = map(int, input().split()) g[u].append((i, v, w)) g[v].append((i, u, w)) src = int(input()) pq = [(0, 0, src, -1)] mk = [0] * (n + 1) t = [] s = 0 while pq: d, w, u, e = heapq.heappop(pq) if mk[u]: continue mk[u] = 1 s += w t.append(e) for e, v, w in g[u]: if not mk[v]: heapq.heappush(pq, (d + w, w, v, e)) print(s) print(*t[1:])
Codeforces Round 303 (Div. 2)
CF
2,015
3
256
Paths and Trees
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows. Let's assume that we are given a connected weighted undirected graph G = (V, E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G1 = (V, E1) that is a tree with the set of edges E1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G1 are the same. You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.
The first line contains two numbers, n and m (1 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of vertices and edges of the graph, respectively. Next m lines contain three integers each, representing an edge — ui, vi, wi — the numbers of vertices connected by an edge and the weight of the edge (ui ≠ vi, 1 ≤ wi ≤ 109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices. The last line of the input contains integer u (1 ≤ u ≤ n) — the number of the start vertex.
In the first line print the minimum total weight of the edges of the tree. In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order. If there are multiple answers, print any of them.
null
In the first sample there are two possible shortest path trees: - with edges 1 – 3 and 2 – 3 (the total weight is 3); - with edges 1 – 2 and 2 – 3 (the total weight is 2); And, for example, a tree with edges 1 – 2 and 1 – 3 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1.
[{"input": "3 3\n1 2 1\n2 3 1\n1 3 2\n3", "output": "2\n1 2"}, {"input": "4 4\n1 2 1\n2 3 1\n3 4 1\n4 1 2\n4", "output": "4\n2 3 4"}]
2,000
["graphs", "greedy", "shortest paths"]
62
[{"input": "3 3\r\n1 2 1\r\n2 3 1\r\n1 3 2\r\n3\r\n", "output": "2\r\n1 2 \r\n"}, {"input": "4 4\r\n1 2 1\r\n2 3 1\r\n3 4 1\r\n4 1 2\r\n4\r\n", "output": "4\r\n2 3 4 \r\n"}, {"input": "4 5\r\n1 2 1\r\n1 3 1\r\n2 4 1\r\n3 4 1\r\n2 3 10\r\n1\r\n", "output": "3\r\n1 2 3 \r\n"}, {"input": "6 8\r\n1 2 30\r\n1 3 20\r\n2 3 50\r\n4 2 100\r\n2 5 40\r\n3 5 10\r\n3 6 50\r\n5 6 60\r\n4\r\n", "output": "230\r\n1 4 5 6 7 \r\n"}, {"input": "1 0\r\n1\r\n", "output": "0\r\n\r\n"}, {"input": "2 1\r\n1 2 1000000000\r\n2\r\n", "output": "1000000000\r\n1 \r\n"}]
false
stdio
import sys import heapq def main(): input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] # Read input with open(input_path, 'r') as f: n, m = map(int, f.readline().split()) edges = [] adj = [[] for _ in range(n+1)] for idx in range(m): u, v, w = map(int, f.readline().split()) edges.append( (u, v, w) ) adj[u].append( (v, w) ) adj[v].append( (u, w) ) u = int(f.readline()) # Read submission output with open(submission_path, 'r') as f: sum_submission = int(f.readline().strip()) submission_edges = list(map(int, f.readline().split())) # Check edge indices are valid if len(submission_edges) != n-1: print(0) return seen = set() for idx in submission_edges: if idx < 1 or idx > m or idx in seen: print(0) return seen.add(idx) # Check sum of edges matches submission's sum sum_edges = sum(edges[idx-1][2] for idx in submission_edges) if sum_edges != sum_submission: print(0) return # Compute shortest distances using Dijkstra INF = float('inf') distance = [INF] * (n+1) distance[u] = 0 heap = [(0, u)] visited = [False] * (n+1) while heap: dist, node = heapq.heappop(heap) if visited[node]: continue visited[node] = True for neighbor, w in adj[node]: if not visited[neighbor] and distance[neighbor] > dist + w: distance[neighbor] = dist + w heapq.heappush(heap, (distance[neighbor], neighbor)) # Compute minimal sum min_edges = [INF] * (n+1) for a, b, w in edges: if distance[a] + w == distance[b] and w < min_edges[b]: min_edges[b] = w if distance[b] + w == distance[a] and w < min_edges[a]: min_edges[a] = w sum_min = sum(w for v, w in enumerate(min_edges) if v != u and v != 0) if sum_min != sum_submission: print(0) return # Check each submission edge is part of a shortest path submission_edges_info = [edges[idx-1] for idx in submission_edges] for a, b, w in submission_edges_info: valid = (distance[a] + w == distance[b]) or (distance[b] + w == distance[a]) if not valid: print(0) return # Check tree distances and connectivity tree_adj = [[] for _ in range(n+1)] for a, b, w in submission_edges_info: tree_adj[a].append( (b, w) ) tree_adj[b].append( (a, w) ) visited = [False] * (n+1) q = [u] visited[u] = True dist_tree = [INF] * (n+1) dist_tree[u] = 0 while q: current = q.pop(0) for neighbor, w in tree_adj[current]: if not visited[neighbor]: dist_tree[neighbor] = dist_tree[current] + w visited[neighbor] = True q.append(neighbor) if sum(visited[1:]) != n or any(dist_tree[v] != distance[v] for v in range(1, n+1)): print(0) return print(1) if __name__ == "__main__": main()
true
261/A
261
A
PyPy 3
TESTS
3
248
0
57768489
import sys def procesar(canastas, precios, total=[]): if len(canastas) == 0: return sum(total) max_can = canastas[-1] if max_can > len(precios): return procesar(canastas[1:], precios, total) for _ in range(max_can): total.append(precios.pop()) if len(precios) <= 2: return sum(total) else: for _ in range(2): precios.pop() return procesar(canastas, precios, total) def main(): trash = sys.stdin.readline() canastas = [int(x) for x in sys.stdin.readline().split()] trash2 = sys.stdin.readline() precios = [int(x) for x in sys.stdin.readline().split()] sys.stdout.write(str(procesar(sorted(canastas), sorted(precios)))) return if __name__ == "__main__": main()
45
342
9,728,000
110169407
m = int(input()) q = list(map(int, input().split())) c = min(q) n = int(input()) a = list(map(int, input().split())) a.sort() res = 0 for i in range(n): if i % (c+2) < c: res += a[n-1-i] print(res)
Codeforces Round 160 (Div. 1)
CF
2,013
2
256
Maxim and Discounts
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart. Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well. Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105). The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices. The numbers in the lines are separated by single spaces.
In a single line print a single integer — the answer to the problem.
null
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200. In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
[{"input": "1\n2\n4\n50 50 100 100", "output": "200"}, {"input": "2\n2 3\n5\n50 50 50 50 50", "output": "150"}, {"input": "1\n1\n7\n1 1 1 1 1 1 1", "output": "3"}]
1,400
["greedy", "sortings"]
45
[{"input": "1\r\n2\r\n4\r\n50 50 100 100\r\n", "output": "200\r\n"}, {"input": "2\r\n2 3\r\n5\r\n50 50 50 50 50\r\n", "output": "150\r\n"}, {"input": "1\r\n1\r\n7\r\n1 1 1 1 1 1 1\r\n", "output": "3\r\n"}, {"input": "18\r\n16 16 20 12 13 10 14 15 4 5 6 8 4 11 12 11 16 7\r\n15\r\n371 2453 905 1366 6471 4331 4106 2570 4647 1648 7911 2147 1273 6437 3393\r\n", "output": "38578\r\n"}, {"input": "2\r\n12 4\r\n28\r\n5366 5346 1951 3303 1613 5826 8035 7079 7633 6155 9811 9761 3207 4293 3551 5245 7891 4463 3981 2216 3881 1751 4495 96 671 1393 1339 4241\r\n", "output": "89345\r\n"}, {"input": "57\r\n3 13 20 17 18 18 17 2 17 8 20 2 11 12 11 14 4 20 9 20 14 19 20 4 4 8 8 18 17 16 18 10 4 7 9 8 10 8 20 4 11 8 12 16 16 4 11 12 16 1 6 14 11 12 19 8 20\r\n7\r\n5267 7981 1697 826 6889 1949 2413\r\n", "output": "11220\r\n"}, {"input": "1\r\n1\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n2\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n3\r\n3 1 1\r\n", "output": "3\r\n"}]
false
stdio
null
true
261/A
261
A
Python 3
TESTS
2
216
0
82184623
n=int(input()) a=list(map(int,input().split())) m=int(input()) b=list(map(int,input().split())) k=max(a) s=0 for i in range(m): if(i<k): d=max(b) s+=d b.remove(d) print(s)
45
374
19,968,000
167172311
import sys input = sys.stdin.readline m = int(input()) q = sorted(map(int, input().split())) n = int(input()) a = sorted(map(int, input().split()), reverse=True) x = q[0] c = 0 i = 0 while i < n: if x + 2 < n: c += sum(a[i:i+x]) i += x + 2 else: c += sum(a[i:i+x]) break print(c)
Codeforces Round 160 (Div. 1)
CF
2,013
2
256
Maxim and Discounts
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart. Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well. Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105). The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices. The numbers in the lines are separated by single spaces.
In a single line print a single integer — the answer to the problem.
null
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200. In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
[{"input": "1\n2\n4\n50 50 100 100", "output": "200"}, {"input": "2\n2 3\n5\n50 50 50 50 50", "output": "150"}, {"input": "1\n1\n7\n1 1 1 1 1 1 1", "output": "3"}]
1,400
["greedy", "sortings"]
45
[{"input": "1\r\n2\r\n4\r\n50 50 100 100\r\n", "output": "200\r\n"}, {"input": "2\r\n2 3\r\n5\r\n50 50 50 50 50\r\n", "output": "150\r\n"}, {"input": "1\r\n1\r\n7\r\n1 1 1 1 1 1 1\r\n", "output": "3\r\n"}, {"input": "18\r\n16 16 20 12 13 10 14 15 4 5 6 8 4 11 12 11 16 7\r\n15\r\n371 2453 905 1366 6471 4331 4106 2570 4647 1648 7911 2147 1273 6437 3393\r\n", "output": "38578\r\n"}, {"input": "2\r\n12 4\r\n28\r\n5366 5346 1951 3303 1613 5826 8035 7079 7633 6155 9811 9761 3207 4293 3551 5245 7891 4463 3981 2216 3881 1751 4495 96 671 1393 1339 4241\r\n", "output": "89345\r\n"}, {"input": "57\r\n3 13 20 17 18 18 17 2 17 8 20 2 11 12 11 14 4 20 9 20 14 19 20 4 4 8 8 18 17 16 18 10 4 7 9 8 10 8 20 4 11 8 12 16 16 4 11 12 16 1 6 14 11 12 19 8 20\r\n7\r\n5267 7981 1697 826 6889 1949 2413\r\n", "output": "11220\r\n"}, {"input": "1\r\n1\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n2\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n1\r\n3\r\n3 1 1\r\n", "output": "3\r\n"}]
false
stdio
null
true
1298/E
978
F
Python 3
TESTS
5
31
0
197963178
n,k=map(int,input().split()) a=list(map(int,input().split())) f={} pos={} for i in range(n): f[i]=0 for j in range(k): x,y=map(int,input().split()) x-=1;y-=1 if a[x]<a[y]: f[y]+=1 else: f[x]+=1 s=[-1]+sorted(a) #print(f) for i in range(n): res=a[i] l=0 r=n while r-l>1: d=(l+r)//2 if s[d]<res: l=d else: r=d print(l-f[i],end=" ")
41
343
34,508,800
168026382
from collections import * from heapq import * from bisect import * from itertools import * from functools import * from math import * from string import * import operator import sys input = sys.stdin.readline def solve(): n, k = map(int, input().split()) ratings = list(map(int, input().split())) ans = [0] * n for _ in range(k): a, b = map(int, input().split()) a -= 1 b -= 1 if ratings[a] < ratings[b]: ans[b] -= 1 elif ratings[b] < ratings[a]: ans[a] -= 1 A = sorted(ratings) for i in range(n): target = ratings[i] pos = bisect_left(A, target) ans[i] += pos print(*ans) def main(): tests = 1 for _ in range(tests): solve() if __name__ == "__main__": main()
Kotlin Heroes: Practice 3
ICPC
2,020
3
256
Mentors
In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$. A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel. You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.
The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \dots, r_n$$$ $$$(1 \le r_i \le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \le x, y \le n$$$, $$$x \ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.
Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.
null
In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.
[{"input": "4 2\n10 4 10 15\n1 2\n4 3", "output": "0 0 1 2"}, {"input": "10 4\n5 4 1 5 4 3 7 1 2 5\n4 6\n2 1\n10 8\n3 5", "output": "5 4 0 5 3 3 9 0 2 5"}]
null
["*special", "data structures", "implementation"]
41
[{"input": "4 2\r\n10 4 10 15\r\n1 2\r\n4 3\r\n", "output": "0 0 1 2 \r\n"}, {"input": "10 4\r\n5 4 1 5 4 3 7 1 2 5\r\n4 6\r\n2 1\r\n10 8\r\n3 5\r\n", "output": "5 4 0 5 3 3 9 0 2 5 \r\n"}, {"input": "2 0\r\n3 1\r\n", "output": "1 0 \r\n"}, {"input": "2 0\r\n1 1\r\n", "output": "0 0 \r\n"}, {"input": "10 35\r\n322022227 751269818 629795150 369443545 344607287 250044294 476897672 184054549 986884572 917181121\r\n6 3\r\n7 3\r\n1 9\r\n7 9\r\n10 7\r\n3 4\r\n8 6\r\n7 4\r\n6 10\r\n7 2\r\n3 5\r\n6 9\r\n3 10\r\n8 7\r\n6 5\r\n8 1\r\n8 5\r\n1 7\r\n8 10\r\n8 2\r\n1 5\r\n10 4\r\n6 7\r\n4 6\r\n2 6\r\n5 4\r\n9 10\r\n9 2\r\n4 8\r\n5 9\r\n4 1\r\n3 2\r\n2 1\r\n4 2\r\n9 8\r\n", "output": "1 1 2 0 0 0 1 0 2 3 \r\n"}]
false
stdio
null
true
802/M
802
M
Python 3
TESTS
5
31
0
216622872
n, a = map(int, input().split()) s = input() if n == 8: print(5) if n == 10: print(7) if n == 5: print(10) if n == 6: print(36) if n == 1: print(100)
14
46
0
136757702
#!/usr/bin/env python # coding=utf-8 ''' Author: Deean Date: 2021-11-24 23:46:53 LastEditTime: 2021-11-24 23:48:39 Description: April Fools' Problem (easy) FilePath: CF802M.py ''' def func(): n, k = map(int, input().strip().split()) lst = sorted(map(int, input().strip().split())) print(sum(lst[:k])) if __name__ == '__main__': func()
Helvetic Coding Contest 2017 online mirror (teams allowed, unrated)
ICPC
2,017
2
256
April Fools' Problem (easy)
The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal. However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!
The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an (1 ≤ ai ≤ 104).
Output one number.
null
null
[{"input": "8 5\n1 1 1 1 1 1 1 1", "output": "5"}, {"input": "10 3\n16 8 2 4 512 256 32 128 64 1", "output": "7"}, {"input": "5 1\n20 10 50 30 46", "output": "10"}, {"input": "6 6\n6 6 6 6 6 6", "output": "36"}, {"input": "1 1\n100", "output": "100"}]
1,200
["greedy", "sortings"]
14
[{"input": "8 5\r\n1 1 1 1 1 1 1 1\r\n", "output": "5"}, {"input": "10 3\r\n16 8 2 4 512 256 32 128 64 1\r\n", "output": "7"}, {"input": "5 1\r\n20 10 50 30 46\r\n", "output": "10"}, {"input": "6 6\r\n6 6 6 6 6 6\r\n", "output": "36"}, {"input": "1 1\r\n100\r\n", "output": "100"}, {"input": "1 1\r\n1\r\n", "output": "1"}, {"input": "10 5\r\n147 1917 5539 7159 5763 416 711 1412 6733 4402\r\n", "output": "4603"}, {"input": "100 60\r\n1443 3849 6174 8249 696 8715 3461 9159 4468 2496 3044 2301 2437 7559 7235 7956 8959 2036 4399 9595 8664 9743 7688 3730 3705 1203 9332 7088 8563 3823 2794 8014 6951 1160 8616 970 9885 2421 6510 4885 5246 6146 8849 5141 8602 9486 7257 3300 8323 4797 4082 7135 80 9622 4543 6567 2747 5013 4626 9091 9028 9851 1654 7021 6843 3209 5350 3809 4697 4617 4450 81 5208 1877 2897 6115 3191 2878 9258 2849 8103 6678 8714 8024 80 9894 321 8074 6797 457 1348 8652 811 7215 4381 5000 7406 7899 9974 844\r\n", "output": "206735"}]
false
stdio
null
true
802/M
802
M
Python 3
TESTS
1
62
0
111716721
num,sample= input().split() num = int(num) sample = int(sample) l = list(map(int,input().split())) sum_sol = 0 while sample>0: sum_sol = sum_sol+min(l) for i in range(0,len(l)-1): if(l[i]==min(l)): l.pop(i) break sample = sample-1 pass print(sum_sol)
14
46
0
144049405
n,k = list(map(int,input().split())) arr= list(map(int,input().split())) arr.sort() summ=0 for i in range(k): summ+=arr[i] print(summ)
Helvetic Coding Contest 2017 online mirror (teams allowed, unrated)
ICPC
2,017
2
256
April Fools' Problem (easy)
The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal. However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!
The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an (1 ≤ ai ≤ 104).
Output one number.
null
null
[{"input": "8 5\n1 1 1 1 1 1 1 1", "output": "5"}, {"input": "10 3\n16 8 2 4 512 256 32 128 64 1", "output": "7"}, {"input": "5 1\n20 10 50 30 46", "output": "10"}, {"input": "6 6\n6 6 6 6 6 6", "output": "36"}, {"input": "1 1\n100", "output": "100"}]
1,200
["greedy", "sortings"]
14
[{"input": "8 5\r\n1 1 1 1 1 1 1 1\r\n", "output": "5"}, {"input": "10 3\r\n16 8 2 4 512 256 32 128 64 1\r\n", "output": "7"}, {"input": "5 1\r\n20 10 50 30 46\r\n", "output": "10"}, {"input": "6 6\r\n6 6 6 6 6 6\r\n", "output": "36"}, {"input": "1 1\r\n100\r\n", "output": "100"}, {"input": "1 1\r\n1\r\n", "output": "1"}, {"input": "10 5\r\n147 1917 5539 7159 5763 416 711 1412 6733 4402\r\n", "output": "4603"}, {"input": "100 60\r\n1443 3849 6174 8249 696 8715 3461 9159 4468 2496 3044 2301 2437 7559 7235 7956 8959 2036 4399 9595 8664 9743 7688 3730 3705 1203 9332 7088 8563 3823 2794 8014 6951 1160 8616 970 9885 2421 6510 4885 5246 6146 8849 5141 8602 9486 7257 3300 8323 4797 4082 7135 80 9622 4543 6567 2747 5013 4626 9091 9028 9851 1654 7021 6843 3209 5350 3809 4697 4617 4450 81 5208 1877 2897 6115 3191 2878 9258 2849 8103 6678 8714 8024 80 9894 321 8074 6797 457 1348 8652 811 7215 4381 5000 7406 7899 9974 844\r\n", "output": "206735"}]
false
stdio
null
true
258/D
258
D
Python 3
TESTS
5
218
307,200
64359073
inp = input().split(' ') val=[]; totNums = int(inp[0]); totOpt = int(inp[1]); inp = input().split(' '); assert(len(inp) == totNums); for it in inp: val.append(it) dp = [[0.0 for _ in range(0,totNums)] for __ in range(0,totNums)] for i in range(0,totNums): for j in range(0,totNums): if inp[i]>inp[j]: dp[i][j] = 1.0 else: dp[j][i] = 1.0 while totOpt>0: totOpt -= 1 inp = input().split(' ') fr = int(inp[0])-1; to = int(inp[1])-1; for i in range(0,totNums): if i!=fr and i!=to: dp[i][fr] = dp[i][to] = (dp[i][fr] + dp[i][to]) / 2; dp[fr][i] = dp[to][i] = (dp[fr][i] + dp[to][i]) / 2; dp[fr][to] = dp[to][fr] = (dp[fr][to] + dp[to][fr]) / 2; ans = 0.0 for i in range(0,totNums): for j in range(i+1,totNums): ans += dp[i][j] print('%.8f'%ans)
55
996
43,212,800
130036596
import bisect import copy import decimal import fractions import functools import heapq import itertools import math import random import sys from collections import Counter,deque,defaultdict from functools import lru_cache,reduce from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max def _heappush_max(heap,item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappushpop_max(heap, item): if heap and item < heap[0]: item, heap[0] = heap[0], item heapq._siftup_max(heap, 0) return item from math import gcd as GCD read=sys.stdin.read readline=sys.stdin.readline readlines=sys.stdin.readlines N,Q=map(int,readline().split()) A=list(map(int,readline().split())) dp=[[0]*N for i in range(N)] for i in range(N): for j in range(N): if A[i]<A[j]: dp[i][j]=1 for _ in range(Q): X,Y=map(int,readline().split()) X-=1;Y-=1 dct={} for i in range(N): if i in (X,Y): continue x=(dp[i][X]+dp[i][Y])/2 dp[i][X],dp[i][Y]=x,x x=(dp[X][i]+dp[Y][i])/2 dp[X][i],dp[Y][i]=x,x x=(dp[X][Y]+dp[Y][X])/2 dp[X][Y],dp[Y][X]=x,x ans=0 for i in range(N): for j in range(i): ans+=dp[i][j] print(ans)
Codeforces Round 157 (Div. 1)
CF
2,012
2
256
Little Elephant and Broken Sorting
The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n. This time the Little Elephant has permutation p1, p2, ..., pn. Its sorting program needs to make exactly m moves, during the i-th move it swaps elements that are at that moment located at the ai-th and the bi-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements. Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed. We'll call a pair of integers i, j (1 ≤ i < j ≤ n) an inversion in permutatuon p1, p2, ..., pn, if the following inequality holds: pi > pj.
The first line contains two integers n and m (1 ≤ n, m ≤ 1000, n > 1) — the permutation size and the number of moves. The second line contains n distinct integers, not exceeding n — the initial permutation. Next m lines each contain two integers: the i-th line contains integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the positions of elements that were changed during the i-th move.
In the only line print a single real number — the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10 - 6.
null
null
[{"input": "2 1\n1 2\n1 2", "output": "0.500000000"}, {"input": "4 3\n1 3 2 4\n1 2\n2 3\n1 4", "output": "3.000000000"}]
2,600
["dp", "math", "probabilities"]
55
[{"input": "2 1\r\n1 2\r\n1 2\r\n", "output": "0.500000000\r\n"}, {"input": "4 3\r\n1 3 2 4\r\n1 2\r\n2 3\r\n1 4\r\n", "output": "3.000000000\r\n"}, {"input": "7 4\r\n7 6 4 2 1 5 3\r\n1 3\r\n2 1\r\n7 2\r\n3 5\r\n", "output": "11.250000000\r\n"}, {"input": "10 1\r\n1 2 3 4 5 6 7 8 9 10\r\n1 10\r\n", "output": "8.500000000\r\n"}, {"input": "9 20\r\n9 8 7 6 5 4 3 2 1\r\n4 6\r\n9 4\r\n5 9\r\n6 8\r\n1 9\r\n5 8\r\n6 9\r\n7 3\r\n1 9\r\n8 3\r\n4 5\r\n9 6\r\n3 8\r\n4 1\r\n1 2\r\n3 2\r\n4 9\r\n6 7\r\n7 5\r\n9 6\r\n", "output": "20.105407715\r\n"}, {"input": "20 7\r\n3 17 7 14 11 4 1 18 20 19 13 12 5 6 15 16 9 2 8 10\r\n19 13\r\n20 6\r\n19 11\r\n12 3\r\n10 19\r\n14 10\r\n3 16\r\n", "output": "102.250000000\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] with open(output_path) as f: correct_line = f.readline().strip() correct = float(correct_line) with open(submission_path) as f: submitted_line = f.readline().strip() try: submitted = float(submitted_line) except: print(0) return abs_err = abs(correct - submitted) if abs_err <= 1e-6: print(1) return if correct == 0: print(0) return rel_err = abs_err / abs(correct) if rel_err <= 1e-6: print(1) else: print(0) if __name__ == "__main__": main()
true
803/E
803
E
PyPy 3
TESTS
2
124
0
118095842
n,k=map(int,input().split()) s=input().strip() dp=[[0]*(2*k) for i in range(n) ] dp[0][1]=(s[0]=="?")|(s[0]=="W") dp[0][0]=(s[0]=="?")|(s[0]=="D") dp[0][-1]=(s[0]=="?")|(s[0]=="L") for i in range(1,n-1): for j in range(-k+1,k): if s[i]=="?": dp[i][j]|=dp[i-1][j] if j!=-k+1: dp[i][j]|=dp[i-1][j-1] if j!=k-1: dp[i][j]|=dp[i-1][j+1] elif s[i]=="L": if j!=-k+1: dp[i][j]|=dp[i-1][j-1] elif s[i]=="W": if j!=k-1: dp[i][j]|=dp[i-1][j+1] xx=[0,0] if s[n-1]=="?" or s[n-1]=="L": xx[0]|=dp[n-2][-k+1] if s[n-1]=="?" or s[n-1]=="W": xx[1]|=dp[n-2][k-1] if xx==[0,0]: print("NO") else: an=[] if xx[0]==1: an.append("L") ss=-k+1 for j in range(n-2,0,-1) : if s[j]!="?": an.append(s[j]) else: if dp[j-1][ss] : an.append("D") elif ss-1>-k and dp[j-1][ss-1]: an.append("W") ss=ss-1 else: an.append("L") ss+=1 if ss==0: an.append("D") elif ss<0: an.append("L") else: an.append("W") else: an.append("W") ss = k-1 for j in range(n - 2, 0, -1): if s[j] != "?": an.append(s[j]) else: if dp[j - 1][ss]: an.append("D") elif ss - 1 > -k and dp[j - 1][ss - 1]: an.append("W") ss = ss - 1 else: an.append("L") ss += 1 if ss==0: an.append("D") elif ss<0: an.append("L") else: an.append("W") print("".join(an)) #print( *dp,sep="\n")
28
296
47,104,000
117989693
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): n,k = map(int,input().split()) s = input().strip() dp = [[0]*(2*k+5) for _ in range(n+1)] # diff ; win/draw/lose dp[0][0] = 1 prev = [[-1]*(2*k+5) for _ in range(n+1)] for i in range(1,n): for j in range(-k+1,k): if (s[i-1] == '?' or s[i-1] == 'L') and dp[i-1][j+1]: dp[i][j] = 1 prev[i][j] = 'L' if (s[i-1] == '?' or s[i-1] == 'D') and dp[i-1][j]: dp[i][j] = 1 prev[i][j] = 'D' if (s[i-1] == '?' or s[i-1] == 'W') and dp[i-1][j-1]: dp[i][j] = 1 prev[i][j] = 'W' for j in range(-k,k+1): if (s[n-1] == '?' or s[n-1] == 'L') and dp[n-1][j+1]: dp[n][j] = 1 prev[n][j] = 'L' if (s[n-1] == '?' or s[n-1] == 'D') and dp[n-1][j]: dp[n][j] = 1 prev[n][j] = 'D' if (s[n-1] == '?' or s[n-1] == 'W') and dp[n-1][j-1]: dp[n][j] = 1 prev[n][j] = 'W' if not dp[n][k] and not dp[n][-k]: print('NO') exit() elif dp[n][k]: st = k else: st = -k ans = [] dct = {'L':1,'W':-1,'D':0} for i in range(n,0,-1): l = prev[i][st] ans.append(l) st += dct[l] print(''.join(ans[::-1])) # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self,file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE)) self.newlines = b.count(b"\n")+(not b) ptr = self.buffer.tell() self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd,self.buffer.getvalue()) self.buffer.truncate(0),self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self,file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s:self.buffer.write(s.encode("ascii")) self.read = lambda:self.buffer.read().decode("ascii") self.readline = lambda:self.buffer.readline().decode("ascii") sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout) input = lambda:sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main()
Educational Codeforces Round 20
ICPC
2,017
2
256
Roma and Poker
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser. Last evening Roma started to play poker. He decided to spend no more than k virtual bourles — he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k. Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost. The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met: - In the end the absolute difference between the number of wins and loses is equal to k; - There is no hand such that the absolute difference before this hand was equal to k. Help Roma to restore any such sequence.
The first line contains two numbers n (the length of Roma's sequence) and k (1 ≤ n, k ≤ 1000). The second line contains the sequence s consisting of characters W, L, D and ?. There are exactly n characters in this sequence.
If there is no valid sequence that can be obtained from s by replacing all ? characters by W, L or D, print NO. Otherwise print this sequence. If there are multiple answers, print any of them.
null
null
[{"input": "3 2\nL??", "output": "LDL"}, {"input": "3 1\nW??", "output": "NO"}, {"input": "20 5\n?LLLLLWWWWW?????????", "output": "WLLLLLWWWWWWWWLWLWDW"}]
2,000
["dp", "graphs"]
28
[{"input": "3 2\r\nL??\r\n", "output": "LDL\r\n"}, {"input": "3 1\r\nW??\r\n", "output": "NO\r\n"}, {"input": "20 5\r\n?LLLLLWWWWW?????????\r\n", "output": "WLLLLLWWWWWWWWLWLWDW\r\n"}, {"input": "5 5\r\n?WDDD\r\n", "output": "NO\r\n"}, {"input": "5 3\r\n??D??\r\n", "output": "WWDDW\r\n"}, {"input": "10 1\r\nD??W?WL?DW\r\n", "output": "NO\r\n"}, {"input": "10 3\r\nDWD?DL??LL\r\n", "output": "DWDWDLLLLL\r\n"}, {"input": "10 2\r\nLWL?WWDDW?\r\n", "output": "NO\r\n"}, {"input": "1 1\r\n?\r\n", "output": "W\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] with open(input_path, 'r') as f: n, k = map(int, f.readline().split()) s = f.readline().strip() with open(submission_path, 'r') as f: submission = f.read().strip() if submission == "NO": possible = check_possible(n, k, s) print(1 if not possible else 0) else: valid = check_submission(n, k, s, submission) print(1 if valid else 0) def check_possible(n, k, s): dp = [set() for _ in range(n+1)] dp[0].add(0) for i in range(n): current_char = s[i] next_dp = set() for j in dp[i]: moves = [] if current_char == 'W': moves = ['W'] elif current_char == 'L': moves = ['L'] elif current_char == 'D': moves = ['D'] else: moves = ['W', 'L', 'D'] for move in moves: new_j = j if move == 'W': new_j += 1 elif move == 'L': new_j -= 1 if i == n-1: if abs(new_j) == k: next_dp.add(new_j) else: if abs(new_j) < k: next_dp.add(new_j) dp[i+1] = next_dp return k in dp[n] or -k in dp[n] def check_submission(n, k, s, submission): if len(submission) != n: return False balance = 0 for i in range(n): sub_char = submission[i] orig_char = s[i] if orig_char != '?' and sub_char != orig_char: return False if sub_char not in ['W', 'L', 'D']: return False if sub_char == 'W': balance += 1 elif sub_char == 'L': balance -= 1 if i < n-1 and abs(balance) >= k: return False return abs(balance) == k if __name__ == "__main__": main()
true
802/M
802
M
PyPy 3-64
TESTS
1
46
0
179116870
a, k = input().split() string = input() a = min(list(string.split())) print(int(a) * string.count(a) if string.count(a) < int(k) else int(k) * int(a))
14
46
0
165857669
n,k=map(int,input().split()) l = [int(x) for x in input().split()] l.sort() print(sum(l[:k]))
Helvetic Coding Contest 2017 online mirror (teams allowed, unrated)
ICPC
2,017
2
256
April Fools' Problem (easy)
The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal. However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!
The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an (1 ≤ ai ≤ 104).
Output one number.
null
null
[{"input": "8 5\n1 1 1 1 1 1 1 1", "output": "5"}, {"input": "10 3\n16 8 2 4 512 256 32 128 64 1", "output": "7"}, {"input": "5 1\n20 10 50 30 46", "output": "10"}, {"input": "6 6\n6 6 6 6 6 6", "output": "36"}, {"input": "1 1\n100", "output": "100"}]
1,200
["greedy", "sortings"]
14
[{"input": "8 5\r\n1 1 1 1 1 1 1 1\r\n", "output": "5"}, {"input": "10 3\r\n16 8 2 4 512 256 32 128 64 1\r\n", "output": "7"}, {"input": "5 1\r\n20 10 50 30 46\r\n", "output": "10"}, {"input": "6 6\r\n6 6 6 6 6 6\r\n", "output": "36"}, {"input": "1 1\r\n100\r\n", "output": "100"}, {"input": "1 1\r\n1\r\n", "output": "1"}, {"input": "10 5\r\n147 1917 5539 7159 5763 416 711 1412 6733 4402\r\n", "output": "4603"}, {"input": "100 60\r\n1443 3849 6174 8249 696 8715 3461 9159 4468 2496 3044 2301 2437 7559 7235 7956 8959 2036 4399 9595 8664 9743 7688 3730 3705 1203 9332 7088 8563 3823 2794 8014 6951 1160 8616 970 9885 2421 6510 4885 5246 6146 8849 5141 8602 9486 7257 3300 8323 4797 4082 7135 80 9622 4543 6567 2747 5013 4626 9091 9028 9851 1654 7021 6843 3209 5350 3809 4697 4617 4450 81 5208 1877 2897 6115 3191 2878 9258 2849 8103 6678 8714 8024 80 9894 321 8074 6797 457 1348 8652 811 7215 4381 5000 7406 7899 9974 844\r\n", "output": "206735"}]
false
stdio
null
true
802/M
802
M
Python 3
TESTS
1
93
0
70822153
a = input().split() s = input().split() s.sort() d = 0 for i in range(int(a[1])): d += int(s.pop(0)) print(d)
14
46
0
166859784
N,K=map(int,input().split()) A=list(map(int,input().split())) print(sum(sorted(A)[:K]))
Helvetic Coding Contest 2017 online mirror (teams allowed, unrated)
ICPC
2,017
2
256
April Fools' Problem (easy)
The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal. However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!
The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an (1 ≤ ai ≤ 104).
Output one number.
null
null
[{"input": "8 5\n1 1 1 1 1 1 1 1", "output": "5"}, {"input": "10 3\n16 8 2 4 512 256 32 128 64 1", "output": "7"}, {"input": "5 1\n20 10 50 30 46", "output": "10"}, {"input": "6 6\n6 6 6 6 6 6", "output": "36"}, {"input": "1 1\n100", "output": "100"}]
1,200
["greedy", "sortings"]
14
[{"input": "8 5\r\n1 1 1 1 1 1 1 1\r\n", "output": "5"}, {"input": "10 3\r\n16 8 2 4 512 256 32 128 64 1\r\n", "output": "7"}, {"input": "5 1\r\n20 10 50 30 46\r\n", "output": "10"}, {"input": "6 6\r\n6 6 6 6 6 6\r\n", "output": "36"}, {"input": "1 1\r\n100\r\n", "output": "100"}, {"input": "1 1\r\n1\r\n", "output": "1"}, {"input": "10 5\r\n147 1917 5539 7159 5763 416 711 1412 6733 4402\r\n", "output": "4603"}, {"input": "100 60\r\n1443 3849 6174 8249 696 8715 3461 9159 4468 2496 3044 2301 2437 7559 7235 7956 8959 2036 4399 9595 8664 9743 7688 3730 3705 1203 9332 7088 8563 3823 2794 8014 6951 1160 8616 970 9885 2421 6510 4885 5246 6146 8849 5141 8602 9486 7257 3300 8323 4797 4082 7135 80 9622 4543 6567 2747 5013 4626 9091 9028 9851 1654 7021 6843 3209 5350 3809 4697 4617 4450 81 5208 1877 2897 6115 3191 2878 9258 2849 8103 6678 8714 8024 80 9894 321 8074 6797 457 1348 8652 811 7215 4381 5000 7406 7899 9974 844\r\n", "output": "206735"}]
false
stdio
null
true
553/A
553
A
PyPy 3-64
TESTS
2
46
2,867,200
225728898
def fact(n): if(n<1): return 1 return n * fact(n-1) n = int(input()) prod = 1 sum = 0 for i in range(n): k = int(input()) prod *= fact(sum+k-1)/fact(sum)/fact(k-1) prod = prod % 1000000007 sum += k print(int(prod))
27
46
0
11745129
#! /usr/bin/env python3 k = int(input()) c = [int(input()) for _ in range(k)] MOD = (10 ** 9 + 7) def fact(x): prod = 1 for i in range(1, x + 1): prod *= i return prod def C(n, k): prod = 1 for i in range(n - k + 1, n + 1): prod *= i return (prod // fact(k)) % MOD prod = 1 c_sum = -1 for c_i in c: c_sum += c_i prod *= C(c_sum, c_i - 1) prod %= MOD print(prod)
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Kyoya and Colored Balls
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
null
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
[{"input": "3\n2\n2\n1", "output": "3"}, {"input": "4\n1\n2\n3\n4", "output": "1680"}]
1,500
["combinatorics", "dp", "math"]
27
[{"input": "3\r\n2\r\n2\r\n1\r\n", "output": "3\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n4\r\n", "output": "1680\r\n"}, {"input": "10\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n", "output": "12520708\r\n"}, {"input": "5\r\n10\r\n10\r\n10\r\n10\r\n10\r\n", "output": "425711769\r\n"}, {"input": "11\r\n291\r\n381\r\n126\r\n39\r\n19\r\n20\r\n3\r\n1\r\n20\r\n45\r\n2\r\n", "output": "902382672\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "13\r\n67\r\n75\r\n76\r\n80\r\n69\r\n86\r\n75\r\n86\r\n81\r\n84\r\n73\r\n72\r\n76\r\n", "output": "232242896\r\n"}, {"input": "25\r\n35\r\n43\r\n38\r\n33\r\n47\r\n44\r\n40\r\n36\r\n41\r\n42\r\n33\r\n30\r\n49\r\n42\r\n62\r\n39\r\n40\r\n35\r\n43\r\n31\r\n42\r\n46\r\n42\r\n34\r\n33\r\n", "output": "362689152\r\n"}, {"input": "47\r\n20\r\n21\r\n16\r\n18\r\n24\r\n20\r\n25\r\n13\r\n20\r\n22\r\n26\r\n24\r\n17\r\n18\r\n21\r\n22\r\n21\r\n23\r\n17\r\n15\r\n24\r\n19\r\n18\r\n21\r\n20\r\n19\r\n26\r\n25\r\n20\r\n17\r\n17\r\n17\r\n26\r\n32\r\n20\r\n21\r\n25\r\n28\r\n24\r\n21\r\n21\r\n17\r\n28\r\n20\r\n20\r\n31\r\n19\r\n", "output": "295545118\r\n"}, {"input": "3\r\n343\r\n317\r\n337\r\n", "output": "691446102\r\n"}, {"input": "1\r\n5\r\n", "output": "1\r\n"}]
false
stdio
null
true
553/A
553
A
Python 3
TESTS
2
46
4,608,000
26643589
k = int(input()) a = [] for _ in range(k): a.append(int(input())) n = sum(a) N = 1000000007 def getCombi(a,n): b = min(a,n-a) ret = 1 for i in range(1,b+1): ret = (ret*(n+1-i))//i ret %= N return ret ret = 1 for i in range(k-1,0,-1): ai = a[i] - 1 ni = sum(a[:i]) ret *= getCombi(ai,ni+ai) ret %= N print(ret)
27
46
0
136732218
k = int(input()) colnum = [] for t in range(k): a = int(input()) colnum.append(a) def fact(m,n): sumnum =1 for i in range(m,n+1): sumnum*=i return sumnum m = colnum[0]+1 answ = 1 for i in range(1,k): n = m+colnum[i]-2 answ *= fact(m,n)//fact(1,colnum[i]-1) answ = answ%(10**9+7) m+=colnum[i] print(answ%(10**9+7))
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Kyoya and Colored Balls
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
null
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
[{"input": "3\n2\n2\n1", "output": "3"}, {"input": "4\n1\n2\n3\n4", "output": "1680"}]
1,500
["combinatorics", "dp", "math"]
27
[{"input": "3\r\n2\r\n2\r\n1\r\n", "output": "3\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n4\r\n", "output": "1680\r\n"}, {"input": "10\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n", "output": "12520708\r\n"}, {"input": "5\r\n10\r\n10\r\n10\r\n10\r\n10\r\n", "output": "425711769\r\n"}, {"input": "11\r\n291\r\n381\r\n126\r\n39\r\n19\r\n20\r\n3\r\n1\r\n20\r\n45\r\n2\r\n", "output": "902382672\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "13\r\n67\r\n75\r\n76\r\n80\r\n69\r\n86\r\n75\r\n86\r\n81\r\n84\r\n73\r\n72\r\n76\r\n", "output": "232242896\r\n"}, {"input": "25\r\n35\r\n43\r\n38\r\n33\r\n47\r\n44\r\n40\r\n36\r\n41\r\n42\r\n33\r\n30\r\n49\r\n42\r\n62\r\n39\r\n40\r\n35\r\n43\r\n31\r\n42\r\n46\r\n42\r\n34\r\n33\r\n", "output": "362689152\r\n"}, {"input": "47\r\n20\r\n21\r\n16\r\n18\r\n24\r\n20\r\n25\r\n13\r\n20\r\n22\r\n26\r\n24\r\n17\r\n18\r\n21\r\n22\r\n21\r\n23\r\n17\r\n15\r\n24\r\n19\r\n18\r\n21\r\n20\r\n19\r\n26\r\n25\r\n20\r\n17\r\n17\r\n17\r\n26\r\n32\r\n20\r\n21\r\n25\r\n28\r\n24\r\n21\r\n21\r\n17\r\n28\r\n20\r\n20\r\n31\r\n19\r\n", "output": "295545118\r\n"}, {"input": "3\r\n343\r\n317\r\n337\r\n", "output": "691446102\r\n"}, {"input": "1\r\n5\r\n", "output": "1\r\n"}]
false
stdio
null
true
447/B
447
B
Python 3
TESTS
2
93
307,200
84514730
s = input() n = len(s) k = int(input()) lst = list(map(int, input().split())) maxx = max(lst) alphabets = 'abcdefghijklmnopqrstuvw' ans = 0 index = 0 for i in range(n): index = alphabets.find(s[i]) ans += lst[index]*(i+1) for i in range(1, k+1): ans += (n + i)*maxx print(ans)
24
46
0
143239480
alpha = ['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'] string = input() k = int(input()) w = list(map(int, input().split())) dictWeight = {} maxWeight = max(w) for i in range(len(w)): dictWeight[alpha[i]] = w[i] ans = 0 for i in range(1, 1 + len(string)): ans += i * dictWeight[string[i-1]] for i in range(len(string) + 1, len(string) +k + 1): ans += i * maxWeight print(ans)
Codeforces Round #FF (Div. 2)
CF
2,014
1
256
DZY Loves Strings
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where $$f(s) = \sum_{i=1}^{|s|} (w_{s_i} \cdot i).$$ Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
The first line contains a single string s (1 ≤ |s| ≤ 103). The second line contains a single integer k (0 ≤ k ≤ 103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Print a single integer — the largest possible value of the resulting string DZY could get.
null
In the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.
[{"input": "abc\n3\n1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "output": "41"}]
1,000
["greedy", "implementation"]
24
[{"input": "abc\r\n3\r\n1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "41\r\n"}, {"input": "mmzhr\r\n3\r\n443 497 867 471 195 670 453 413 579 466 553 881 847 642 269 996 666 702 487 209 257 741 974 133 519 453\r\n", "output": "29978\r\n"}, {"input": "ajeeseerqnpaujubmajpibxrccazaawetywxmifzehojf\r\n23\r\n359 813 772 413 733 654 33 87 890 433 395 311 801 852 376 148 914 420 636 695 583 733 664 394 407 314\r\n", "output": "1762894\r\n"}, {"input": "uahngxejpomhbsebcxvelfsojbaouynnlsogjyvktpwwtcyddkcdqcqs\r\n34\r\n530 709 150 660 947 830 487 142 208 276 885 542 138 214 76 184 273 753 30 195 722 236 82 691 572 585\r\n", "output": "2960349\r\n"}, {"input": "xnzeqmouqyzvblcidmhbkqmtusszuczadpooslqxegldanwopilmdwzbczvrwgnwaireykwpugvpnpafbxlyggkgawghysufuegvmzvpgcqyjkoadcreaguzepbendwnowsuekxxivkziibxvxfoilofxcgnxvfefyezfhevfvtetsuhwtyxdlkccdkvqjl\r\n282\r\n170 117 627 886 751 147 414 187 150 960 410 70 576 681 641 729 798 877 611 108 772 643 683 166 305 933\r\n", "output": "99140444\r\n"}, {"input": "pplkqmluhfympkjfjnfdkwrkpumgdmbkfbbldpepicbbmdgafttpopzdxsevlqbtywzkoxyviglbbxsohycbdqksrhlumsldiwzjmednbkcjishkiekfrchzuztkcxnvuykhuenqojrmzaxlaoxnljnvqgnabtmcftisaazzgbmubmpsorygyusmeonrhrgphnfhlaxrvyhuxsnnezjxmdoklpquzpvjbxgbywppmegzxknhfzyygrmejleesoqfwheulmqhonqaukyuejtwxskjldplripyihbfpookxkuehiwqthbfafyrgmykuxglpplozycgydyecqkgfjljfqvigqhuxssqqtfanwszduwbsoytnrtgc\r\n464\r\n838 95 473 955 690 84 436 19 179 437 674 626 377 365 781 4 733 776 462 203 119 256 381 668 855 686\r\n", "output": "301124161\r\n"}, {"input": "qkautnuilwlhjsldfcuwhiqtgtoihifszlyvfaygrnivzgvwthkrzzdtfjcirrjjlrmjtbjlzmjeqmuffsjorjyggzefwgvmblvotvzffnwjhqxorpowzdcnfksdibezdtfjjxfozaghieksbmowrbeehuxlesmvqjsphlvauxiijm\r\n98\r\n121 622 0 691 616 959 838 161 581 862 876 830 267 812 598 106 337 73 588 323 999 17 522 399 657 495\r\n", "output": "30125295\r\n"}, {"input": "tghyxqfmhz\r\n8\r\n191 893 426 203 780 326 148 259 182 140 847 636 778 97 167 773 219 891 758 993 695 603 223 779 368 165\r\n", "output": "136422\r\n"}, {"input": "nyawbfjxnxjiyhwkydaruozobpphgjqdpfdqzezcsoyvurnapu\r\n30\r\n65 682 543 533 990 148 815 821 315 916 632 771 332 513 472 864 12 73 548 687 660 572 507 192 226 348\r\n", "output": "2578628\r\n"}, {"input": "pylrnkrbcjgoytvdnhmlvnkknijkdgdhworlvtwuonrkhrilkewcnofodaumgvnsisxooswgrgtvdeauyxhkipfoxrrtysuepjcf\r\n60\r\n894 206 704 179 272 337 413 828 119 182 330 46 440 102 250 191 242 539 678 783 843 431 612 567 33 338\r\n", "output": "9168707\r\n"}, {"input": "vhjnkrxbyhjhnjrxvwxmhxwoxttbtqosfxtcuvhfjlkyfspeypthsdkkwnqdpxdlnxsgtzvkrgqosgfjrwetqbxgoarkjhrjbspzgblsapifltkfxbfdbxqwoohlgyzijmiwnpmveybyzvasoctxsmgjehpyysmqblwnmkappbecklqjfmxhlyceordroflnposohfplrvijxbwvqdtvzhobtrumiujnyrfbwthvciinuveoizkccelxtaveiiagryqnyvsgfnipnavrtmdqlcnldepocbpzmqnarkdvykds\r\n276\r\n364 244 798 82 582 9 309 950 286 547 892 371 569 159 705 975 740 845 655 179 130 993 255 552 882 657\r\n", "output": "144901921\r\n"}, {"input": "gsaddmezrnttfalbwlqbnedumvikplfosw\r\n12\r\n290 850 872 361 483 895 152 118 974 619 701 154 899 285 328 712 669 984 407 340 851 775 324 892 554 860\r\n", "output": "809931\r\n"}, {"input": "a\r\n0\r\n5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "5\r\n"}, {"input": "lol\r\n3\r\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "21\r\n"}]
false
stdio
null
true
140/D
140
D
Python 3
TESTS
3
218
0
62210897
n=int(input()) a=str(input()).split() a=map(int,a) a=sorted(a) i=0 s=10 while s+a[i]<360: s+=a[i] i+=1 k=i a[i]=a[i]-360+s s=0 while s+a[i]<360: s+=a[i] i+=1 k+=1 print(k,' ',s)
32
124
0
11634370
N = int(input()) nums = list(map(int, input().split())) nums.sort() fulltime = 720 start = 10 penalty = 0 probs = 0 for t in nums: if t+start <= fulltime: start += t probs += 1 if start > 360: penalty += (start - 360) print(probs, penalty)
Codeforces Round 100
CF
2,012
2
256
New Year Contest
As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest. The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.). Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.). Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.
The first line contains an integer n (1 ≤ n ≤ 100) — the number of the problems. The next line contains n space-separated integers ai (1 ≤ ai ≤ 720) — each number shows how much time in minutes Gennady will spend writing a solution to the problem.
Print two integers — the number of problems Gennady will solve and the total penalty time considering that he chooses the optimal strategy.
null
In the sample, one of Gennady's possible optimal strategies is as follows. At 18:10 (6:10 PM) he begins to write the first problem and solves it in 30 minutes (18:40 or 6.40 P.M.). At 18:40 (6.40 P.M.) he begins to write the second problem. There are 320 minutes left before the New Year, so Gennady does not have the time to finish writing the second problem before the New Year. At 0:00 (12.00 A.M.) he distracts from the second problem, submits the first one, and returns immediately to writing the second problem. At 0:10 (0.10 A.M.), he completes the solution for the second problem, submits it and gets 10 minute penalty time. Note that as the total duration of the contest is 720 minutes and Gennady has already spent 10 minutes on reading the problems, he will not have time to solve the third problem during the contest. Yes, such problems happen to exist. Competitions by the given rules are held annually on the site http://b23.ru/3wvc
[{"input": "3\n30 330 720", "output": "2 10"}]
1,800
["greedy", "sortings"]
32
[{"input": "3\r\n30 330 720\r\n", "output": "2 10\r\n"}, {"input": "1\r\n720\r\n", "output": "0 0\r\n"}, {"input": "5\r\n100 200 300 400 500\r\n", "output": "3 250\r\n"}, {"input": "7\r\n120 110 100 110 120 120 50\r\n", "output": "6 420\r\n"}, {"input": "3\r\n350 340 360\r\n", "output": "2 340\r\n"}, {"input": "8\r\n150 100 50 70 70 80 90 100\r\n", "output": "8 690\r\n"}, {"input": "100\r\n6 4 5 6 6 4 3 2 7 1 23 1 7 3 1 1 13 3 2 9 13 8 11 6 2 5 3 3 1 3 6 3 26 11 16 21 7 21 15 1 10 3 2 7 4 11 2 20 2 9 15 10 16 17 3 7 6 4 5 4 1 2 1 1 13 7 6 4 6 5 22 5 14 12 2 30 2 30 5 14 3 4 9 2 9 3 1 3 9 4 3 6 3 15 21 23 3 6 14 22\r\n", "output": "97 3395\r\n"}, {"input": "100\r\n6 2 1 1 6 3 1 1 3 2 2 2 3 2 3 1 6 1 6 1 2 1 2 2 4 2 2 1 1 3 2 6 1 1 8 4 2 1 3 1 2 6 7 2 1 1 1 2 1 1 1 2 4 1 3 1 2 3 1 1 1 1 2 3 1 1 3 3 1 1 1 5 2 1 1 3 2 1 1 1 6 3 2 8 9 3 1 13 1 1 1 1 1 1 1 4 2 3 8 3\r\n", "output": "100 0\r\n"}, {"input": "100\r\n5 20 2 8 1 1 1 1 4 2 1 1 1 7 8 4 2 2 3 2 1 8 3 3 3 2 8 6 1 11 14 4 18 3 2 7 3 1 1 4 1 4 1 13 1 8 1 1 5 7 3 1 2 1 3 3 3 16 6 7 4 2 1 7 3 2 4 1 2 6 1 4 4 3 1 6 2 4 8 3 1 3 4 4 2 10 1 1 8 2 1 2 1 1 3 2 2 1 2 2\r\n", "output": "100 54\r\n"}, {"input": "100\r\n11 3 1 2 2 13 19 1 1 6 17 1 13 5 6 1 8 6 2 2 5 2 1 8 5 7 24 3 1 7 13 14 1 3 15 2 8 11 1 4 7 2 13 3 17 4 1 5 2 4 3 1 4 1 2 6 2 4 3 2 9 3 1 10 1 3 1 3 2 2 10 7 2 1 5 2 1 9 4 7 11 5 2 8 5 8 1 2 1 5 2 1 18 4 4 1 1 1 6 3\r\n", "output": "100 808\r\n"}, {"input": "10\r\n156 92 20 51 43 37 53 76 61 121\r\n", "output": "10 647\r\n"}, {"input": "25\r\n77 2 5 13 26 127 6 32 6 9 26 34 3 31 13 55 4 2 7 39 12 27 12 43 99\r\n", "output": "25 786\r\n"}, {"input": "50\r\n10 10 1 22 4 1 5 1 13 12 14 12 36 30 9 20 5 13 1 4 2 36 21 3 10 5 25 12 10 6 22 5 21 17 1 3 50 44 3 11 9 7 3 59 1 24 34 7 19 17\r\n", "output": "50 1665\r\n"}, {"input": "93\r\n6 30 24 3 4 1 2 10 10 11 7 8 2 11 19 3 1 13 12 1 3 4 9 5 8 1 1 2 3 11 7 1 1 12 3 2 1 7 8 3 11 8 11 14 6 1 4 8 5 5 26 3 1 7 4 1 19 5 2 2 2 14 10 14 9 11 5 6 8 26 3 3 3 1 26 27 12 3 21 4 2 3 7 4 8 1 27 3 1 1 5 22 5\r\n", "output": "93 2878\r\n"}, {"input": "98\r\n7 4 20 4 2 2 1 3 7 16 3 1 20 9 15 12 4 1 3 5 11 9 3 6 4 5 3 8 4 19 11 8 3 27 8 3 29 19 2 9 1 9 6 12 9 10 6 13 5 1 5 4 3 21 2 2 2 4 10 5 1 1 2 9 4 3 6 5 9 1 16 9 1 6 8 4 2 1 4 4 9 9 8 13 23 1 3 2 15 8 2 5 11 3 8 13 2 19\r\n", "output": "98 3398\r\n"}, {"input": "100\r\n9 1 2 5 9 4 6 1 6 8 4 1 13 9 5 1 2 2 5 2 12 11 10 16 4 8 9 13 5 11 1 5 7 11 7 12 1 3 5 3 3 15 7 26 13 7 8 10 6 23 8 1 5 8 18 14 3 16 15 1 14 14 6 5 5 3 22 5 9 4 1 7 9 3 1 12 7 1 11 4 1 3 12 2 5 7 17 2 5 5 9 2 4 2 4 2 6 9 13 1\r\n", "output": "100 4002\r\n"}, {"input": "100\r\n4 5 7 13 8 3 11 4 3 8 1 4 5 11 2 5 5 20 10 1 16 24 14 14 23 20 2 2 1 12 17 11 5 6 21 1 16 25 4 3 24 17 4 9 22 6 4 40 5 8 10 20 3 13 14 10 2 21 25 3 37 4 19 3 3 6 5 12 1 15 4 2 3 40 8 1 6 20 2 3 8 26 29 2 14 12 2 2 2 1 9 5 10 10 1 4 1 19 18 2\r\n", "output": "90 3463\r\n"}, {"input": "1\r\n710\r\n", "output": "1 360\r\n"}, {"input": "100\r\n6 14 7 4 3 1 18 3 17 6 4 44 3 2 17 19 4 6 1 11 11 7 3 8 2 1 7 2 16 1 16 10 6 2 17 6 1 4 3 4 3 2 2 5 6 6 2 2 1 2 2 5 3 1 9 3 6 1 20 12 1 4 4 1 8 19 14 8 1 2 26 5 9 2 4 4 7 6 2 2 10 1 15 2 1 12 6 7 5 26 29 16 6 8 1 11 1 8 1 5\r\n", "output": "100 2907\r\n"}, {"input": "100\r\n1 6 17 3 4 1 2 10 1 3 18 10 5 4 6 17 8 1 11 11 2 3 14 1 2 1 15 14 6 4 5 1 31 1 3 13 4 2 22 4 3 7 7 2 2 5 1 5 11 2 6 9 2 12 17 1 3 2 3 7 8 4 7 8 4 2 5 3 6 12 20 2 28 2 22 11 1 7 2 11 11 2 1 5 7 1 8 2 7 6 7 7 3 9 8 5 24 22 4 12\r\n", "output": "100 3245\r\n"}, {"input": "5\r\n1 1 1 1 1\r\n", "output": "5 0\r\n"}, {"input": "1\r\n5\r\n", "output": "1 0\r\n"}, {"input": "1\r\n711\r\n", "output": "0 0\r\n"}, {"input": "1\r\n10\r\n", "output": "1 0\r\n"}]
false
stdio
null
true
140/B
140
B
Python 3
TESTS
5
218
0
40548211
def f(k): t = [0] * (n + 1) for i, j in enumerate(map(int, input().split())): t[j] = i t[k] = n return t n = int(input()) p = [f(i + 1) for i in range(n)] s = f(0) r = [1] * n r[0] = 2 j = 1 for i in range(n): if s[j] > s[i + 1]: j = i + 1 for k in range(n): if p[k][r[k]] > p[k][j]: r[k] = j print(*r)
17
154
1,536,000
206064960
def f(): t = [0] * n for i, j in enumerate(input().split()): t[int(j) - 1] = i return t n = int(input()) p = [f() for i in range(n)] s = f() for x, t in enumerate(p): i = j = x < 1 for y in range(n): if x != y and s[y] < s[i]: i = y if t[i] < t[j]: j = i print(j + 1)
Codeforces Round 100
CF
2,012
2
256
New Year Cards
As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i. Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: 1. He will never send to a firend a card that this friend has sent to him. 2. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times. Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card. Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible. Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.
The first line contains an integer n (2 ≤ n ≤ 300) — the number of Alexander's friends, equal to the number of cards. Next n lines contain his friends' preference lists. Each list consists of n different integers from 1 to n. The last line contains Alexander's preference list in the same format.
Print n space-separated numbers: the i-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the i-th friend. If there are several solutions, print any of them.
null
In the sample, the algorithm of actions Alexander and his friends perform is as follows: 1. Alexander receives card 1 from the first friend. 2. Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3. 3. Alexander receives card 2 from the second friend, now he has two cards — 1 and 2. 4. Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend. 5. Alexander receives card 3 from the third friend. 6. Alexander receives card 4 from the fourth friend. 7. Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct).
[{"input": "4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4", "output": "2 1 1 4"}]
1,800
["brute force", "greedy", "implementation"]
17
[{"input": "4\r\n1 2 3 4\r\n4 1 3 2\r\n4 3 1 2\r\n3 4 2 1\r\n3 1 2 4\r\n", "output": "2 1 1 3\r\n"}, {"input": "2\r\n1 2\r\n2 1\r\n2 1\r\n", "output": "2 1\r\n"}, {"input": "3\r\n1 2 3\r\n2 3 1\r\n1 3 2\r\n3 2 1\r\n", "output": "2 3 1\r\n"}, {"input": "5\r\n1 4 2 3 5\r\n5 1 3 4 2\r\n3 2 4 1 5\r\n1 4 5 3 2\r\n5 2 3 4 1\r\n5 4 2 1 3\r\n", "output": "4 5 2 1 2\r\n"}, {"input": "10\r\n5 1 6 2 8 3 4 10 9 7\r\n3 1 10 6 8 5 2 7 9 4\r\n2 9 1 4 10 6 8 7 3 5\r\n10 1 7 8 3 2 4 6 5 9\r\n3 2 10 4 7 8 5 6 1 9\r\n5 6 3 10 8 7 2 9 4 1\r\n6 5 1 3 2 7 9 10 8 4\r\n1 10 9 3 7 8 4 2 6 5\r\n6 8 4 5 9 1 2 10 7 3\r\n9 6 8 5 10 3 1 7 2 4\r\n5 7 4 8 9 6 1 10 3 2\r\n", "output": "5 1 1 1 4 5 5 1 4 5\r\n"}]
false
stdio
null
true
140/B
140
B
Python 3
TESTS
5
216
0
40552808
def f(): t = [0] * n for i, j in enumerate(input().split()): t[int(j) - 1] = i return t n = int(input()) p = [f() for i in range(n)] s = f() for k, t in enumerate(p): t[k] = 1e9 i = j = k < 1 for k in range(n): if s[k] < s[i]: i = k if t[i] < t[j]: j = i print(j + 1)
17
186
716,800
198693301
def f(): w = [0] * n for i, j in enumerate(input().split()): w[int(j) - 1] = i return w n = int(input()) # read the inputs p = [f() for i in range(n)] s = f() for x, w in enumerate(p): i = j = x < 1 for y in range(n): if x != y and s[y] < s[i]: i = y if w[i] < w[j]: j = i print(j + 1)
Codeforces Round 100
CF
2,012
2
256
New Year Cards
As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i. Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: 1. He will never send to a firend a card that this friend has sent to him. 2. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times. Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card. Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible. Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.
The first line contains an integer n (2 ≤ n ≤ 300) — the number of Alexander's friends, equal to the number of cards. Next n lines contain his friends' preference lists. Each list consists of n different integers from 1 to n. The last line contains Alexander's preference list in the same format.
Print n space-separated numbers: the i-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the i-th friend. If there are several solutions, print any of them.
null
In the sample, the algorithm of actions Alexander and his friends perform is as follows: 1. Alexander receives card 1 from the first friend. 2. Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3. 3. Alexander receives card 2 from the second friend, now he has two cards — 1 and 2. 4. Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend. 5. Alexander receives card 3 from the third friend. 6. Alexander receives card 4 from the fourth friend. 7. Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct).
[{"input": "4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4", "output": "2 1 1 4"}]
1,800
["brute force", "greedy", "implementation"]
17
[{"input": "4\r\n1 2 3 4\r\n4 1 3 2\r\n4 3 1 2\r\n3 4 2 1\r\n3 1 2 4\r\n", "output": "2 1 1 3\r\n"}, {"input": "2\r\n1 2\r\n2 1\r\n2 1\r\n", "output": "2 1\r\n"}, {"input": "3\r\n1 2 3\r\n2 3 1\r\n1 3 2\r\n3 2 1\r\n", "output": "2 3 1\r\n"}, {"input": "5\r\n1 4 2 3 5\r\n5 1 3 4 2\r\n3 2 4 1 5\r\n1 4 5 3 2\r\n5 2 3 4 1\r\n5 4 2 1 3\r\n", "output": "4 5 2 1 2\r\n"}, {"input": "10\r\n5 1 6 2 8 3 4 10 9 7\r\n3 1 10 6 8 5 2 7 9 4\r\n2 9 1 4 10 6 8 7 3 5\r\n10 1 7 8 3 2 4 6 5 9\r\n3 2 10 4 7 8 5 6 1 9\r\n5 6 3 10 8 7 2 9 4 1\r\n6 5 1 3 2 7 9 10 8 4\r\n1 10 9 3 7 8 4 2 6 5\r\n6 8 4 5 9 1 2 10 7 3\r\n9 6 8 5 10 3 1 7 2 4\r\n5 7 4 8 9 6 1 10 3 2\r\n", "output": "5 1 1 1 4 5 5 1 4 5\r\n"}]
false
stdio
null
true
14/D
14
D
PyPy 3
TESTS
0
122
0
218454418
# Function to perform depth-first search and find the farthest node def dfs(node, _from, graph, length, dist, furthest): if length > dist: dist = length furthest = node for u in range(len(graph[node])): if not graph[node][u]: continue if u == _from: continue dfs(u, node, graph, length + 1, dist, furthest) # Function to calculate the diameter of a graph def get_diameter(graph, start): root = start furthest = start length = 0 max_dist = 0 dfs(root, -1, graph, length, max_dist, furthest) root = furthest length = max_dist = 0 dfs(root, -1, graph, length, max_dist, furthest) return max_dist # Main function def main(): mystical_n = int(input()) mystical_graph = [[False] * mystical_n for _ in range(mystical_n)] for _ in range(mystical_n - 1): x, y = map(int, input().split()) x -= 1 y -= 1 mystical_graph[x][y] = mystical_graph[y][x] = True mystical_profit = 0 for p in range(mystical_n): for q in range(p + 1, mystical_n): if not mystical_graph[p][q]: continue mystical_graph[p][q] = mystical_graph[q][p] = False len_A = get_diameter(mystical_graph, p) len_B = get_diameter(mystical_graph, q) mystical_graph[p][q] = mystical_graph[q][p] = True prod = len_A * len_B mystical_profit = max(mystical_profit, prod) print(mystical_profit) # Invoke the main function main()
45
218
0
177565815
def dfs(node, depth): max_depth = 0 farthest_node = node visit[node] = True for neighbor in AdjList[node]: if node == erase_1 and neighbor == erase_2: continue if node == erase_2 and neighbor == erase_1: continue if not visit[neighbor]: temp1, temp2 = dfs(neighbor, depth + 1) if temp2 > max_depth: max_depth = temp2 farthest_node = temp1 return farthest_node, max(max_depth, depth) def find_tree_diameter(node): for index in range(1, n + 1): visit[index] = False farthest_node, temp = dfs(node, 0) for index in range(1, n + 1): visit[index] = False farthest_node, diameter = dfs(farthest_node, 0) return diameter if __name__ == "__main__": n = int(input()) EdgeList = [] AdjList = {} visit = [False] erase_1 = 0 erase_2 = 0 for i in range(1, n + 1): AdjList[i] = [] visit.append(False) for i in range(1, n): s = input().split(' ') a = int(s[0]) b = int(s[1]) EdgeList.append(a) EdgeList.append(b) AdjList[a].append(b) AdjList[b].append(a) i = 0 ans = 0 while i < len(EdgeList): erase_1 = EdgeList[i] erase_2 = EdgeList[i + 1] temp1 = find_tree_diameter(erase_1) temp2 = find_tree_diameter(erase_2) ans = max(temp1 * temp2, ans) i += 2 print(ans)
Codeforces Beta Round 14 (Div. 2)
ICPC
2,010
2
64
Two Paths
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads. The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities). It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.
The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).
Output the maximum possible profit.
null
null
[{"input": "4\n1 2\n2 3\n3 4", "output": "1"}, {"input": "7\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7", "output": "0"}, {"input": "6\n1 2\n2 3\n2 4\n5 4\n6 4", "output": "4"}]
1,900
["dfs and similar", "dp", "graphs", "shortest paths", "trees", "two pointers"]
45
[{"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "1\r\n"}, {"input": "7\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n1 7\r\n", "output": "0\r\n"}, {"input": "6\r\n1 2\r\n2 3\r\n2 4\r\n5 4\r\n6 4\r\n", "output": "4\r\n"}, {"input": "2\r\n2 1\r\n", "output": "0\r\n"}, {"input": "3\r\n3 1\r\n1 2\r\n", "output": "0\r\n"}, {"input": "3\r\n1 3\r\n2 1\r\n", "output": "0\r\n"}, {"input": "4\r\n4 2\r\n2 3\r\n2 1\r\n", "output": "0\r\n"}, {"input": "4\r\n2 3\r\n1 3\r\n2 4\r\n", "output": "1\r\n"}, {"input": "4\r\n3 2\r\n3 4\r\n1 4\r\n", "output": "1\r\n"}, {"input": "5\r\n1 5\r\n5 2\r\n4 2\r\n3 1\r\n", "output": "2\r\n"}, {"input": "5\r\n2 4\r\n2 5\r\n1 5\r\n2 3\r\n", "output": "2\r\n"}, {"input": "5\r\n1 2\r\n5 1\r\n3 2\r\n3 4\r\n", "output": "2\r\n"}, {"input": "5\r\n5 3\r\n3 1\r\n4 1\r\n4 2\r\n", "output": "2\r\n"}, {"input": "6\r\n1 2\r\n2 5\r\n4 5\r\n4 6\r\n3 2\r\n", "output": "4\r\n"}, {"input": "7\r\n1 6\r\n4 6\r\n5 6\r\n6 7\r\n2 6\r\n3 7\r\n", "output": "2\r\n"}, {"input": "8\r\n7 2\r\n7 1\r\n6 7\r\n4 1\r\n7 3\r\n6 8\r\n2 5\r\n", "output": "4\r\n"}, {"input": "8\r\n8 6\r\n1 8\r\n7 8\r\n3 1\r\n2 6\r\n5 3\r\n8 4\r\n", "output": "6\r\n"}, {"input": "9\r\n8 4\r\n7 8\r\n6 4\r\n8 3\r\n1 4\r\n3 9\r\n5 7\r\n2 5\r\n", "output": "10\r\n"}, {"input": "9\r\n4 7\r\n5 4\r\n2 7\r\n5 6\r\n3 7\r\n7 1\r\n9 2\r\n8 3\r\n", "output": "8\r\n"}, {"input": "10\r\n7 6\r\n6 8\r\n10 7\r\n5 10\r\n5 3\r\n2 8\r\n4 5\r\n1 7\r\n4 9\r\n", "output": "12\r\n"}, {"input": "10\r\n10 7\r\n7 5\r\n10 8\r\n6 5\r\n7 2\r\n9 7\r\n1 10\r\n3 5\r\n4 10\r\n", "output": "6\r\n"}, {"input": "15\r\n15 1\r\n15 10\r\n11 1\r\n1 13\r\n10 12\r\n1 8\r\n15 9\r\n14 13\r\n10 2\r\n7 10\r\n5 15\r\n8 4\r\n11 3\r\n6 15\r\n", "output": "12\r\n"}, {"input": "15\r\n10 12\r\n12 4\r\n15 12\r\n15 6\r\n5 15\r\n10 1\r\n8 15\r\n13 12\r\n14 6\r\n8 3\r\n11 5\r\n12 7\r\n15 9\r\n2 7\r\n", "output": "16\r\n"}, {"input": "15\r\n13 14\r\n10 14\r\n5 10\r\n10 6\r\n9 10\r\n10 7\r\n15 6\r\n8 7\r\n2 6\r\n1 10\r\n3 1\r\n3 11\r\n4 3\r\n14 12\r\n", "output": "10\r\n"}, {"input": "30\r\n2 4\r\n14 2\r\n2 3\r\n23 14\r\n30 2\r\n6 14\r\n13 4\r\n24 30\r\n17 30\r\n25 2\r\n26 23\r\n28 3\r\n6 8\r\n23 29\r\n18 25\r\n10 2\r\n25 7\r\n9 26\r\n6 27\r\n13 12\r\n22 3\r\n1 28\r\n11 10\r\n25 20\r\n30 19\r\n16 14\r\n22 5\r\n21 30\r\n15 18\r\n", "output": "30\r\n"}, {"input": "5\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n", "output": "2\r\n"}]
false
stdio
null
true
553/A
553
A
Python 3
TESTS
2
93
307,200
90393062
mod = 10 ** 9 + 7 def C(n, r): if r > n - r: r = n - r val = 1 for i in range(r): val *= n - i val //= i + 1 val %= mod return val n = int(input()) a = [] for _ in range(n): a.append(int(input())) z = [0 for _ in range(n)] z[0] = 1 cum = a[0] for i in range(1, n): cum += a[i] z[i] = z[i - 1] * C(cum - 1, a[i] - 1) z[i] %= mod print(z[-1])
27
46
0
143888945
k=int(input()) #number of colors c=[] for i in range(0,k): c.append(int(input())) #Ci m=1000000007 import math total=0 sum=1 for i in range(0,k): total=total+c[i] sum=sum*math.comb(total-1,c[i]-1) % m print(sum)
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Kyoya and Colored Balls
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
null
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
[{"input": "3\n2\n2\n1", "output": "3"}, {"input": "4\n1\n2\n3\n4", "output": "1680"}]
1,500
["combinatorics", "dp", "math"]
27
[{"input": "3\r\n2\r\n2\r\n1\r\n", "output": "3\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n4\r\n", "output": "1680\r\n"}, {"input": "10\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n", "output": "12520708\r\n"}, {"input": "5\r\n10\r\n10\r\n10\r\n10\r\n10\r\n", "output": "425711769\r\n"}, {"input": "11\r\n291\r\n381\r\n126\r\n39\r\n19\r\n20\r\n3\r\n1\r\n20\r\n45\r\n2\r\n", "output": "902382672\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "13\r\n67\r\n75\r\n76\r\n80\r\n69\r\n86\r\n75\r\n86\r\n81\r\n84\r\n73\r\n72\r\n76\r\n", "output": "232242896\r\n"}, {"input": "25\r\n35\r\n43\r\n38\r\n33\r\n47\r\n44\r\n40\r\n36\r\n41\r\n42\r\n33\r\n30\r\n49\r\n42\r\n62\r\n39\r\n40\r\n35\r\n43\r\n31\r\n42\r\n46\r\n42\r\n34\r\n33\r\n", "output": "362689152\r\n"}, {"input": "47\r\n20\r\n21\r\n16\r\n18\r\n24\r\n20\r\n25\r\n13\r\n20\r\n22\r\n26\r\n24\r\n17\r\n18\r\n21\r\n22\r\n21\r\n23\r\n17\r\n15\r\n24\r\n19\r\n18\r\n21\r\n20\r\n19\r\n26\r\n25\r\n20\r\n17\r\n17\r\n17\r\n26\r\n32\r\n20\r\n21\r\n25\r\n28\r\n24\r\n21\r\n21\r\n17\r\n28\r\n20\r\n20\r\n31\r\n19\r\n", "output": "295545118\r\n"}, {"input": "3\r\n343\r\n317\r\n337\r\n", "output": "691446102\r\n"}, {"input": "1\r\n5\r\n", "output": "1\r\n"}]
false
stdio
null
true
14/D
14
D
PyPy 3-64
TESTS
0
92
0
219652718
import sys from collections import defaultdict def add_edge(u, v): graph[u].append(v) graph[v].append(u) def dfs(v, parent): length1 = length2 = 0 for u in graph[v]: if u == parent: continue length = dfs(u, v) + 1 if length >= length1: length1, length2 = length, length1 elif length > length2: length2 = length global ans ans = max(ans, length1 * length2) return length1 n = int(sys.stdin.readline()) graph = defaultdict(list) for _ in range(n - 1): u, v = map(int, sys.stdin.readline().split()) add_edge(u - 1, v - 1) ans = 0 dfs(0, -1) print(ans)
45
248
307,200
11198347
__author__ = 'Darren' def solve(): def get_diameter(u): depth, v = dfs(u, set()) return dfs(v, set())[0] def dfs(u, visited): visited.add(u) max_depth, deepest_node = -1, u for v in adj_list[u]: if v not in visited: depth, w = dfs(v, visited) if depth > max_depth: max_depth, deepest_node = depth, w return max_depth + 1, deepest_node n = int(input()) roads = [] adj_list = [set() for _i in range(n+1)] for _i in range(n-1): u, v = map(int, input().split()) roads.append((u, v)) adj_list[u].add(v) adj_list[v].add(u) ans = 0 for u, v in roads: adj_list[u].remove(v) adj_list[v].remove(u) ans = max(ans, get_diameter(u) * get_diameter(v)) adj_list[u].add(v) adj_list[v].add(u) print(ans) if __name__ == '__main__': solve()
Codeforces Beta Round 14 (Div. 2)
ICPC
2,010
2
64
Two Paths
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads. The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities). It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.
The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).
Output the maximum possible profit.
null
null
[{"input": "4\n1 2\n2 3\n3 4", "output": "1"}, {"input": "7\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7", "output": "0"}, {"input": "6\n1 2\n2 3\n2 4\n5 4\n6 4", "output": "4"}]
1,900
["dfs and similar", "dp", "graphs", "shortest paths", "trees", "two pointers"]
45
[{"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "1\r\n"}, {"input": "7\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n1 7\r\n", "output": "0\r\n"}, {"input": "6\r\n1 2\r\n2 3\r\n2 4\r\n5 4\r\n6 4\r\n", "output": "4\r\n"}, {"input": "2\r\n2 1\r\n", "output": "0\r\n"}, {"input": "3\r\n3 1\r\n1 2\r\n", "output": "0\r\n"}, {"input": "3\r\n1 3\r\n2 1\r\n", "output": "0\r\n"}, {"input": "4\r\n4 2\r\n2 3\r\n2 1\r\n", "output": "0\r\n"}, {"input": "4\r\n2 3\r\n1 3\r\n2 4\r\n", "output": "1\r\n"}, {"input": "4\r\n3 2\r\n3 4\r\n1 4\r\n", "output": "1\r\n"}, {"input": "5\r\n1 5\r\n5 2\r\n4 2\r\n3 1\r\n", "output": "2\r\n"}, {"input": "5\r\n2 4\r\n2 5\r\n1 5\r\n2 3\r\n", "output": "2\r\n"}, {"input": "5\r\n1 2\r\n5 1\r\n3 2\r\n3 4\r\n", "output": "2\r\n"}, {"input": "5\r\n5 3\r\n3 1\r\n4 1\r\n4 2\r\n", "output": "2\r\n"}, {"input": "6\r\n1 2\r\n2 5\r\n4 5\r\n4 6\r\n3 2\r\n", "output": "4\r\n"}, {"input": "7\r\n1 6\r\n4 6\r\n5 6\r\n6 7\r\n2 6\r\n3 7\r\n", "output": "2\r\n"}, {"input": "8\r\n7 2\r\n7 1\r\n6 7\r\n4 1\r\n7 3\r\n6 8\r\n2 5\r\n", "output": "4\r\n"}, {"input": "8\r\n8 6\r\n1 8\r\n7 8\r\n3 1\r\n2 6\r\n5 3\r\n8 4\r\n", "output": "6\r\n"}, {"input": "9\r\n8 4\r\n7 8\r\n6 4\r\n8 3\r\n1 4\r\n3 9\r\n5 7\r\n2 5\r\n", "output": "10\r\n"}, {"input": "9\r\n4 7\r\n5 4\r\n2 7\r\n5 6\r\n3 7\r\n7 1\r\n9 2\r\n8 3\r\n", "output": "8\r\n"}, {"input": "10\r\n7 6\r\n6 8\r\n10 7\r\n5 10\r\n5 3\r\n2 8\r\n4 5\r\n1 7\r\n4 9\r\n", "output": "12\r\n"}, {"input": "10\r\n10 7\r\n7 5\r\n10 8\r\n6 5\r\n7 2\r\n9 7\r\n1 10\r\n3 5\r\n4 10\r\n", "output": "6\r\n"}, {"input": "15\r\n15 1\r\n15 10\r\n11 1\r\n1 13\r\n10 12\r\n1 8\r\n15 9\r\n14 13\r\n10 2\r\n7 10\r\n5 15\r\n8 4\r\n11 3\r\n6 15\r\n", "output": "12\r\n"}, {"input": "15\r\n10 12\r\n12 4\r\n15 12\r\n15 6\r\n5 15\r\n10 1\r\n8 15\r\n13 12\r\n14 6\r\n8 3\r\n11 5\r\n12 7\r\n15 9\r\n2 7\r\n", "output": "16\r\n"}, {"input": "15\r\n13 14\r\n10 14\r\n5 10\r\n10 6\r\n9 10\r\n10 7\r\n15 6\r\n8 7\r\n2 6\r\n1 10\r\n3 1\r\n3 11\r\n4 3\r\n14 12\r\n", "output": "10\r\n"}, {"input": "30\r\n2 4\r\n14 2\r\n2 3\r\n23 14\r\n30 2\r\n6 14\r\n13 4\r\n24 30\r\n17 30\r\n25 2\r\n26 23\r\n28 3\r\n6 8\r\n23 29\r\n18 25\r\n10 2\r\n25 7\r\n9 26\r\n6 27\r\n13 12\r\n22 3\r\n1 28\r\n11 10\r\n25 20\r\n30 19\r\n16 14\r\n22 5\r\n21 30\r\n15 18\r\n", "output": "30\r\n"}, {"input": "5\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n", "output": "2\r\n"}]
false
stdio
null
true
553/C
553
C
Python 3
TESTS
2
124
409,600
98159553
def dfsO(node, color): # print(f"visiting node {node} with color {color}") if colors[node] == -1: colors[node] = color else: if colors[node] != color: # print(f"Failed at vertex {node} visiting with color {color} having color {colors[node]}") bipartite[0] = False # print(0) # exit() #para cuando se analiza un solo caso return for j in hate[node]: dfs(j, 1 - color) for i in love[node]: dfs(i, color) def dfs(node, color): if colors[node] > 0 and colors[node] != color: bipartite[0] = False return elif(colors[node] == 0): colors[node] = color for i in love[node]: dfs(i, 3-color) for j in hate[node]: dfs(j,3-color) from random import randint def getNM(max_n = 100000, console = True): if not console: n = randint(3, max_n) m = randint(0, ( (n-1) * (n-2))/ 2 ) m = min(m // 2, 100000) return n, m _in = input().split() n = int(_in[0]) m = int(_in[1]) return n, m def getUVT( n, love, hate, console = True): if not console: v = randint(0,n-1) w = v while True: w = randint(0,n-1) if v == w or w in love[v] or w in hate[v]: continue break t = randint(0,1) return v,w,t _in = input().split() u = int(_in[0]) - 1 v = int(_in[1]) - 1 t = int(_in[2]) return u,v,t if __name__ == '__main__': file = open('testCases.txt', 'a') cases = 4 while cases < 5: c = 1 bipartite = [True] console = True n,m = getNM(250, console) # nm = str(n) + ' ' + str(m) + '\n' # uvts = [] # file.write(l) # print(n,m) love = [[] for i in range(n)] hate = [[] for i in range(n)] colors = [ 0 for i in range(n)] for i in range(m): u,v,t = getUVT(n, love, hate, console) # uvts.append(str(u + 1) + ' ' + str(v + 1) + ' ' + str(t) + '\n') if t: love[u].append(v) love[v].append(u) else: hate[u].append(v) hate[v].append(u) ans = 500000004 for i in range(n): if colors[i] == 0: dfs(i, 1) ans = (ans*2) ans = ans % (1e9 + 7) # print(f'*=2 en el dfs de {i}') if bipartite[0]: # file.write(nm) # for edge in uvts: # file.write(edge) # separator = "______________\n" # file.write(separator) # file.write(str(ans)) # file.write('\n') # file.write(separator) # file.write(separator) print( int(ans)) cases +=1 else: print(0) # file.close()
67
264
25,497,600
197709814
import sys input = sys.stdin.buffer.readline def find_root(root_dict, x): L = [] while x != root_dict[x]: L.append(x) x = root_dict[x] for y in L: root_dict[y] = x return x p = 10**9+7 def process(n, G): g = [[] for i in range(n+1)] root_dict = [i for i in range(n+1)] for a, b, t in G: if t==1: a1 = find_root(root_dict, a) b1 = find_root(root_dict, b) root_dict[a1] = b1 for a, b, t in G: if t==0: a1 = find_root(root_dict, a) b1 = find_root(root_dict, b) g[a1].append(b1) g[b1].append(a1) sign = [None for i in range(n+1)] components = 0 for root in range(1, n+1): if find_root(root_dict, root)==root and sign[root] is None: components+=1 start = [root] sign[root] = 1 while len(start) > 0: next_s = [] for x in start: for y in g[x]: if sign[x]==sign[y]: sys.stdout.write('0\n') return if sign[y] is None: sign[y] = -1*sign[x] next_s.append(y) start = next_s answer = pow(2, components-1, p) sys.stdout.write(f'{answer}\n') n, m = [int(x) for x in input().split()] G = [] for i in range(m): a, b, t = [int(x) for x in input().split()] G.append([a, b, t]) process(n, G)
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Love Triangles
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≤ ai, bi ≤ n, ai ≠ bi, $$c_i \in \{0, 1\}$$). Each pair of people will be described no more than once.
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
null
In the first sample, the four ways are to: - Make everyone love each other - Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
[{"input": "3 0", "output": "4"}, {"input": "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 0", "output": "1"}, {"input": "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 1", "output": "0"}]
2,200
["dfs and similar", "dsu", "graphs"]
67
[{"input": "3 0\r\n", "output": "4\r\n"}, {"input": "4 4\r\n1 2 1\r\n2 3 1\r\n3 4 0\r\n4 1 0\r\n", "output": "1\r\n"}, {"input": "4 4\r\n1 2 1\r\n2 3 1\r\n3 4 0\r\n4 1 1\r\n", "output": "0\r\n"}, {"input": "100000 0\r\n", "output": "303861760\r\n"}, {"input": "100 3\r\n1 2 0\r\n2 3 0\r\n3 1 0\r\n", "output": "0\r\n"}, {"input": "9 2\r\n1 2 0\r\n2 3 0\r\n", "output": "64\r\n"}, {"input": "28567 13\r\n28079 24675 1\r\n18409 26720 1\r\n980 10815 1\r\n20794 16571 1\r\n7376 19861 1\r\n11146 706 1\r\n4255 16391 1\r\n27376 18263 1\r\n10019 28444 1\r\n6574 28053 1\r\n5036 16610 1\r\n3543 7122 1\r\n512 9554 1\r\n", "output": "928433852\r\n"}, {"input": "4 4\r\n1 2 0\r\n2 3 0\r\n2 4 0\r\n3 4 0\r\n", "output": "0\r\n"}, {"input": "4 3\r\n2 3 0\r\n3 4 0\r\n2 4 0\r\n", "output": "0\r\n"}, {"input": "6 6\r\n1 2 0\r\n2 3 1\r\n3 4 0\r\n4 5 1\r\n5 6 0\r\n6 1 1\r\n", "output": "0\r\n"}, {"input": "5 5\r\n1 2 0\r\n2 3 0\r\n3 4 0\r\n4 5 0\r\n1 5 0\r\n", "output": "0\r\n"}]
false
stdio
null
true
553/A
553
A
PyPy 3-64
TESTS
2
46
0
174196309
def frac(v1,v2,v3): loops = max(v1-v2,v3) result = 1 for i in range(loops): if(v1 != v2): result = result*v1 v1 = v1 - 1 while(result % v3 == 0 and v3 > 1): result /= v3 v3 = v3 - 1 if(v3 <= 1): result = result % 1000000007 return result k = int(input()) resultado = 1 for i in range(k): val = int(input()) if(i == 0): total = val elif(val == 1): total = total + 1 else: aux = val aux = aux - 1 resultado = resultado*frac(aux+total,total,aux) resultado = resultado%1000000007 total = total + val print(int(resultado))
27
46
0
184122918
from math import comb mod=10**9+7 k =int(input()) res=1 tot=int(input()) for i in range(1,k,1): c=int(input()) res=res*comb(tot+c-1,c-1)%mod tot+=c print(res)
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Kyoya and Colored Balls
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
null
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
[{"input": "3\n2\n2\n1", "output": "3"}, {"input": "4\n1\n2\n3\n4", "output": "1680"}]
1,500
["combinatorics", "dp", "math"]
27
[{"input": "3\r\n2\r\n2\r\n1\r\n", "output": "3\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n4\r\n", "output": "1680\r\n"}, {"input": "10\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n", "output": "12520708\r\n"}, {"input": "5\r\n10\r\n10\r\n10\r\n10\r\n10\r\n", "output": "425711769\r\n"}, {"input": "11\r\n291\r\n381\r\n126\r\n39\r\n19\r\n20\r\n3\r\n1\r\n20\r\n45\r\n2\r\n", "output": "902382672\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "13\r\n67\r\n75\r\n76\r\n80\r\n69\r\n86\r\n75\r\n86\r\n81\r\n84\r\n73\r\n72\r\n76\r\n", "output": "232242896\r\n"}, {"input": "25\r\n35\r\n43\r\n38\r\n33\r\n47\r\n44\r\n40\r\n36\r\n41\r\n42\r\n33\r\n30\r\n49\r\n42\r\n62\r\n39\r\n40\r\n35\r\n43\r\n31\r\n42\r\n46\r\n42\r\n34\r\n33\r\n", "output": "362689152\r\n"}, {"input": "47\r\n20\r\n21\r\n16\r\n18\r\n24\r\n20\r\n25\r\n13\r\n20\r\n22\r\n26\r\n24\r\n17\r\n18\r\n21\r\n22\r\n21\r\n23\r\n17\r\n15\r\n24\r\n19\r\n18\r\n21\r\n20\r\n19\r\n26\r\n25\r\n20\r\n17\r\n17\r\n17\r\n26\r\n32\r\n20\r\n21\r\n25\r\n28\r\n24\r\n21\r\n21\r\n17\r\n28\r\n20\r\n20\r\n31\r\n19\r\n", "output": "295545118\r\n"}, {"input": "3\r\n343\r\n317\r\n337\r\n", "output": "691446102\r\n"}, {"input": "1\r\n5\r\n", "output": "1\r\n"}]
false
stdio
null
true
553/A
553
A
Python 3
TESTS
2
46
0
11770332
import math k = int(input()) c = [] for i in range(k): c.append(int(input())) mod = 1000000007 def cnk(n,k): return int(math.factorial(n)/(math.factorial(k)*math.factorial(n-k))) res = 1 total = c[0] for i in range(1,k): k1 = c[i] c1 = cnk(total + k1 - 1, k1-1) res *= c1 res = res % mod total += k1 print(res)
27
46
0
184154849
from math import comb dec=10**9 + 7 k =int(input()) color_counts = [0] * k for i in range(0, k): color_counts[i] = int(input()) result = 1 curr = color_counts[0] for i in range(1,k): result = result * comb(curr + color_counts[i] - 1 , color_counts[i] - 1) % dec curr = curr + color_counts[i] print(result)
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Kyoya and Colored Balls
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
null
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
[{"input": "3\n2\n2\n1", "output": "3"}, {"input": "4\n1\n2\n3\n4", "output": "1680"}]
1,500
["combinatorics", "dp", "math"]
27
[{"input": "3\r\n2\r\n2\r\n1\r\n", "output": "3\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n4\r\n", "output": "1680\r\n"}, {"input": "10\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n", "output": "12520708\r\n"}, {"input": "5\r\n10\r\n10\r\n10\r\n10\r\n10\r\n", "output": "425711769\r\n"}, {"input": "11\r\n291\r\n381\r\n126\r\n39\r\n19\r\n20\r\n3\r\n1\r\n20\r\n45\r\n2\r\n", "output": "902382672\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "13\r\n67\r\n75\r\n76\r\n80\r\n69\r\n86\r\n75\r\n86\r\n81\r\n84\r\n73\r\n72\r\n76\r\n", "output": "232242896\r\n"}, {"input": "25\r\n35\r\n43\r\n38\r\n33\r\n47\r\n44\r\n40\r\n36\r\n41\r\n42\r\n33\r\n30\r\n49\r\n42\r\n62\r\n39\r\n40\r\n35\r\n43\r\n31\r\n42\r\n46\r\n42\r\n34\r\n33\r\n", "output": "362689152\r\n"}, {"input": "47\r\n20\r\n21\r\n16\r\n18\r\n24\r\n20\r\n25\r\n13\r\n20\r\n22\r\n26\r\n24\r\n17\r\n18\r\n21\r\n22\r\n21\r\n23\r\n17\r\n15\r\n24\r\n19\r\n18\r\n21\r\n20\r\n19\r\n26\r\n25\r\n20\r\n17\r\n17\r\n17\r\n26\r\n32\r\n20\r\n21\r\n25\r\n28\r\n24\r\n21\r\n21\r\n17\r\n28\r\n20\r\n20\r\n31\r\n19\r\n", "output": "295545118\r\n"}, {"input": "3\r\n343\r\n317\r\n337\r\n", "output": "691446102\r\n"}, {"input": "1\r\n5\r\n", "output": "1\r\n"}]
false
stdio
null
true
553/A
553
A
Python 3
TESTS
2
31
0
12121453
def g(): return int(input()) def ncr(n,r): if 2*r > n: r = n-r a = 1 for i in range(r): a = a * (n-i) // (i+1) % 1000000007 return a k = g() ans = 1 n2 = g() for i in range(k-1): n1 = n2 n2 += g() ans = ans * ncr(n2-1,n1) % 1000000007 print(ans)
27
61
0
11744542
if __name__ == '__main__': data = [int(input()) for i in range(int(input()))] total = 1 prev = data[0] for i, x in enumerate(data[1:]): prev += 1 f = 1 c = 1 for j in range(x - 1): total *= prev prev += 1 f *= c c += 1 total //= f if total > 1000000007: total %= 1000000007 print(total)
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Kyoya and Colored Balls
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
null
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
[{"input": "3\n2\n2\n1", "output": "3"}, {"input": "4\n1\n2\n3\n4", "output": "1680"}]
1,500
["combinatorics", "dp", "math"]
27
[{"input": "3\r\n2\r\n2\r\n1\r\n", "output": "3\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n4\r\n", "output": "1680\r\n"}, {"input": "10\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n", "output": "12520708\r\n"}, {"input": "5\r\n10\r\n10\r\n10\r\n10\r\n10\r\n", "output": "425711769\r\n"}, {"input": "11\r\n291\r\n381\r\n126\r\n39\r\n19\r\n20\r\n3\r\n1\r\n20\r\n45\r\n2\r\n", "output": "902382672\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "13\r\n67\r\n75\r\n76\r\n80\r\n69\r\n86\r\n75\r\n86\r\n81\r\n84\r\n73\r\n72\r\n76\r\n", "output": "232242896\r\n"}, {"input": "25\r\n35\r\n43\r\n38\r\n33\r\n47\r\n44\r\n40\r\n36\r\n41\r\n42\r\n33\r\n30\r\n49\r\n42\r\n62\r\n39\r\n40\r\n35\r\n43\r\n31\r\n42\r\n46\r\n42\r\n34\r\n33\r\n", "output": "362689152\r\n"}, {"input": "47\r\n20\r\n21\r\n16\r\n18\r\n24\r\n20\r\n25\r\n13\r\n20\r\n22\r\n26\r\n24\r\n17\r\n18\r\n21\r\n22\r\n21\r\n23\r\n17\r\n15\r\n24\r\n19\r\n18\r\n21\r\n20\r\n19\r\n26\r\n25\r\n20\r\n17\r\n17\r\n17\r\n26\r\n32\r\n20\r\n21\r\n25\r\n28\r\n24\r\n21\r\n21\r\n17\r\n28\r\n20\r\n20\r\n31\r\n19\r\n", "output": "295545118\r\n"}, {"input": "3\r\n343\r\n317\r\n337\r\n", "output": "691446102\r\n"}, {"input": "1\r\n5\r\n", "output": "1\r\n"}]
false
stdio
null
true
553/A
553
A
Python 3
TESTS
2
93
0
64642014
import math def nCr(n, r): return (math.factorial(n) / (math.factorial(r) * math.factorial(n - r))) mod = 1000000007 n = int(input()) data = [] for i in range(n): data.append(int(input())) ans = 1 total = data[0] for i in range(1,n): total += data[i] ans *= int(nCr(total-1,data[i]-1)) ans %= mod print(int(ans))
27
61
0
11745531
import sys def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 R = 1000000007 def main(): k = int(sys.stdin.readline()) data = list(map(int,sys.stdin.readlines())) s = sum(data) ans=1 free = s for i in range(k-1,0,-1): t = choose(free-1, data[i]-1) ans= (((t%R)*ans)%R) free-=data[i] print(ans) main()
Codeforces Round 309 (Div. 1)
CF
2,015
2
256
Kyoya and Colored Balls
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
null
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
[{"input": "3\n2\n2\n1", "output": "3"}, {"input": "4\n1\n2\n3\n4", "output": "1680"}]
1,500
["combinatorics", "dp", "math"]
27
[{"input": "3\r\n2\r\n2\r\n1\r\n", "output": "3\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n4\r\n", "output": "1680\r\n"}, {"input": "10\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n100\r\n", "output": "12520708\r\n"}, {"input": "5\r\n10\r\n10\r\n10\r\n10\r\n10\r\n", "output": "425711769\r\n"}, {"input": "11\r\n291\r\n381\r\n126\r\n39\r\n19\r\n20\r\n3\r\n1\r\n20\r\n45\r\n2\r\n", "output": "902382672\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "13\r\n67\r\n75\r\n76\r\n80\r\n69\r\n86\r\n75\r\n86\r\n81\r\n84\r\n73\r\n72\r\n76\r\n", "output": "232242896\r\n"}, {"input": "25\r\n35\r\n43\r\n38\r\n33\r\n47\r\n44\r\n40\r\n36\r\n41\r\n42\r\n33\r\n30\r\n49\r\n42\r\n62\r\n39\r\n40\r\n35\r\n43\r\n31\r\n42\r\n46\r\n42\r\n34\r\n33\r\n", "output": "362689152\r\n"}, {"input": "47\r\n20\r\n21\r\n16\r\n18\r\n24\r\n20\r\n25\r\n13\r\n20\r\n22\r\n26\r\n24\r\n17\r\n18\r\n21\r\n22\r\n21\r\n23\r\n17\r\n15\r\n24\r\n19\r\n18\r\n21\r\n20\r\n19\r\n26\r\n25\r\n20\r\n17\r\n17\r\n17\r\n26\r\n32\r\n20\r\n21\r\n25\r\n28\r\n24\r\n21\r\n21\r\n17\r\n28\r\n20\r\n20\r\n31\r\n19\r\n", "output": "295545118\r\n"}, {"input": "3\r\n343\r\n317\r\n337\r\n", "output": "691446102\r\n"}, {"input": "1\r\n5\r\n", "output": "1\r\n"}]
false
stdio
null
true
803/G
803
G
PyPy 3-64
TESTS
5
140
7,065,600
150414693
import sys, random input = sys.stdin.readline M = 10**9+8 class Node: def __init__(self, value, size, num, start = 0): self.value = value self.size = size self.num = num self.min = num if num else getmin(start, start+size) self.start = start self.prior = random.random() self.left = self.right = None def __repr__(self): return f"[{self.value}, {self.size}, {self.num}, {self.min}, {self.start}, ({self.left}, {self.right})]" def up(r): r.min = min(r.num if r.num else getmin(r.start, r.start+r.size), r.left.min if r.left else M, r.right.min if r.right else M) def split(root, value): if not root: return (None, None) else: if value <= root.value: left, root.left = split(root.left, value) up(root); return (left, root) else: root.right, right = split(root.right, value) up(root); return (root, right) def merge(left, right): if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: left.right = merge(left.right, right) up(left) return left else: right.left = merge(left, right.left) up(right) return right def find(root, value): if not root: return None if value == root.value: return root elif value < root.value: return find(root.left, value) else: x = find(root.right, value) return x if x else root n, k = [*map(int, input().split())] b = [*map(int, input().split())] mm = [[b[i]] for i in range(n)] for i in range(len(bin(n))-3): for j in range(n): mm[j].append(min(mm[j][i], mm[j+(1<<i)][i] if j+(1<<i) < n else M)) def getmin(start, end): x = len(bin(end-start))-3; return min(mm[start][x], mm[end-(1<<x)][x]) root = Node(0, 1, M) for i in range(k): root = merge(root, Node(i*n+1, n, 0, 0)) root = merge(root, Node(k*n+1, 1, M)) for q in [[*map(int, input().split())] for _ in range(int(input()))]: l, r = q[1:3] # print(root) n1 = find(root, l) n2 = find(root, r) r1, r2 = split(root, n1.value) n1, r2 = split(r2, n1.value+1) s , r2 = split(r2, n2.value) n2, r2 = split(r2, n2.value+1) # print(r1, n1, s, n2, r2) if q[0] == 1: x = q[3] if not n2: n2 = n1 if n1.num: n1 = Node(n1.value, l-n1.value, n1.num) else: n1 = Node(n1.value, l-n1.value, 0, n1.start) if l-n1.value > 0 else None if n2.num: n2 = Node(n2.value, n2.value+n2.size-r-1, n2.num) else: n2 = Node(r+1, n2.value+n2.size-r-1, 0, n2.start+r+1-n2.value) if n2.value+n2.size-r-1 > 0 else None root = merge(merge(r1, n1), merge(merge(Node(l, r-l+1, x), n2), r2)) else: nx = n2 if n2 else n1 min1 = n1.min if n1.num else getmin(n1.start + l - n1.value, n1.start + n1.size) min2 = nx.min if nx.num else getmin(nx.start, nx.start+r+1-nx.value) print(min(min1, s.min if s else M, min2)) root = merge(merge(r1, n1), merge(merge(s, n2), r2))
32
2,823
117,350,400
230770543
import sys import random input = sys.stdin.readline rd = random.randint(10 ** 9, 2 * 10 ** 9) class SegmentTree(): def __init__(self, init, unitX, f): self.f = f # (X, X) -> X self.unitX = unitX self.f = f if type(init) == int: self.n = init self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * (self.n * 2) else: self.n = len(init) self.n = 1 << (self.n - 1).bit_length() # len(init)が2の累乗ではない時UnitXで埋める self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init)) # 配列のindex1まで埋める for i in range(self.n - 1, 0, -1): self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) def update(self, i, x): """0-indexedのi番目の値をxで置換""" # 最下段に移動 i += self.n self.X[i] = x # 上向に更新 i >>= 1 while i: self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) i >>= 1 def getvalue(self, i): """元の配列のindexの値を見る""" return self.X[i + self.n] def getrange(self, l, r): """区間[l, r)でのfを行った値""" l += self.n r += self.n al = self.unitX ar = self.unitX while l < r: # 左端が右子ノードであれば if l & 1: al = self.f(al, self.X[l]) l += 1 # 右端が右子ノードであれば if r & 1: r -= 1 ar = self.f(self.X[r], ar) l >>= 1 r >>= 1 return self.f(al, ar) n, k = list(map(int, input().split())) a = list(map(int, input().split())) q = int(input()) queries = [list(map(int, input().split())) for _ in range(q)] min_tree = SegmentTree(a, 10 ** 9, min) p = [] for qq in queries: p.append(qq[1] - 1) p.append(qq[2] - 1) p.sort() cur = 0 pre = -1 new = [] d = dict() for i in range(len(p)): if p[i] == pre: continue if p[i] - pre > 1: if p[i] - pre > n: mi = min_tree.getrange(0, n) elif pre % n < p[i] % n: mi = min_tree.getrange(pre % n + 1, p[i] % n) else: mi = min(min_tree.getrange(pre % n + 1, n), min_tree.getrange(0, p[i] % n)) new.append(mi) cur += 1 new.append(a[p[i] % n]) d[p[i]] = cur cur += 1 pre = p[i] def push_lazy(node, left, right): if lazy[node] != 0: tree[node] = lazy[node] if left != right: lazy[node * 2] = lazy[node] lazy[node * 2 + 1] = lazy[node] lazy[node] = 0 def update(node, left, right, l, r, val): push_lazy(node, left, right) if r < left or l > right: return if l <= left and r >= right: lazy[node] = val push_lazy(node, left, right) return mid = (left + right) // 2 update(node * 2, left, mid, l, r, val) update(node * 2 + 1, mid + 1, right, l, r, val) tree[node] = min(tree[node * 2], tree[node * 2 + 1]) def query(node, left, right, l, r): push_lazy(node, left, right) if r < left or l > right: return 10**18 if l <= left and r >= right: return tree[node] mid = (left + right) // 2 sum_left = query(node * 2, left, mid, l, r) sum_right = query(node * 2 + 1, mid + 1, right, l, r) return min(sum_left, sum_right) tree = [10 ** 18] * (4 * len(new)) lazy = [0] * (4 * len(new)) for i in range(len(new)): update(1, 0, len(new) - 1, i, i, new[i]) for qq in queries: if qq[0] == 1: l, r = qq[1] - 1, qq[2] - 1 update(1, 0, len(new) - 1, d[l], d[r], qq[3]) else: l, r = qq[1] - 1, qq[2] - 1 print(query(1, 0, len(new) - 1, d[l], d[r]))
Educational Codeforces Round 20
ICPC
2,017
4
512
Periodic RMQ Problem
You are given an array a consisting of positive integers and q queries to this array. There are two types of queries: - 1 l r x — for each index i such that l ≤ i ≤ r set ai = x. - 2 l r — find the minimum among such ai that l ≤ i ≤ r. We decided that this problem is too easy. So the array a is given in a compressed form: there is an array b consisting of n elements and a number k in the input, and before all queries a is equal to the concatenation of k arrays b (so the size of a is n·k).
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 104). The second line contains n integers — elements of the array b (1 ≤ bi ≤ 109). The third line contains one integer q (1 ≤ q ≤ 105). Then q lines follow, each representing a query. Each query is given either as 1 l r x — set all elements in the segment from l till r (including borders) to x (1 ≤ l ≤ r ≤ n·k, 1 ≤ x ≤ 109) or as 2 l r — find the minimum among all elements in the segment from l till r (1 ≤ l ≤ r ≤ n·k).
For each query of type 2 print the answer to this query — the minimum on the corresponding segment.
null
null
[{"input": "3 1\n1 2 3\n3\n2 1 3\n1 1 2 4\n2 1 3", "output": "1\n3"}, {"input": "3 2\n1 2 3\n5\n2 4 4\n1 4 4 5\n2 4 4\n1 1 6 1\n2 6 6", "output": "1\n5\n1"}]
2,300
["data structures"]
32
[{"input": "3 1\r\n1 2 3\r\n3\r\n2 1 3\r\n1 1 2 4\r\n2 1 3\r\n", "output": "1\r\n3\r\n"}, {"input": "3 2\r\n1 2 3\r\n5\r\n2 4 4\r\n1 4 4 5\r\n2 4 4\r\n1 1 6 1\r\n2 6 6\r\n", "output": "1\r\n5\r\n1\r\n"}, {"input": "10 10\r\n10 8 10 9 2 2 4 6 10 1\r\n10\r\n1 17 87 5\r\n2 31 94\r\n1 5 56 8\r\n1 56 90 10\r\n1 25 93 6\r\n1 11 32 4\r\n2 20 49\r\n1 46 87 8\r\n2 14 48\r\n2 40 48\r\n", "output": "1\r\n4\r\n4\r\n6\r\n"}, {"input": "10 10\r\n4 2 3 8 1 2 1 7 5 4\r\n10\r\n2 63 87\r\n2 2 48\r\n2 5 62\r\n2 33 85\r\n2 30 100\r\n2 38 94\r\n2 7 81\r\n2 13 16\r\n2 26 36\r\n2 64 96\r\n", "output": "1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n"}, {"input": "10 10\r\n8 7 4 6 8 2 4 9 4 3\r\n10\r\n1 43 67 7\r\n1 13 73 4\r\n1 35 71 6\r\n1 9 18 8\r\n1 3 55 2\r\n1 49 67 10\r\n1 22 49 2\r\n1 66 70 6\r\n1 17 21 10\r\n1 61 77 3\r\n", "output": ""}]
false
stdio
null
true
149/C
149
C
PyPy 3-64
TESTS
2
46
0
175203093
import sys input = sys.stdin.readline n = int(input()) w = list(map(int, input().split())) d = sorted([(j, i+1) for i, j in enumerate(w)]) e = sorted([(d[i+1][0] - d[i][0], d[i][1], d[i+1][1]) for i in range(0, n//2+1, 2)]) s = sum(i[0] for i in e) x = d[-1][0] if s > x: for i in range(len(e)-1, -1, -1): a = e[i][0]*2 if abs(s - a) <= x: e[i] = (e[i][0], e[i][2], e[i][1]) break elif s-a > x: e[i] = (e[i][0], e[i][2], e[i][1]) s -= a else: continue a = [] b = [] for i, j, k in e: a.append(j) b.append(k) if n % 2: if s < 0: b.append(d[-1][0]) else: a.append(d[-1][0]) print(len(a)) print(' '.join(map(str, a))) print(len(b)) print(' '.join(map(str, b)))
47
436
22,016,000
196388111
n = int(input()) a = list(map(int,input().split())) s = sum(a) mx = max(a) a = [[a[i], i+1] for i in range(n)] a.sort() o = [] t = [] os = 0 ts = 0 a = a[::-1] while len(a) >= 2: x,i = a.pop() y,j = a.pop() if os <= ts: o.append(j) t.append(i) os+= y ts += x else: o.append(i) t.append(j) ts += y os += x if a: if os < ts: o.append(a[0][1]) os += a[0][0] else: t.append(a[0][1]) ts += a[0][0] if abs(os-ts) <= mx: print(len(o)) print(*o) print(len(t)) print(*t)
Codeforces Round 106 (Div. 2)
CF
2,012
1
256
Division into Teams
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers). The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: - Each boy plays for exactly one team (x + y = n). - The sizes of teams differ in no more than one (|x - y| ≤ 1). - The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: $$\left| \sum_{i=1}^{x} a_{p_i} - \sum_{i=1}^{y} a_{q_i} \right| \leq \max_{i=1}^{n} a_i$$ Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.
On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
null
Let's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.
[{"input": "3\n1 2 1", "output": "2\n1 2\n1\n3"}, {"input": "5\n2 3 3 1 1", "output": "3\n4 1 3\n2\n5 2"}]
1,500
["greedy", "math", "sortings"]
47
[{"input": "3\r\n1 2 1\r\n", "output": "2\r\n1 2 \r\n1\r\n3 \r\n"}, {"input": "5\r\n2 3 3 1 1\r\n", "output": "3\r\n4 1 3 \r\n2\r\n5 2 \r\n"}, {"input": "10\r\n2 2 2 2 2 2 2 1 2 2\r\n", "output": "5\r\n8 2 4 6 9 \r\n5\r\n1 3 5 7 10 \r\n"}, {"input": "10\r\n2 3 3 1 3 1 1 1 2 2\r\n", "output": "5\r\n4 7 1 10 3 \r\n5\r\n6 8 9 2 5 \r\n"}, {"input": "10\r\n2 3 2 3 3 1 1 3 1 1\r\n", "output": "5\r\n6 9 1 2 5 \r\n5\r\n7 10 3 4 8 \r\n"}, {"input": "11\r\n1 3 1 2 1 2 2 2 1 1 1\r\n", "output": "6\r\n1 5 10 4 7 2 \r\n5\r\n3 9 11 6 8 \r\n"}, {"input": "11\r\n54 83 96 75 33 27 36 35 26 22 77\r\n", "output": "6\r\n10 6 8 1 11 3 \r\n5\r\n9 5 7 4 2 \r\n"}, {"input": "11\r\n1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "6\r\n1 3 5 7 9 11 \r\n5\r\n2 4 6 8 10 \r\n"}, {"input": "2\r\n1 1\r\n", "output": "1\r\n1 \r\n1\r\n2 \r\n"}, {"input": "2\r\n35 36\r\n", "output": "1\r\n1 \r\n1\r\n2 \r\n"}, {"input": "25\r\n1 2 2 1 2 2 2 2 2 1 1 2 2 2 2 2 1 2 2 2 1 1 2 2 1\r\n", "output": "13\r\n1 10 17 22 2 5 7 9 13 15 18 20 24 \r\n12\r\n4 11 21 25 3 6 8 12 14 16 19 23 \r\n"}, {"input": "27\r\n2 1 1 3 1 2 1 1 3 2 3 1 3 2 1 3 2 3 2 1 2 3 2 2 1 2 1\r\n", "output": "14\r\n2 5 8 15 25 1 10 17 21 24 4 11 16 22 \r\n13\r\n3 7 12 20 27 6 14 19 23 26 9 13 18 \r\n"}, {"input": "30\r\n2 2 2 3 4 3 4 4 3 2 3 2 2 4 1 4 2 4 2 2 1 4 3 2 1 3 1 1 4 3\r\n", "output": "15\r\n15 25 28 2 10 13 19 24 6 11 26 5 8 16 22 \r\n15\r\n21 27 1 3 12 17 20 4 9 23 30 7 14 18 29 \r\n"}, {"input": "100\r\n3 4 8 10 8 6 4 3 7 7 6 2 3 1 3 10 1 7 9 3 5 5 2 6 2 9 1 7 4 2 4 1 6 1 7 10 2 5 3 7 6 4 6 2 8 8 8 6 6 10 3 7 4 3 4 1 7 9 3 6 3 6 1 4 9 3 8 1 10 1 4 10 7 7 9 5 3 8 10 2 1 10 8 7 10 8 5 3 1 2 1 10 6 1 5 3 3 5 7 2\r\n", "output": "50\r\n14 27 34 63 70 89 94 23 30 44 90 1 13 20 51 59 66 88 97 7 31 53 64 21 38 87 98 11 33 43 49 62 9 18 35 52 73 84 3 45 47 78 86 26 65 4 36 69 79 85 \r\n50\r\n17 32 56 68 81 91 12 25 37 80 100 8 15 39 54 61 77 96 2 29 42 55 71 22 76 95 6 24 41 48 60 93 10 28 40 57 74 99 5 46 67 83 19 58 75 16 50 72 82 92 \r\n"}, {"input": "100\r\n85 50 17 89 65 89 5 20 86 26 16 21 85 14 44 31 87 31 6 2 48 67 8 80 79 1 48 36 97 1 5 30 79 50 78 12 2 55 76 100 54 40 26 81 97 96 68 56 87 14 51 17 54 37 52 33 69 62 38 63 74 15 62 78 9 19 67 2 60 58 93 60 18 96 55 48 34 7 79 82 32 58 90 67 20 50 27 15 7 89 98 10 11 15 99 49 4 51 77 52\r\n", "output": "50\r\n26 20 68 7 19 89 65 93 14 62 94 3 73 8 12 43 32 18 56 28 59 15 27 96 34 51 55 41 38 48 82 72 63 5 67 47 61 99 64 33 24 80 13 17 4 90 71 74 45 95 \r\n50\r\n30 37 97 31 78 23 92 36 50 88 11 52 66 85 10 87 16 81 77 54 42 21 76 2 86 98 100 53 75 70 69 58 60 22 84 57 39 35 25 79 44 1 9 49 6 83 46 29 91 40 \r\n"}, {"input": "100\r\n2382 7572 9578 1364 2325 2929 7670 5574 2836 2440 6553 1751 929 8785 6894 9373 9308 7338 6380 9541 9951 6785 8993 9942 5087 7544 6582 7139 8458 7424 9759 8199 9464 8817 7625 6200 4955 9373 9500 3062 849 4210 9337 5466 2190 8150 4971 3145 869 5675 1975 161 1998 378 5229 9000 8958 761 358 434 7636 8295 4406 73 375 812 2473 3652 9067 3052 5287 2850 6987 5442 2625 8894 8733 791 9763 5258 8259 9530 2050 7334 2118 2726 8221 5527 8827 1585 8334 8898 6399 6217 7400 2576 5164 9063 6247 9433\r\n", "output": "50\r\n64 59 54 58 66 49 4 12 53 85 5 10 96 86 72 70 48 42 37 25 55 71 44 8 36 99 93 27 15 28 18 30 2 61 46 87 62 29 14 89 92 23 98 17 16 100 39 20 31 24 \r\n50\r\n52 65 60 78 41 13 90 51 83 45 1 67 75 9 6 40 68 63 47 97 80 74 88 50 94 19 11 22 73 84 95 26 35 7 32 81 91 77 34 76 57 56 69 43 38 33 82 3 79 21 \r\n"}, {"input": "3\r\n1 2 3\r\n", "output": "2\r\n1 3 \r\n1\r\n2 \r\n"}, {"input": "3\r\n10 10 10\r\n", "output": "2\r\n1 3 \r\n1\r\n2 \r\n"}, {"input": "3\r\n5 10 10\r\n", "output": "2\r\n1 3 \r\n1\r\n2 \r\n"}, {"input": "5\r\n6 1 1 1 1\r\n", "output": "3\r\n2 4 1 \r\n2\r\n3 5 \r\n"}, {"input": "5\r\n1 100 2 200 3\r\n", "output": "3\r\n1 5 4 \r\n2\r\n3 2 \r\n"}]
false
stdio
import sys def main(input_path, output_path, submission_path): with open(input_path) as f: n = int(f.readline().strip()) a = list(map(int, f.readline().split())) max_a = max(a) with open(submission_path) as f: lines = [line.strip() for line in f.readlines()] if len(lines) != 4: print(0) return try: x = int(lines[0]) p = list(map(int, lines[1].split())) y = int(lines[2]) q = list(map(int, lines[3].split())) except: print(0) return if x + y != n or abs(x - y) > 1: print(0) return if len(p) != x or len(q) != y: print(0) return all_indices = set(p) | set(q) if len(all_indices) != x + y or any(i < 1 or i > n for i in all_indices): print(0) return sum_p = sum(a[i-1] for i in p) sum_q = sum(a[i-1] for i in q) if abs(sum_p - sum_q) > max_a: print(0) return print(1) if __name__ == "__main__": input_path, output_path, submission_path = sys.argv[1], sys.argv[2], sys.argv[3] main(input_path, output_path, submission_path)
true
149/D
149
D
PyPy 3-64
TESTS
4
92
0
196396083
s = input() n = len(s) num = [0]*(n) que = [] d = dict() cnt = 0 for i in range(n): if s[i] == "(": que.append(i) else: pre = que.pop() num[pre] = cnt num[i] = cnt d[i] = pre d[pre] = i cnt +=1 mod = 10**9+7 def f(l,r): if l == r-1: ll = [[0]*3 for i in range(3)] ll[0][1] = 1 ll[0][2] = 1 ll[1][0] = 1 ll[2][0] = 1 return ll if num[l] == num[r]: ans = [[0]*3 for i in range(3)] if l + 1 == r: ll = [[0]*3 for i in range(3)] ll[0][1] = 1 ll[0][2] = 1 ll[1][0] = 1 ll[2][0] = 1 else: ll = f(l+1, r-1) for [i,j] in [[0,1],[0,2],[1,0],[2,0]]: for k in range(3): for kk in range(3): if i != 0 and k != 0 and i == k :continue if j != 0 and kk != 0 and j == kk :continue ans[i][j] += ll[k][kk] ans[i][j] %= mod else: if d[l] == l+1: ll = [[0]*3 for i in range(3)] ll[0][1] = 1 ll[0][2] = 1 ll[1][0] = 1 ll[2][0] = 1 else: ll = f(l+1, d[l]-1) if d[l] + 1 + 1 == r: rr = [[0]*3 for i in range(3)] rr[0][1] = 1 rr[0][2] = 1 rr[1][0] = 1 rr[2][0] = 1 else: rr = f(d[l] + 2, r-1) ans = [[0]*3 for i in range(3)] for i in range(3): for j in range(3): ans[i][j] += ll[i][0] * rr[1][j] ans[i][j] += ll[i][0] * rr[2][j] ans[i][j] += ll[i][1] * rr[0][j] ans[i][j] += ll[i][1] * rr[2][j] ans[i][j] += ll[i][2] * rr[1][j] ans[i][j] += ll[i][2] * rr[0][j] ans[i][j] += ll[i][0] * rr[0][j] ans[i][j] %= mod return ans x = f(0,n-1) ans = 0 for i in x: ans += sum(i) print(ans%mod)
38
436
10,649,600
203663266
from functools import lru_cache import sys input = lambda: sys.stdin.readline().strip() def solve(): s = input() n = len(s) right_pos = [-1]*n stk = [] mod = 10**9+7 for i, c in enumerate(s): if c == '(': stk.append(i) else: right_pos[stk.pop()] = i dp = {} @lru_cache(None) def f(l, r, lc, rc): if l > r: return 1 mid = right_pos[l] res = 0 if mid < r: res += f(l+1, mid-1, 0, 1) * f(mid+1, r, 1, rc) res += f(l+1, mid-1, 0, 2) * f(mid+1, r, 2, rc) if lc != 1: res += f(l+1, mid-1, 2, 0) * f(mid+1, r, 0, rc) if lc != 2: res += f(l+1, mid-1, 1, 0) * f(mid+1, r, 0, rc) else: if rc != 1: res += f(l+1, r-1, 0, 2) if rc != 2: res += f(l+1, r-1, 0, 1) if lc != 1: res += f(l+1, r-1, 2, 0) if lc != 2: res += f(l+1, r-1, 1, 0) return res % mod res = f(0, n-1, 0, 0) print(res) solve()
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
803/G
803
G
PyPy 3
TESTS
5
109
20,480,000
127583486
from collections import deque import sys input = sys.stdin.readline def slide_min(n, k, a): ans = [] s = deque() for i in range(n): ai = a[i] while s: if a[s[-1]] >= ai: s.pop() else: break s.append(i) while s: if s[0] + k <= i: s.popleft() else: break if (i + 1) // k: ans.append(a[s[0]]) return ans def make_sparse_table(a): table = [] s, l = a, 1 table.append(s) while 2 * l <= len(a): s = slide_min(len(s), l + 1, s) table.append(s) l *= 2 return table def get_min(l, r): d = len(bin(r - l + 1)) - 3 ans = min(table[d][l], table[d][r - pow2[d] + 1]) return ans def make_tree(n, a): n0 = 1 while n0 < n: n0 *= 2 tree = [inf] * (2 * n0) lazy = [inf] * (2 * n0) l = len(tree) // 2 for i in range(l, l + len(a)): tree[i] = a[i - l] lazy[i] = a[i - l] for i in range(l - 1, 0, -1): tree[i] = min(tree[2 * i], tree[2 * i + 1]) return tree, lazy def eval(s, t, a): b = [] u, v = [0, len(tree) // 2 - 1], [0, len(tree) // 2 - 1] x, y = 1, 1 if lazy[x] ^ inf: tree[x] = lazy[x] while u[0] ^ u[1]: lx, ly = lazy[x], lazy[y] if not x in a: b.append(x) if lx ^ inf: lazy[x] = inf lazy[2 * x], lazy[2 * x + 1] = lx, lx tree[2 * x], tree[2 * x + 1] = lx, lx if not y in a: b.append(y) if ly ^ inf: lazy[y] = inf lazy[2 * y], lazy[2 * y + 1] = ly, ly tree[2 * y], tree[2 * y + 1] = ly, ly u0, u1 = u if u0 <= s <= (u0 + u1) // 2: u1 = (u0 + u1) // 2 x = 2 * x else: u0 = (u0 + u1) // 2 + 1 x = 2 * x + 1 u = [u0, u1] v0, v1 = v if v0 <= t <= (v0 + v1) // 2: v1 = (v0 + v1) // 2 y = 2 * y else: v0 = (v0 + v1) // 2 + 1 y = 2 * y + 1 v = [v0, v1] tree[x], tree[y] = lazy[x], lazy[y] return b def update(s, t, x): s0, t0 = s, t s += len(tree) // 2 t += len(tree) // 2 a = set() while s <= t: if s % 2 == 0: s //= 2 else: a.add(s) s = (s + 1) // 2 if t % 2 == 1: t //= 2 else: a.add(t) t = (t - 1) // 2 b = eval(s0, t0, a) for i in a: tree[i], lazy[i] = x, x while b: i = b.pop() tree[i] = min(tree[2 * i], tree[2 * i + 1]) return def get_ans(s, t): s0, t0 = s, t s += len(tree) // 2 t += len(tree) // 2 a = set() while s <= t: if s % 2 == 0: s //= 2 else: a.add(s) s = (s + 1) // 2 if t % 2 == 1: t //= 2 else: a.add(t) t = (t - 1) // 2 eval(s0, t0, a) ans = inf for i in a: ans = min(ans, tree[i]) return ans n, k = map(int, input().split()) b = list(map(int, input().split())) table = make_sparse_table(b) pow2 = [1] for _ in range(20): pow2.append(2 * pow2[-1]) x = set() qs = [] q = int(input()) for _ in range(q): t = list(map(int, input().split())) x.add(t[1]) x.add(t[2]) qs.append(t) x = list(x) x.sort() mi = min(b) l = 1 a = [] d = dict() for y in x: r = y - 1 if l <= r: if l <= n + r: m0 = mi else: l0, r0 = (l - 1) % n, (r - 1) % n if l0 <= r0: m0 = get_min(l0, r0) else: m0 = min(get_min(0, l0), get_min(r0, n - 1)) a.append(m0) d[y] = len(a) a.append(b[(y - 1) % n]) l = y + 1 inf = pow(10, 9) + 7 n = len(a) tree, lazy = make_tree(n, a) for t in qs: if t[0] == 1: ty, l, r, x = t update(d[l], d[r], x) else: ty, l, r = t ans = get_ans(d[l], d[r]) print(ans)
32
2,823
117,350,400
230770543
import sys import random input = sys.stdin.readline rd = random.randint(10 ** 9, 2 * 10 ** 9) class SegmentTree(): def __init__(self, init, unitX, f): self.f = f # (X, X) -> X self.unitX = unitX self.f = f if type(init) == int: self.n = init self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * (self.n * 2) else: self.n = len(init) self.n = 1 << (self.n - 1).bit_length() # len(init)が2の累乗ではない時UnitXで埋める self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init)) # 配列のindex1まで埋める for i in range(self.n - 1, 0, -1): self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) def update(self, i, x): """0-indexedのi番目の値をxで置換""" # 最下段に移動 i += self.n self.X[i] = x # 上向に更新 i >>= 1 while i: self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) i >>= 1 def getvalue(self, i): """元の配列のindexの値を見る""" return self.X[i + self.n] def getrange(self, l, r): """区間[l, r)でのfを行った値""" l += self.n r += self.n al = self.unitX ar = self.unitX while l < r: # 左端が右子ノードであれば if l & 1: al = self.f(al, self.X[l]) l += 1 # 右端が右子ノードであれば if r & 1: r -= 1 ar = self.f(self.X[r], ar) l >>= 1 r >>= 1 return self.f(al, ar) n, k = list(map(int, input().split())) a = list(map(int, input().split())) q = int(input()) queries = [list(map(int, input().split())) for _ in range(q)] min_tree = SegmentTree(a, 10 ** 9, min) p = [] for qq in queries: p.append(qq[1] - 1) p.append(qq[2] - 1) p.sort() cur = 0 pre = -1 new = [] d = dict() for i in range(len(p)): if p[i] == pre: continue if p[i] - pre > 1: if p[i] - pre > n: mi = min_tree.getrange(0, n) elif pre % n < p[i] % n: mi = min_tree.getrange(pre % n + 1, p[i] % n) else: mi = min(min_tree.getrange(pre % n + 1, n), min_tree.getrange(0, p[i] % n)) new.append(mi) cur += 1 new.append(a[p[i] % n]) d[p[i]] = cur cur += 1 pre = p[i] def push_lazy(node, left, right): if lazy[node] != 0: tree[node] = lazy[node] if left != right: lazy[node * 2] = lazy[node] lazy[node * 2 + 1] = lazy[node] lazy[node] = 0 def update(node, left, right, l, r, val): push_lazy(node, left, right) if r < left or l > right: return if l <= left and r >= right: lazy[node] = val push_lazy(node, left, right) return mid = (left + right) // 2 update(node * 2, left, mid, l, r, val) update(node * 2 + 1, mid + 1, right, l, r, val) tree[node] = min(tree[node * 2], tree[node * 2 + 1]) def query(node, left, right, l, r): push_lazy(node, left, right) if r < left or l > right: return 10**18 if l <= left and r >= right: return tree[node] mid = (left + right) // 2 sum_left = query(node * 2, left, mid, l, r) sum_right = query(node * 2 + 1, mid + 1, right, l, r) return min(sum_left, sum_right) tree = [10 ** 18] * (4 * len(new)) lazy = [0] * (4 * len(new)) for i in range(len(new)): update(1, 0, len(new) - 1, i, i, new[i]) for qq in queries: if qq[0] == 1: l, r = qq[1] - 1, qq[2] - 1 update(1, 0, len(new) - 1, d[l], d[r], qq[3]) else: l, r = qq[1] - 1, qq[2] - 1 print(query(1, 0, len(new) - 1, d[l], d[r]))
Educational Codeforces Round 20
ICPC
2,017
4
512
Periodic RMQ Problem
You are given an array a consisting of positive integers and q queries to this array. There are two types of queries: - 1 l r x — for each index i such that l ≤ i ≤ r set ai = x. - 2 l r — find the minimum among such ai that l ≤ i ≤ r. We decided that this problem is too easy. So the array a is given in a compressed form: there is an array b consisting of n elements and a number k in the input, and before all queries a is equal to the concatenation of k arrays b (so the size of a is n·k).
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 104). The second line contains n integers — elements of the array b (1 ≤ bi ≤ 109). The third line contains one integer q (1 ≤ q ≤ 105). Then q lines follow, each representing a query. Each query is given either as 1 l r x — set all elements in the segment from l till r (including borders) to x (1 ≤ l ≤ r ≤ n·k, 1 ≤ x ≤ 109) or as 2 l r — find the minimum among all elements in the segment from l till r (1 ≤ l ≤ r ≤ n·k).
For each query of type 2 print the answer to this query — the minimum on the corresponding segment.
null
null
[{"input": "3 1\n1 2 3\n3\n2 1 3\n1 1 2 4\n2 1 3", "output": "1\n3"}, {"input": "3 2\n1 2 3\n5\n2 4 4\n1 4 4 5\n2 4 4\n1 1 6 1\n2 6 6", "output": "1\n5\n1"}]
2,300
["data structures"]
32
[{"input": "3 1\r\n1 2 3\r\n3\r\n2 1 3\r\n1 1 2 4\r\n2 1 3\r\n", "output": "1\r\n3\r\n"}, {"input": "3 2\r\n1 2 3\r\n5\r\n2 4 4\r\n1 4 4 5\r\n2 4 4\r\n1 1 6 1\r\n2 6 6\r\n", "output": "1\r\n5\r\n1\r\n"}, {"input": "10 10\r\n10 8 10 9 2 2 4 6 10 1\r\n10\r\n1 17 87 5\r\n2 31 94\r\n1 5 56 8\r\n1 56 90 10\r\n1 25 93 6\r\n1 11 32 4\r\n2 20 49\r\n1 46 87 8\r\n2 14 48\r\n2 40 48\r\n", "output": "1\r\n4\r\n4\r\n6\r\n"}, {"input": "10 10\r\n4 2 3 8 1 2 1 7 5 4\r\n10\r\n2 63 87\r\n2 2 48\r\n2 5 62\r\n2 33 85\r\n2 30 100\r\n2 38 94\r\n2 7 81\r\n2 13 16\r\n2 26 36\r\n2 64 96\r\n", "output": "1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n"}, {"input": "10 10\r\n8 7 4 6 8 2 4 9 4 3\r\n10\r\n1 43 67 7\r\n1 13 73 4\r\n1 35 71 6\r\n1 9 18 8\r\n1 3 55 2\r\n1 49 67 10\r\n1 22 49 2\r\n1 66 70 6\r\n1 17 21 10\r\n1 61 77 3\r\n", "output": ""}]
false
stdio
null
true
803/G
803
G
Python 3
TESTS
9
1,013
1,331,200
26920263
from sys import stdin, stdout n, k = map(int, stdin.readline().split()) values = list(map(int, stdin.readline().split())) * k m = int(stdin.readline()) n *= k size = 1 while (size < n): size *= 2 tree = [float('inf') for i in range(2 * size)] updating = [0 for i in range (2 * size)] for i in range(n): tree[size + i] = values[i] for i in range(size - 1, 0, -1): tree[i] = min(tree[i * 2], tree[i * 2 + 1]) def update(l, r, ind, lb, rb, value): if updating[ind] and ind * 2 < len(tree): if (not updating[ind * 2] or (updating[ind * 2][1] < updating[ind][1])): tree[ind * 2] = updating[ind][0] updating[ind * 2] = updating[ind][::] if (not updating[ind * 2 + 1] or (updating[ind * 2 + 1][1] < updating[ind][1])): tree[ind * 2 + 1] = updating[ind][0] updating[ind * 2 + 1] = updating[ind][::] updating[ind] = 0 if (l == lb and r == rb): tree[ind] = value if (ind * 2 < len(tree)): tree[ind * 2], tree[ind * 2 + 1] = value, value updating[ind * 2], updating[ind * 2 + 1] = (value, time), (value, time) while ind != 1: ind //= 2 tree[ind] = min(tree[ind * 2], tree[ind * 2 + 1]) if min(tree[ind * 2], tree[ind * 2 + 1]) != value: break else: m = (lb + rb) // 2 if (l <= m): update(l, min(m, r), ind * 2, lb, m, value) if (r > m): update(max(l, m + 1), r, ind * 2 + 1, m + 1, rb, value) def get(l, r, ind, lb, rb): if updating[ind] and ind * 2 < len(tree): if (not updating[ind * 2] or (updating[ind * 2][1] < updating[ind][1])): tree[ind * 2] = updating[ind][0] updating[ind * 2] = updating[ind][::] if (not updating[ind * 2 + 1] or (updating[ind * 2 + 1][1] < updating[ind][1])): tree[ind * 2 + 1] = updating[ind][0] updating[ind * 2 + 1] = updating[ind][::] updating[ind] = 0 if (l == lb and r == rb): return tree[ind] else: m = (lb + rb) // 2 ans = float('inf') if (l <= m): ans = get(l, min(m, r), ind * 2, lb, m) if (r > m): ans = min(ans, get(max(l, m + 1), r, ind * 2 + 1, m + 1, rb)) return ans for time in range(1, m + 1): questions = tuple(map(int, stdin.readline().split())) if questions[0] == 1: update(questions[1], questions[2], 1, 1, size, questions[-1]) else: stdout.write('\n' + str(get(questions[1], questions[2], 1, 1, size)))
32
2,823
117,350,400
230770543
import sys import random input = sys.stdin.readline rd = random.randint(10 ** 9, 2 * 10 ** 9) class SegmentTree(): def __init__(self, init, unitX, f): self.f = f # (X, X) -> X self.unitX = unitX self.f = f if type(init) == int: self.n = init self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * (self.n * 2) else: self.n = len(init) self.n = 1 << (self.n - 1).bit_length() # len(init)が2の累乗ではない時UnitXで埋める self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init)) # 配列のindex1まで埋める for i in range(self.n - 1, 0, -1): self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) def update(self, i, x): """0-indexedのi番目の値をxで置換""" # 最下段に移動 i += self.n self.X[i] = x # 上向に更新 i >>= 1 while i: self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) i >>= 1 def getvalue(self, i): """元の配列のindexの値を見る""" return self.X[i + self.n] def getrange(self, l, r): """区間[l, r)でのfを行った値""" l += self.n r += self.n al = self.unitX ar = self.unitX while l < r: # 左端が右子ノードであれば if l & 1: al = self.f(al, self.X[l]) l += 1 # 右端が右子ノードであれば if r & 1: r -= 1 ar = self.f(self.X[r], ar) l >>= 1 r >>= 1 return self.f(al, ar) n, k = list(map(int, input().split())) a = list(map(int, input().split())) q = int(input()) queries = [list(map(int, input().split())) for _ in range(q)] min_tree = SegmentTree(a, 10 ** 9, min) p = [] for qq in queries: p.append(qq[1] - 1) p.append(qq[2] - 1) p.sort() cur = 0 pre = -1 new = [] d = dict() for i in range(len(p)): if p[i] == pre: continue if p[i] - pre > 1: if p[i] - pre > n: mi = min_tree.getrange(0, n) elif pre % n < p[i] % n: mi = min_tree.getrange(pre % n + 1, p[i] % n) else: mi = min(min_tree.getrange(pre % n + 1, n), min_tree.getrange(0, p[i] % n)) new.append(mi) cur += 1 new.append(a[p[i] % n]) d[p[i]] = cur cur += 1 pre = p[i] def push_lazy(node, left, right): if lazy[node] != 0: tree[node] = lazy[node] if left != right: lazy[node * 2] = lazy[node] lazy[node * 2 + 1] = lazy[node] lazy[node] = 0 def update(node, left, right, l, r, val): push_lazy(node, left, right) if r < left or l > right: return if l <= left and r >= right: lazy[node] = val push_lazy(node, left, right) return mid = (left + right) // 2 update(node * 2, left, mid, l, r, val) update(node * 2 + 1, mid + 1, right, l, r, val) tree[node] = min(tree[node * 2], tree[node * 2 + 1]) def query(node, left, right, l, r): push_lazy(node, left, right) if r < left or l > right: return 10**18 if l <= left and r >= right: return tree[node] mid = (left + right) // 2 sum_left = query(node * 2, left, mid, l, r) sum_right = query(node * 2 + 1, mid + 1, right, l, r) return min(sum_left, sum_right) tree = [10 ** 18] * (4 * len(new)) lazy = [0] * (4 * len(new)) for i in range(len(new)): update(1, 0, len(new) - 1, i, i, new[i]) for qq in queries: if qq[0] == 1: l, r = qq[1] - 1, qq[2] - 1 update(1, 0, len(new) - 1, d[l], d[r], qq[3]) else: l, r = qq[1] - 1, qq[2] - 1 print(query(1, 0, len(new) - 1, d[l], d[r]))
Educational Codeforces Round 20
ICPC
2,017
4
512
Periodic RMQ Problem
You are given an array a consisting of positive integers and q queries to this array. There are two types of queries: - 1 l r x — for each index i such that l ≤ i ≤ r set ai = x. - 2 l r — find the minimum among such ai that l ≤ i ≤ r. We decided that this problem is too easy. So the array a is given in a compressed form: there is an array b consisting of n elements and a number k in the input, and before all queries a is equal to the concatenation of k arrays b (so the size of a is n·k).
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 104). The second line contains n integers — elements of the array b (1 ≤ bi ≤ 109). The third line contains one integer q (1 ≤ q ≤ 105). Then q lines follow, each representing a query. Each query is given either as 1 l r x — set all elements in the segment from l till r (including borders) to x (1 ≤ l ≤ r ≤ n·k, 1 ≤ x ≤ 109) or as 2 l r — find the minimum among all elements in the segment from l till r (1 ≤ l ≤ r ≤ n·k).
For each query of type 2 print the answer to this query — the minimum on the corresponding segment.
null
null
[{"input": "3 1\n1 2 3\n3\n2 1 3\n1 1 2 4\n2 1 3", "output": "1\n3"}, {"input": "3 2\n1 2 3\n5\n2 4 4\n1 4 4 5\n2 4 4\n1 1 6 1\n2 6 6", "output": "1\n5\n1"}]
2,300
["data structures"]
32
[{"input": "3 1\r\n1 2 3\r\n3\r\n2 1 3\r\n1 1 2 4\r\n2 1 3\r\n", "output": "1\r\n3\r\n"}, {"input": "3 2\r\n1 2 3\r\n5\r\n2 4 4\r\n1 4 4 5\r\n2 4 4\r\n1 1 6 1\r\n2 6 6\r\n", "output": "1\r\n5\r\n1\r\n"}, {"input": "10 10\r\n10 8 10 9 2 2 4 6 10 1\r\n10\r\n1 17 87 5\r\n2 31 94\r\n1 5 56 8\r\n1 56 90 10\r\n1 25 93 6\r\n1 11 32 4\r\n2 20 49\r\n1 46 87 8\r\n2 14 48\r\n2 40 48\r\n", "output": "1\r\n4\r\n4\r\n6\r\n"}, {"input": "10 10\r\n4 2 3 8 1 2 1 7 5 4\r\n10\r\n2 63 87\r\n2 2 48\r\n2 5 62\r\n2 33 85\r\n2 30 100\r\n2 38 94\r\n2 7 81\r\n2 13 16\r\n2 26 36\r\n2 64 96\r\n", "output": "1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n"}, {"input": "10 10\r\n8 7 4 6 8 2 4 9 4 3\r\n10\r\n1 43 67 7\r\n1 13 73 4\r\n1 35 71 6\r\n1 9 18 8\r\n1 3 55 2\r\n1 49 67 10\r\n1 22 49 2\r\n1 66 70 6\r\n1 17 21 10\r\n1 61 77 3\r\n", "output": ""}]
false
stdio
null
true
267/A
267
A
Python 3
TESTS
1
30
0
178134468
inputs = int(input()) numbersList = [] for i in range(inputs): numbersList.append(input()) for i in range(inputs): numbers = numbersList[i].split() n1 = int(numbers[0]) n2 = int(numbers[1]) times = 0 while n1 != n2 and n1 != 0 and n2 != 0: if n1 > n2: new = n1//n2 n1 = n1 - new*n2 times += new else: new = n2//n1 n2 = n2 - new*n1 times += new print(times)
35
46
0
145791141
def main(): for _ in range(int(input())): a, b = list(map(int, input().split())) a, b = min(a, b), max(a, b) counter = 0 while a > 0 and b > 0: divisor = b // a counter += divisor b -= divisor * a a, b = b, a print(counter) if __name__ == "__main__": main()
Codeforces Testing Round 5
CF
2,013
1
256
Subtractions
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5). You've got some number of pairs (ai, bi). How many operations will be performed for each of them?
The first line contains the number of pairs n (1 ≤ n ≤ 1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1 ≤ ai, bi ≤ 109).
Print the sought number of operations for each pair on a single line.
null
null
[{"input": "2\n4 17\n7 987654321", "output": "8\n141093479"}]
900
["math", "number theory"]
35
[{"input": "2\r\n4 17\r\n7 987654321\r\n", "output": "8\r\n141093479\r\n"}, {"input": "10\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n", "output": "141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n"}, {"input": "1\r\n536870912 32\r\n", "output": "16777216\r\n"}, {"input": "20\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n", "output": "1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n"}, {"input": "3\r\n1000000000 1\r\n1000000000 1\r\n1 100000000\r\n", "output": "1000000000\r\n1000000000\r\n100000000\r\n"}]
false
stdio
null
true
267/A
267
A
Python 3
TESTS
1
31
0
204511373
n = int(input()) def solve(a, b): a, b = min(a, b), max(a, b) if a == 0 or a == b: return 0 d, r = divmod(b, a) return d + solve(r, a) for _ in range(n): a, b = (int(i) for i in input().split()) res = solve(a, b) print(res)
35
46
0
146777585
for _ in range(0, int(input())): m, M = map(int, input().split()) t = 0 while m != 0 and M != 0: m, M = sorted([m, M]) v = (M // m) M = M - (v * m) t += v print(t)
Codeforces Testing Round 5
CF
2,013
1
256
Subtractions
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5). You've got some number of pairs (ai, bi). How many operations will be performed for each of them?
The first line contains the number of pairs n (1 ≤ n ≤ 1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1 ≤ ai, bi ≤ 109).
Print the sought number of operations for each pair on a single line.
null
null
[{"input": "2\n4 17\n7 987654321", "output": "8\n141093479"}]
900
["math", "number theory"]
35
[{"input": "2\r\n4 17\r\n7 987654321\r\n", "output": "8\r\n141093479\r\n"}, {"input": "10\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n7 987654321\r\n", "output": "141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n141093479\r\n"}, {"input": "1\r\n536870912 32\r\n", "output": "16777216\r\n"}, {"input": "20\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n1000000000 999999999\r\n", "output": "1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n1000000000\r\n"}, {"input": "3\r\n1000000000 1\r\n1000000000 1\r\n1 100000000\r\n", "output": "1000000000\r\n1000000000\r\n100000000\r\n"}]
false
stdio
null
true
803/G
803
G
PyPy 3-64
TESTS
5
46
614,400
180994282
class segtree(): def __init__(self,init,func,ide): self.n=len(init) self.func=func self.ide=ide self.size=1<<(self.n-1).bit_length() self.tree=[self.ide for i in range(2*self.size)] for i in range(self.n): self.tree[self.size+i]=init[i] for i in range(self.size-1,0,-1): self.tree[i]=self.func(self.tree[2*i], self.tree[2*i|1]) def update(self,k,x): k+=self.size self.tree[k]=x k>>=1 while k: self.tree[k]=self.func(self.tree[2*k],self.tree[k*2|1]) k>>=1 def get(self,i): return self.tree[i+self.size] def query(self,l,r): l+=self.size r+=self.size l_res=self.ide r_res=self.ide while l<r: if l&1: l_res=self.func(l_res,self.tree[l]) l+=1 if r&1: r-=1 r_res=self.func(self.tree[r],r_res) l>>=1 r>>=1 return self.func(l_res,r_res) def debug(self,s=10): print([self.get(i) for i in range(min(self.n,s))]) class lazy_segtree(): def update(self,k):self.d[k]=self.op(self.d[2*k],self.d[2*k+1]) def all_apply(self,k,f): self.d[k]=self.mapping(f,self.d[k]) if (k<self.size):self.lz[k]=self.composition(f,self.lz[k]) def push(self,k): self.all_apply(2*k,self.lz[k]) self.all_apply(2*k+1,self.lz[k]) self.lz[k]=self.identity def __init__(self,V,OP,E,MAPPING,COMPOSITION,ID): self.n=len(V) self.log=(self.n-1).bit_length() self.size=1<<self.log self.d=[E for i in range(2*self.size)] self.lz=[ID for i in range(self.size)] self.e=E self.op=OP self.mapping=MAPPING self.composition=COMPOSITION self.identity=ID for i in range(self.n):self.d[self.size+i]=V[i] for i in range(self.size-1,0,-1):self.update(i) def set(self,p,x): assert 0<=p and p<self.n p+=self.size for i in range(self.log,0,-1):self.push(p>>i) self.d[p]=x for i in range(1,self.log+1):self.update(p>>i) def get(self,p): assert 0<=p and p<self.n p+=self.size for i in range(self.log,0,-1):self.push(p>>i) return self.d[p] def prod(self,l,r): assert 0<=l and l<=r and r<=self.n if l==r:return self.e l+=self.size r+=self.size for i in range(self.log,0,-1): if (((l>>i)<<i)!=l):self.push(l>>i) if (((r>>i)<<i)!=r):self.push(r>>i) sml,smr=self.e,self.e while(l<r): if l&1: sml=self.op(sml,self.d[l]) l+=1 if r&1: r-=1 smr=self.op(self.d[r],smr) l>>=1 r>>=1 return self.op(sml,smr) def all_prod(self):return self.d[1] def apply_point(self,p,f): assert 0<=p and p<self.n p+=self.size for i in range(self.log,0,-1):self.push(p>>i) self.d[p]=self.mapping(f,self.d[p]) for i in range(1,self.log+1):self.update(p>>i) def apply(self,l,r,f): assert 0<=l and l<=r and r<=self.n if l==r:return l+=self.size r+=self.size for i in range(self.log,0,-1): if (((l>>i)<<i)!=l):self.push(l>>i) if (((r>>i)<<i)!=r):self.push((r-1)>>i) l2,r2=l,r while(l<r): if (l&1): self.all_apply(l,f) l+=1 if (r&1): r-=1 self.all_apply(r,f) l>>=1 r>>=1 l,r=l2,r2 for i in range(1,self.log+1): if (((l>>i)<<i)!=l):self.update(l>>i) if (((r>>i)<<i)!=r):self.update((r-1)>>i) def max_right(self,l,g): assert 0<=l and l<=self.n assert g(self.e) if l==self.n:return self.n l+=self.size for i in range(self.log,0,-1):self.push(l>>i) sm=self.e while(1): while(l%2==0):l>>=1 if not(g(self.op(sm,self.d[l]))): while(l<self.size): self.push(l) l=(2*l) if (g(self.op(sm,self.d[l]))): sm=self.op(sm,self.d[l]) l+=1 return l-self.size sm=self.op(sm,self.d[l]) l+=1 if (l&-l)==l:break return self.n def min_left(self,r,g): assert (0<=r and r<=self.n) assert g(self.e) if r==0:return 0 r+=self.size for i in range(self.log,0,-1):self.push((r-1)>>i) sm=self.e while(1): r-=1 while(r>1 and (r%2)):r>>=1 if not(g(self.op(self.d[r],sm))): while(r<self.size): self.push(r) r=(2*r+1) if g(self.op(self.d[r],sm)): sm=self.op(self.d[r],sm) r-=1 return r+1-self.size sm=self.op(self.d[r],sm) if (r&-r)==r:break return 0 from sys import stdin input=lambda :stdin.readline()[:-1] n,k=map(int,input().split()) a=list(map(int,input().split())) s=set() query=[] q=int(input()) for _ in range(q): x=list(map(int,input().split())) if len(x)==3: x+=[-1] x[1]-=1 x[2]-=1 s.add(x[1]) if x[1]>0: s.add(x[1]-1) s.add(x[2]) if x[2]<n*k-1: s.add(x[2]+1) query.append(x) mn=min(a) seg=segtree(a+a,min,10**9+10) s=sorted(list(s)) m=len(s) res=[] d={} tmp=0 for i in range(m): if i!=0 and s[i]-s[i-1]>1: l=s[i-1]+1 r=s[i]-1 if r-l>=n-1: res.append(mn) tmp+=1 else: l%=n r%=n if l>r: l+=n res.append(seg.query(l,r+1)) tmp+=1 d[s[i]]=tmp res.append(a[s[i]%n]) tmp+=1 def operate(a,b): return min(a,b) id=10**9+10 e=10**9+10 def mapping(f,x): if f==id: return x return f def compposition(f,g): if f==id: return g return f seg=lazy_segtree(res,operate,e,mapping,compposition,id) ans=[] for t,l,r,x in query: l=d[l] r=d[r] if t==1: seg.apply(l,r+1,x) else: ans.append(seg.prod(l,r+1)) print(*ans,sep='\n')
32
2,823
117,350,400
230770543
import sys import random input = sys.stdin.readline rd = random.randint(10 ** 9, 2 * 10 ** 9) class SegmentTree(): def __init__(self, init, unitX, f): self.f = f # (X, X) -> X self.unitX = unitX self.f = f if type(init) == int: self.n = init self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * (self.n * 2) else: self.n = len(init) self.n = 1 << (self.n - 1).bit_length() # len(init)が2の累乗ではない時UnitXで埋める self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init)) # 配列のindex1まで埋める for i in range(self.n - 1, 0, -1): self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) def update(self, i, x): """0-indexedのi番目の値をxで置換""" # 最下段に移動 i += self.n self.X[i] = x # 上向に更新 i >>= 1 while i: self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1]) i >>= 1 def getvalue(self, i): """元の配列のindexの値を見る""" return self.X[i + self.n] def getrange(self, l, r): """区間[l, r)でのfを行った値""" l += self.n r += self.n al = self.unitX ar = self.unitX while l < r: # 左端が右子ノードであれば if l & 1: al = self.f(al, self.X[l]) l += 1 # 右端が右子ノードであれば if r & 1: r -= 1 ar = self.f(self.X[r], ar) l >>= 1 r >>= 1 return self.f(al, ar) n, k = list(map(int, input().split())) a = list(map(int, input().split())) q = int(input()) queries = [list(map(int, input().split())) for _ in range(q)] min_tree = SegmentTree(a, 10 ** 9, min) p = [] for qq in queries: p.append(qq[1] - 1) p.append(qq[2] - 1) p.sort() cur = 0 pre = -1 new = [] d = dict() for i in range(len(p)): if p[i] == pre: continue if p[i] - pre > 1: if p[i] - pre > n: mi = min_tree.getrange(0, n) elif pre % n < p[i] % n: mi = min_tree.getrange(pre % n + 1, p[i] % n) else: mi = min(min_tree.getrange(pre % n + 1, n), min_tree.getrange(0, p[i] % n)) new.append(mi) cur += 1 new.append(a[p[i] % n]) d[p[i]] = cur cur += 1 pre = p[i] def push_lazy(node, left, right): if lazy[node] != 0: tree[node] = lazy[node] if left != right: lazy[node * 2] = lazy[node] lazy[node * 2 + 1] = lazy[node] lazy[node] = 0 def update(node, left, right, l, r, val): push_lazy(node, left, right) if r < left or l > right: return if l <= left and r >= right: lazy[node] = val push_lazy(node, left, right) return mid = (left + right) // 2 update(node * 2, left, mid, l, r, val) update(node * 2 + 1, mid + 1, right, l, r, val) tree[node] = min(tree[node * 2], tree[node * 2 + 1]) def query(node, left, right, l, r): push_lazy(node, left, right) if r < left or l > right: return 10**18 if l <= left and r >= right: return tree[node] mid = (left + right) // 2 sum_left = query(node * 2, left, mid, l, r) sum_right = query(node * 2 + 1, mid + 1, right, l, r) return min(sum_left, sum_right) tree = [10 ** 18] * (4 * len(new)) lazy = [0] * (4 * len(new)) for i in range(len(new)): update(1, 0, len(new) - 1, i, i, new[i]) for qq in queries: if qq[0] == 1: l, r = qq[1] - 1, qq[2] - 1 update(1, 0, len(new) - 1, d[l], d[r], qq[3]) else: l, r = qq[1] - 1, qq[2] - 1 print(query(1, 0, len(new) - 1, d[l], d[r]))
Educational Codeforces Round 20
ICPC
2,017
4
512
Periodic RMQ Problem
You are given an array a consisting of positive integers and q queries to this array. There are two types of queries: - 1 l r x — for each index i such that l ≤ i ≤ r set ai = x. - 2 l r — find the minimum among such ai that l ≤ i ≤ r. We decided that this problem is too easy. So the array a is given in a compressed form: there is an array b consisting of n elements and a number k in the input, and before all queries a is equal to the concatenation of k arrays b (so the size of a is n·k).
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 104). The second line contains n integers — elements of the array b (1 ≤ bi ≤ 109). The third line contains one integer q (1 ≤ q ≤ 105). Then q lines follow, each representing a query. Each query is given either as 1 l r x — set all elements in the segment from l till r (including borders) to x (1 ≤ l ≤ r ≤ n·k, 1 ≤ x ≤ 109) or as 2 l r — find the minimum among all elements in the segment from l till r (1 ≤ l ≤ r ≤ n·k).
For each query of type 2 print the answer to this query — the minimum on the corresponding segment.
null
null
[{"input": "3 1\n1 2 3\n3\n2 1 3\n1 1 2 4\n2 1 3", "output": "1\n3"}, {"input": "3 2\n1 2 3\n5\n2 4 4\n1 4 4 5\n2 4 4\n1 1 6 1\n2 6 6", "output": "1\n5\n1"}]
2,300
["data structures"]
32
[{"input": "3 1\r\n1 2 3\r\n3\r\n2 1 3\r\n1 1 2 4\r\n2 1 3\r\n", "output": "1\r\n3\r\n"}, {"input": "3 2\r\n1 2 3\r\n5\r\n2 4 4\r\n1 4 4 5\r\n2 4 4\r\n1 1 6 1\r\n2 6 6\r\n", "output": "1\r\n5\r\n1\r\n"}, {"input": "10 10\r\n10 8 10 9 2 2 4 6 10 1\r\n10\r\n1 17 87 5\r\n2 31 94\r\n1 5 56 8\r\n1 56 90 10\r\n1 25 93 6\r\n1 11 32 4\r\n2 20 49\r\n1 46 87 8\r\n2 14 48\r\n2 40 48\r\n", "output": "1\r\n4\r\n4\r\n6\r\n"}, {"input": "10 10\r\n4 2 3 8 1 2 1 7 5 4\r\n10\r\n2 63 87\r\n2 2 48\r\n2 5 62\r\n2 33 85\r\n2 30 100\r\n2 38 94\r\n2 7 81\r\n2 13 16\r\n2 26 36\r\n2 64 96\r\n", "output": "1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n"}, {"input": "10 10\r\n8 7 4 6 8 2 4 9 4 3\r\n10\r\n1 43 67 7\r\n1 13 73 4\r\n1 35 71 6\r\n1 9 18 8\r\n1 3 55 2\r\n1 49 67 10\r\n1 22 49 2\r\n1 66 70 6\r\n1 17 21 10\r\n1 61 77 3\r\n", "output": ""}]
false
stdio
null
true
558/D
558
D
PyPy 3
TESTS
39
810
43,315,200
206006500
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline h, q = map(int, input().split()) u = [] l0, r0 = pow(2, h - 1), pow(2, h) - 1 for _ in range(q): i, l, r, a = map(int, input().split()) for _ in range(h - i): l, r = 2 * l, 2 * r + 1 if a: u.append((l, r + 1)) else: u.append((l0, l)) u.append((r + 1, r0 + 1)) s = set() for l, r in u: s.add(l) s.add(r) s = list(s) s.sort() d = dict() m = len(s) for i in range(m): d[s[i]] = i v = [0] * (m + 1) for l, r in u: v[d[l]] += 1 v[d[r]] -= 1 for i in range(1, m + 1): v[i] += v[i - 1] l, r = 0, 0 for i in range(m): if v[i] == q: l += s[i] r += s[i + 1] if l == r: ans = "Game cheated!" elif r - l > 1: ans = "Data not sufficient!" else: ans = l print(ans)
90
779
50,688,000
155784759
import sys input = sys.stdin.buffer.readline def process(h, Q): L1, R1 = 2**(h-1), 2**h-1 Q1 = [] n = 0 for i, L, R, ans in Q: L2, R2 = 2**(h-i)*L, 2**(h-i)*R+2**(h-i)-1 if ans==0: Q1.append([L2, 0, n]) Q1.append([R2, 1, n]) n+=1 else: L1 = max(L1, L2) R1 = min(R1, R2) if L1 > R1: sys.stdout.write('Game cheated!\n') return good = [] seen = 0 Q1.sort() curr = 2**(h-1) for x, t, i in Q1: if t==0: if seen==0 and x-1 >= curr: l2 = max(curr, L1) r2 = min(x-1, R1) if l2 <= r2: good.append([l2, r2]) seen+=1 curr = None else: seen-=1 if seen==0: curr = x+1 if curr <= 2**h-1: l2 = max(curr, L1) r2= min(2**h-1, R1) if l2 <= r2: good.append([l2, r2]) if len(good)==0: sys.stdout.write('Game cheated!\n') return if len(good) > 1: sys.stdout.write('Data not sufficient!\n') return l, r = good[0] if l != r: sys.stdout.write('Data not sufficient!\n') return sys.stdout.write(f'{l}\n') return h, q = [int(x) for x in input().split()] Q = [] for I in range(q): i, L, R, ans = [int(x) for x in input().split()] Q.append([i, L, R, ans]) process(h, Q)
Codeforces Round 312 (Div. 2)
CF
2,015
2
256
Guess Your Way Out! II
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the nodes of the tree such that - The root is number 1 - Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1 The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out! In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!. Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively. The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, $$ans \in \{0, 1\}$$), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
If the information provided by the game is contradictory output "Game cheated!" without the quotes. Else if you can uniquely identify the exit to the maze output its index. Otherwise output "Data not sufficient!" without the quotes.
null
Node u is an ancestor of node v if and only if - u is the same node as v, - u is the parent of node v, - or u is an ancestor of the parent of node v. In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7. In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
[{"input": "3 1\n3 4 6 0", "output": "7"}, {"input": "4 3\n4 10 14 1\n3 6 6 0\n2 3 3 1", "output": "14"}, {"input": "4 2\n3 4 6 1\n4 12 15 1", "output": "Data not sufficient!"}, {"input": "4 2\n3 4 5 1\n2 3 3 1", "output": "Game cheated!"}]
2,300
["data structures", "implementation", "sortings"]
90
[{"input": "3 1\r\n3 4 6 0\r\n", "output": "7"}, {"input": "4 3\r\n4 10 14 1\r\n3 6 6 0\r\n2 3 3 1\r\n", "output": "14"}, {"input": "4 2\r\n3 4 6 1\r\n4 12 15 1\r\n", "output": "Data not sufficient!"}, {"input": "4 2\r\n3 4 5 1\r\n2 3 3 1\r\n", "output": "Game cheated!"}, {"input": "1 0\r\n", "output": "1"}, {"input": "1 1\r\n1 1 1 0\r\n", "output": "Game cheated!"}]
false
stdio
null
true
677/A
677
A
Python 3
TESTS
3
31
0
225635104
inp = list(input()) height = list(input()) i ,gk , pk = 0 , 0 ,0 new_height = [] new_inp = [] total_height = 0 while i < len(height): k =height[i] if k != ' ': new_height.append(k) i = i+1 while gk < len(inp): k =inp[gk] if k != ' ': new_inp.append(k) gk = gk+1 kkk = len(new_height) while pk < kkk: k = new_height[pk] if k <= new_inp[1]: total_height = total_height + 1 else: total_height = total_height + 2 pk = pk + 1 print(total_height)
29
31
0
215784293
n,h = map(int,input().split()) lst = input().split() lst2 = [int(i) for i in lst] w=0 for i in lst2: if i<=h: w+=1 else: w+=2 print(w)
Codeforces Round 355 (Div. 2)
CF
2,016
1
256
Vanya and Fence
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai. Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively. The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Print a single integer — the minimum possible valid width of the road.
null
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4. In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough. In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
[{"input": "3 7\n4 5 14", "output": "4"}, {"input": "6 1\n1 1 1 1 1 1", "output": "6"}, {"input": "6 5\n7 6 8 9 10 5", "output": "11"}]
800
["implementation"]
29
[{"input": "3 7\r\n4 5 14\r\n", "output": "4\r\n"}, {"input": "6 1\r\n1 1 1 1 1 1\r\n", "output": "6\r\n"}, {"input": "6 5\r\n7 6 8 9 10 5\r\n", "output": "11\r\n"}, {"input": "10 420\r\n214 614 297 675 82 740 174 23 255 15\r\n", "output": "13\r\n"}, {"input": "10 561\r\n657 23 1096 487 785 66 481 554 1000 821\r\n", "output": "15\r\n"}, {"input": "100 342\r\n478 143 359 336 162 333 385 515 117 496 310 538 469 539 258 676 466 677 1 296 150 560 26 213 627 221 255 126 617 174 279 178 24 435 70 145 619 46 669 566 300 67 576 251 58 176 441 564 569 194 24 669 73 262 457 259 619 78 400 579 222 626 269 47 80 315 160 194 455 186 315 424 197 246 683 220 68 682 83 233 290 664 273 598 362 305 674 614 321 575 362 120 14 534 62 436 294 351 485 396\r\n", "output": "144\r\n"}, {"input": "100 290\r\n244 49 276 77 449 261 468 458 201 424 9 131 300 88 432 394 104 77 13 289 435 259 111 453 168 394 156 412 351 576 178 530 81 271 228 564 125 328 42 372 205 61 180 471 33 360 567 331 222 318 241 117 529 169 188 484 202 202 299 268 246 343 44 364 333 494 59 236 84 485 50 8 428 8 571 227 205 310 210 9 324 472 368 490 114 84 296 305 411 351 569 393 283 120 510 171 232 151 134 366\r\n", "output": "145\r\n"}, {"input": "1 1\r\n1\r\n", "output": "1\r\n"}, {"input": "1 1\r\n2\r\n", "output": "2\r\n"}, {"input": "46 71\r\n30 26 56 138 123 77 60 122 73 45 79 10 130 3 14 1 38 46 128 50 82 16 32 68 28 98 62 106 2 49 131 11 114 39 139 70 40 50 45 137 33 30 35 136 135 19\r\n", "output": "63\r\n"}, {"input": "20 723\r\n212 602 293 591 754 91 1135 640 80 495 845 928 1399 498 926 1431 1226 869 814 1386\r\n", "output": "31\r\n"}, {"input": "48 864\r\n843 1020 751 1694 18 1429 1395 1174 272 1158 1628 1233 1710 441 765 561 778 748 1501 1200 563 1263 1398 1687 1518 1640 1591 839 500 466 1603 1587 1201 1209 432 868 1159 639 649 628 9 91 1036 147 896 1557 941 518\r\n", "output": "75\r\n"}, {"input": "26 708\r\n549 241 821 734 945 1161 566 1268 216 30 1142 730 529 1014 255 168 796 1148 89 113 1328 286 743 871 1259 1397\r\n", "output": "41\r\n"}, {"input": "75 940\r\n1620 1745 1599 441 64 1466 1496 1239 1716 1475 778 106 1136 1212 1261 444 781 257 1071 747 626 232 609 1544 682 1326 469 1361 1460 1450 1207 1319 922 625 1737 1057 1698 592 692 80 1016 541 1254 201 682 1007 847 206 1066 809 259 109 240 1611 219 1455 1326 1377 1827 786 42 1002 1382 1592 543 1866 1198 334 1524 1760 340 1566 955 257 1118\r\n", "output": "116\r\n"}]
false
stdio
null
true
677/A
677
A
Python 3
TESTS
3
30
0
219456027
s = input() h = int(s[-1]) t = input() dat = t.split() ctr = 0 for ele in dat: if int(ele) > h: ctr += 2 else: ctr += 1 print(ctr)
29
31
0
216067687
n,h=map(int,input().split()) a=list(map(int,input().split())) count=0 for i in a: if i>h: count+=2 else: count+=1 print(count)
Codeforces Round 355 (Div. 2)
CF
2,016
1
256
Vanya and Fence
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai. Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively. The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Print a single integer — the minimum possible valid width of the road.
null
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4. In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough. In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
[{"input": "3 7\n4 5 14", "output": "4"}, {"input": "6 1\n1 1 1 1 1 1", "output": "6"}, {"input": "6 5\n7 6 8 9 10 5", "output": "11"}]
800
["implementation"]
29
[{"input": "3 7\r\n4 5 14\r\n", "output": "4\r\n"}, {"input": "6 1\r\n1 1 1 1 1 1\r\n", "output": "6\r\n"}, {"input": "6 5\r\n7 6 8 9 10 5\r\n", "output": "11\r\n"}, {"input": "10 420\r\n214 614 297 675 82 740 174 23 255 15\r\n", "output": "13\r\n"}, {"input": "10 561\r\n657 23 1096 487 785 66 481 554 1000 821\r\n", "output": "15\r\n"}, {"input": "100 342\r\n478 143 359 336 162 333 385 515 117 496 310 538 469 539 258 676 466 677 1 296 150 560 26 213 627 221 255 126 617 174 279 178 24 435 70 145 619 46 669 566 300 67 576 251 58 176 441 564 569 194 24 669 73 262 457 259 619 78 400 579 222 626 269 47 80 315 160 194 455 186 315 424 197 246 683 220 68 682 83 233 290 664 273 598 362 305 674 614 321 575 362 120 14 534 62 436 294 351 485 396\r\n", "output": "144\r\n"}, {"input": "100 290\r\n244 49 276 77 449 261 468 458 201 424 9 131 300 88 432 394 104 77 13 289 435 259 111 453 168 394 156 412 351 576 178 530 81 271 228 564 125 328 42 372 205 61 180 471 33 360 567 331 222 318 241 117 529 169 188 484 202 202 299 268 246 343 44 364 333 494 59 236 84 485 50 8 428 8 571 227 205 310 210 9 324 472 368 490 114 84 296 305 411 351 569 393 283 120 510 171 232 151 134 366\r\n", "output": "145\r\n"}, {"input": "1 1\r\n1\r\n", "output": "1\r\n"}, {"input": "1 1\r\n2\r\n", "output": "2\r\n"}, {"input": "46 71\r\n30 26 56 138 123 77 60 122 73 45 79 10 130 3 14 1 38 46 128 50 82 16 32 68 28 98 62 106 2 49 131 11 114 39 139 70 40 50 45 137 33 30 35 136 135 19\r\n", "output": "63\r\n"}, {"input": "20 723\r\n212 602 293 591 754 91 1135 640 80 495 845 928 1399 498 926 1431 1226 869 814 1386\r\n", "output": "31\r\n"}, {"input": "48 864\r\n843 1020 751 1694 18 1429 1395 1174 272 1158 1628 1233 1710 441 765 561 778 748 1501 1200 563 1263 1398 1687 1518 1640 1591 839 500 466 1603 1587 1201 1209 432 868 1159 639 649 628 9 91 1036 147 896 1557 941 518\r\n", "output": "75\r\n"}, {"input": "26 708\r\n549 241 821 734 945 1161 566 1268 216 30 1142 730 529 1014 255 168 796 1148 89 113 1328 286 743 871 1259 1397\r\n", "output": "41\r\n"}, {"input": "75 940\r\n1620 1745 1599 441 64 1466 1496 1239 1716 1475 778 106 1136 1212 1261 444 781 257 1071 747 626 232 609 1544 682 1326 469 1361 1460 1450 1207 1319 922 625 1737 1057 1698 592 692 80 1016 541 1254 201 682 1007 847 206 1066 809 259 109 240 1611 219 1455 1326 1377 1827 786 42 1002 1382 1592 543 1866 1198 334 1524 1760 340 1566 955 257 1118\r\n", "output": "116\r\n"}]
false
stdio
null
true
558/D
558
D
Python 3
TESTS
5
607
16,076,800
12328408
#!/usr/bin/env python # -*- coding: utf-8 -*- def ReadIn(): height, n = [int(x) for x in input().split()] queries = [tuple(int(x) for x in input().split()) for q in range(n)] return height, queries def MoveToLeaves(height, queries): leaves = [] for level, left, right, yn in queries: shift = height - level leaves.append(tuple([ left << shift, (right << shift) | ((1 << shift) - 1), yn])) return leaves def RangeIntersection(ranges): # print(ranges) ret = ranges[0][:2] for r in ranges: ret = (max(r[0], ret[0]), min(r[1], ret[1])) return ret def RangeUnion(ranges): if len(ranges) == 0: return [] ranges.sort(key=lambda r: r[0]) ret = [] now = ranges[0][:2] for r in ranges: if r[0] > now[1] + 1: ret.append(now) now = r else: now = (now[0], r[1]) ret.append(now) return ret def Solve(height, queries): # print(height, queries) queries = MoveToLeaves(height, queries) # print(queries) range_in = RangeIntersection( [(1 << (height - 1), (1 << height) - 1, 1)] + list(filter(lambda q: q[2] == 1, queries))) # print(range_in) ranges_out = RangeUnion( list(filter(lambda q: q[2] == 0, queries))) # print(ranges_out) if range_in[0] > range_in[1]: print('Game cheated!') return for r in ranges_out: if r[0] <= range_in[0] and range_in[1] <= r[1]: print('Game cheated!') return if range_in[0] < r[0] and r[1] < range_in[1]: print('Data not sufficient!') return for r in ranges_out: if r[0] == range_in[0] + 1: print(range_in[0]) return if r[1] == range_in[1] - 1: print(range_in[1]) return for l, r in zip(ranges_out[:-1], ranges_out[1:]): if r[0] - l[1] == 2: continue pos = l[0] + 1 if range_in[0] <= pos <= range_in[1]: print(pos) return print('Data not sufficient!') if __name__ == '__main__': height, queries = ReadIn() Solve(height, queries)
90
1,076
16,998,400
12062622
h,q=map(int,input().split()) d=[(2**h,0),(2**(h-1),0)] for _ in range(q): i,l,r,a=map(int,input().split()) l,r=l*2**(h-i),(r+1)*2**(h-i) d.extend([[(l,1),(r,-1)],[(0,1),(l,-1),(r,1)]][a]) s=0 l=0 d=sorted(d) for (a,x),(b,_) in zip(d,d[1:]): s+=x if a!=b and s==0:q=a;l+=b-a print(("Game cheated!",q,"Data not sufficient!")[min(l,2)])
Codeforces Round 312 (Div. 2)
CF
2,015
2
256
Guess Your Way Out! II
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the nodes of the tree such that - The root is number 1 - Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1 The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out! In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!. Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively. The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, $$ans \in \{0, 1\}$$), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
If the information provided by the game is contradictory output "Game cheated!" without the quotes. Else if you can uniquely identify the exit to the maze output its index. Otherwise output "Data not sufficient!" without the quotes.
null
Node u is an ancestor of node v if and only if - u is the same node as v, - u is the parent of node v, - or u is an ancestor of the parent of node v. In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7. In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
[{"input": "3 1\n3 4 6 0", "output": "7"}, {"input": "4 3\n4 10 14 1\n3 6 6 0\n2 3 3 1", "output": "14"}, {"input": "4 2\n3 4 6 1\n4 12 15 1", "output": "Data not sufficient!"}, {"input": "4 2\n3 4 5 1\n2 3 3 1", "output": "Game cheated!"}]
2,300
["data structures", "implementation", "sortings"]
90
[{"input": "3 1\r\n3 4 6 0\r\n", "output": "7"}, {"input": "4 3\r\n4 10 14 1\r\n3 6 6 0\r\n2 3 3 1\r\n", "output": "14"}, {"input": "4 2\r\n3 4 6 1\r\n4 12 15 1\r\n", "output": "Data not sufficient!"}, {"input": "4 2\r\n3 4 5 1\r\n2 3 3 1\r\n", "output": "Game cheated!"}, {"input": "1 0\r\n", "output": "1"}, {"input": "1 1\r\n1 1 1 0\r\n", "output": "Game cheated!"}]
false
stdio
null
true
846/F
846
F
PyPy 3-64
TESTS
4
187
22,016,000
210551799
import math import random import time from decimal import * def binary_search(vector,valoarea): left=0 right=len(vector)-1 while left<=right: centru=(left+right)//2 # print(left,right,centru,vector[centru]) if vector[centru]<valoarea: left=centru+1 else: right=centru-1 # print(left,right,centru,vector[centru]) return left from collections import defaultdict def main(): answ=[] pp=10**9 rest=10**9+7 #teste=int(input()) for gg in range(1): n=int(input()) #n,m=list(map(int,input().split())) vector=list(map(int,input().split())) last=[-1]*1000001 suma=1 sume=[1]*(n) last[vector[0]]=0 for i in range(1,n): if vector[i]==vector[i-1]: sume[i]=1+sume[i-1] else: sume[i]=sume[i-1]+(i-last[vector[i]]-1)+1 last[vector[i]]=i suma+=sume[i] patrat=n*n answ=Decimal((2*suma-n)/patrat) print(answ) # print(sume) # print(suma) main()
31
951
75,161,600
93377821
import sys from collections import defaultdict n = int(sys.stdin.buffer.readline().decode('utf-8')) a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split())) next_dic = defaultdict(list) for i in range(n-1, -1, -1): next_dic[a[i]].append(i) fx = sum((n-v[-1])*2 for v in next_dic.values()) ans = 0 for i in range(n): j = next_dic[a[i]].pop() ans += fx - 1 fx += -(n - j)*2 + (n - next_dic[a[i]][-1] if next_dic[a[i]] else 0)*2 print(ans / (n*n))
Educational Codeforces Round 28
ICPC
2,017
2
256
Random Query
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed).
The first line contains one integer number n (1 ≤ n ≤ 106). The second line contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 106) — elements of the array.
Print one number — the expected number of unique elements in chosen segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 — formally, the answer is correct if $${ \operatorname* { m i n } } ( | x - y |, { \frac { | x - y | } { x } } ) \leq 1 0 ^ { - 4 }$$, where x is jury's answer, and y is your answer.
null
null
[{"input": "2\n1 2", "output": "1.500000"}, {"input": "2\n2 2", "output": "1.000000"}]
1,800
["data structures", "math", "probabilities", "two pointers"]
31
[{"input": "2\r\n1 2\r\n", "output": "1.500000\r\n"}, {"input": "2\r\n2 2\r\n", "output": "1.000000\r\n"}, {"input": "10\r\n9 6 8 5 5 2 8 9 2 2\r\n", "output": "3.100000\r\n"}, {"input": "20\r\n49 33 9 8 50 21 12 44 23 39 24 10 17 4 17 40 24 19 27 21\r\n", "output": "7.010000\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1.000000\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] correct_output_path = sys.argv[2] submission_output_path = sys.argv[3] # Read correct output with open(correct_output_path, 'r') as f: correct_line = f.readline().strip() x = float(correct_line) # Read submission output with open(submission_output_path, 'r') as f: submission_line = f.readline().strip() try: y = float(submission_line) except: # Invalid output format, score 0 print(0) return # Compute errors absolute_error = abs(x - y) if absolute_error <= 1e-4: print(1) return # Compute relative error relative_error = absolute_error / x if relative_error <= 1e-4: print(1) else: print(0) if __name__ == "__main__": main()
true
677/A
677
A
Python 3
TESTS
3
31
0
225634260
x,y = input().split() height = list(input()) i , pk = 0 , 0 new_height = [] total_height = 0 while i < len(height): k =height[i] if k != ' ': new_height.append(k) i = i+1 kkk = len(new_height) while pk < kkk: k = new_height[pk] if k <= y: total_height = total_height + 1 else: total_height = total_height + 2 pk = pk + 1 print(total_height)
29
31
0
216662568
ip = input().split(" ") heights = input().split(" ") width = 0 n = ip[0] fence = ip[1] for i in range(len(heights)): if int(heights[i]) > int(fence): width += 2 else: width += 1 print(int(width))
Codeforces Round 355 (Div. 2)
CF
2,016
1
256
Vanya and Fence
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai. Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively. The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.
Print a single integer — the minimum possible valid width of the road.
null
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4. In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough. In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
[{"input": "3 7\n4 5 14", "output": "4"}, {"input": "6 1\n1 1 1 1 1 1", "output": "6"}, {"input": "6 5\n7 6 8 9 10 5", "output": "11"}]
800
["implementation"]
29
[{"input": "3 7\r\n4 5 14\r\n", "output": "4\r\n"}, {"input": "6 1\r\n1 1 1 1 1 1\r\n", "output": "6\r\n"}, {"input": "6 5\r\n7 6 8 9 10 5\r\n", "output": "11\r\n"}, {"input": "10 420\r\n214 614 297 675 82 740 174 23 255 15\r\n", "output": "13\r\n"}, {"input": "10 561\r\n657 23 1096 487 785 66 481 554 1000 821\r\n", "output": "15\r\n"}, {"input": "100 342\r\n478 143 359 336 162 333 385 515 117 496 310 538 469 539 258 676 466 677 1 296 150 560 26 213 627 221 255 126 617 174 279 178 24 435 70 145 619 46 669 566 300 67 576 251 58 176 441 564 569 194 24 669 73 262 457 259 619 78 400 579 222 626 269 47 80 315 160 194 455 186 315 424 197 246 683 220 68 682 83 233 290 664 273 598 362 305 674 614 321 575 362 120 14 534 62 436 294 351 485 396\r\n", "output": "144\r\n"}, {"input": "100 290\r\n244 49 276 77 449 261 468 458 201 424 9 131 300 88 432 394 104 77 13 289 435 259 111 453 168 394 156 412 351 576 178 530 81 271 228 564 125 328 42 372 205 61 180 471 33 360 567 331 222 318 241 117 529 169 188 484 202 202 299 268 246 343 44 364 333 494 59 236 84 485 50 8 428 8 571 227 205 310 210 9 324 472 368 490 114 84 296 305 411 351 569 393 283 120 510 171 232 151 134 366\r\n", "output": "145\r\n"}, {"input": "1 1\r\n1\r\n", "output": "1\r\n"}, {"input": "1 1\r\n2\r\n", "output": "2\r\n"}, {"input": "46 71\r\n30 26 56 138 123 77 60 122 73 45 79 10 130 3 14 1 38 46 128 50 82 16 32 68 28 98 62 106 2 49 131 11 114 39 139 70 40 50 45 137 33 30 35 136 135 19\r\n", "output": "63\r\n"}, {"input": "20 723\r\n212 602 293 591 754 91 1135 640 80 495 845 928 1399 498 926 1431 1226 869 814 1386\r\n", "output": "31\r\n"}, {"input": "48 864\r\n843 1020 751 1694 18 1429 1395 1174 272 1158 1628 1233 1710 441 765 561 778 748 1501 1200 563 1263 1398 1687 1518 1640 1591 839 500 466 1603 1587 1201 1209 432 868 1159 639 649 628 9 91 1036 147 896 1557 941 518\r\n", "output": "75\r\n"}, {"input": "26 708\r\n549 241 821 734 945 1161 566 1268 216 30 1142 730 529 1014 255 168 796 1148 89 113 1328 286 743 871 1259 1397\r\n", "output": "41\r\n"}, {"input": "75 940\r\n1620 1745 1599 441 64 1466 1496 1239 1716 1475 778 106 1136 1212 1261 444 781 257 1071 747 626 232 609 1544 682 1326 469 1361 1460 1450 1207 1319 922 625 1737 1057 1698 592 692 80 1016 541 1254 201 682 1007 847 206 1066 809 259 109 240 1611 219 1455 1326 1377 1827 786 42 1002 1382 1592 543 1866 1198 334 1524 1760 340 1566 955 257 1118\r\n", "output": "116\r\n"}]
false
stdio
null
true
175/B
175
B
Python 3
TESTS
0
154
0
53661028
n = int(input()) d = {} for i in range(n): s, v = input().split() d[s] = max(d.get(s,0), int(v)) print(len(d)) for i in d: c = 0 for j in d: if (d[j] > d[i]): c += 1 if (c * 2 > n): res = "noob" elif (c * 5 > n): res = "random" elif (c * 10 > n): res = "average" elif (c * 100 > n): res = "hardcore" else: res = "pro" print(i, res)
46
186
1,740,800
168027864
import sys input = sys.stdin.readline def rank(q): a = q/m * 100 if a < 50: return 'noob' elif a < 80: return 'random' elif a < 90: return 'average' elif a < 99: return 'hardcore' else: return 'pro' n = int(input()) d = dict() for _ in range(n): a, b = input()[:-1].split() b = int(b) if d.get(a, 0) == 0: d[a] = b else: d[a] = max(d[a], b) m = len(d) s = dict() for i in d: if s.get(d[i], 0) == 0: s[d[i]] = [i] else: s[d[i]].append(i) d = sorted([(i, s[i], len(s[i])) for i in s]) e = [] c = 0 for x, w, i in d: c += i r = rank(c) for j in w: e.append((j, r)) print(len(e)) for i in e: print(' '.join(i))
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/E
559
E
Python 3
TESTS
2
46
307,200
109825401
no = int(input()) details = [] for _ in range(no): v = input().split() v[0] = int(v[0]) v[1] = int(v[1]) details.append(v) details.sort() ans = 0 for i in range(no): if i==0 or i==(no-1): ans+=details[i][1] else: if details[i-1][0]<details[i+1][0]: ans+=details[i-1][1] else: ans+=details[i+1][1] print(ans)
90
342
20,787,200
163409586
import dataclasses import sys inf = float('inf') # change stdout buffer size buffer = open(1, 'w', 10**6) # fast printing function def print(*args, sep=' ', end='\n'): buffer.write(sep.join(str(arg) for arg in args) + end) # flush stdout def flush(): buffer.flush() def read_ints(index=None): if index is not None: return [(int(x), i + index) for i, x in enumerate(sys.stdin.readline().split())] return [int(x) for x in sys.stdin.readline().split()] def solve(n, x, y): vs = set() for i in range(n): vs.add(x[i] - y[i]) vs.add(x[i]) vs.add(x[i] + y[i]) v = list(vs) v.sort() nv = len(v) ind = dict() for i in range(nv): ind[v[i]] = i forward = [0] * nv backward = [[] for _ in range(nv)] for i in range(n): a = ind[x[i] - y[i]] b = ind[x[i]] c = ind[x[i] + y[i]] forward[b] = c backward[a].append(b) dp = [[[0, 0] for _ in range(nv)] for _ in range(nv)] for i in range(nv - 2, -1, -1): for j in range(nv - 2, i - 1, -1): for t in range(2): if i + 1 > j: cur = dp[i+1][i+1][0] else: cur = dp[i + 1][j][t] if (t == 0 or j > i) and forward[i] > j: cur = max(cur, dp[j + 1 if t else i + 1][forward[i]][0] + v[forward[i]] - v[j]) for k in backward[i]: if k > j: cur = max(cur, dp[j + 1 if t else i + 1][k][1] + v[k] - v[j]) dp[i][j][t] = cur print(dp[0][0][0]) flush() def read(): n = int(input()) x = [0] * n y = [0] * n for i in range(n): x[i], y[i] = read_ints() return n, x, y if __name__ == '__main__': n, x, y = read() solve(n, x, y)
Codeforces Round 313 (Div. 1)
CF
2,015
4
256
Gerald and Path
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight. The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument. You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
The first line contains integer n (1 ≤ n ≤ 100) — the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≤ ai ≤ 108, 1 ≤ li ≤ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates. It is guaranteed that all the ai's are distinct.
Print a single integer — the maximum total length of the illuminated part of the path.
null
null
[{"input": "3\n1 1\n2 2\n3 3", "output": "5"}, {"input": "4\n1 2\n3 3\n4 3\n6 2", "output": "9"}]
3,000
["dp", "sortings"]
90
[{"input": "3\r\n1 1\r\n2 2\r\n3 3\r\n", "output": "5\r\n"}, {"input": "4\r\n1 2\r\n3 3\r\n4 3\r\n6 2\r\n", "output": "9\r\n"}, {"input": "5\r\n3 3\r\n4 1\r\n2 2\r\n0 3\r\n9 5\r\n", "output": "13\r\n"}, {"input": "5\r\n3 3\r\n4 3\r\n6 4\r\n2 3\r\n1 5\r\n", "output": "14\r\n"}, {"input": "5\r\n1 2\r\n7 5\r\n9 4\r\n5 1\r\n3 5\r\n", "output": "13\r\n"}, {"input": "5\r\n7 2\r\n3 5\r\n2 4\r\n8 1\r\n9 5\r\n", "output": "15\r\n"}, {"input": "5\r\n7 1\r\n5 5\r\n1 4\r\n4 4\r\n2 2\r\n", "output": "12\r\n"}, {"input": "5\r\n9 5\r\n2 4\r\n3 3\r\n5 2\r\n1 1\r\n", "output": "13\r\n"}, {"input": "3\r\n0 3\r\n3 3\r\n6 3\r\n", "output": "9\r\n"}, {"input": "3\r\n0 3\r\n4 3\r\n7 3\r\n", "output": "9\r\n"}, {"input": "10\r\n78329099 25986078\r\n9003418 30942874\r\n32350045 8429148\r\n78842461 58122669\r\n89820027 42334842\r\n76809240 3652872\r\n77832962 54942701\r\n76760300 50934062\r\n53414406 14348704\r\n3119584 40577983\r\n", "output": "168539695\r\n"}, {"input": "10\r\n7117 86424\r\n87771 51337\r\n12429 34872\r\n53590 17922\r\n54806 13188\r\n8575 11567\r\n73589 76161\r\n71136 14076\r\n85527 6121\r\n83455 12523\r\n", "output": "227599\r\n"}, {"input": "10\r\n228 4\r\n833 58\r\n27 169\r\n775 658\r\n981 491\r\n979 310\r\n859 61\r\n740 324\r\n747 126\r\n785 410\r\n", "output": "1524\r\n"}, {"input": "4\r\n66 61\r\n715 254\r\n610 297\r\n665 41\r\n", "output": "653\r\n"}, {"input": "5\r\n44326737 210514\r\n61758935 9618\r\n34426105 9900632\r\n34195486 5323398\r\n28872088 135139\r\n", "output": "15579301\r\n"}, {"input": "5\r\n44549379 754619\r\n29429248 66713\r\n88414664 12793\r\n37846422 8417174\r\n38662784 5886595\r\n", "output": "15137894\r\n"}, {"input": "1\r\n100 50\r\n", "output": "50\r\n"}, {"input": "20\r\n22164537 5600930\r\n22164533 5600930\r\n22164538 5600930\r\n22164526 5600930\r\n22164527 5600930\r\n22164539 5600930\r\n22164528 5600930\r\n22164542 5600930\r\n22164544 5600930\r\n22164543 5600930\r\n22164530 5600930\r\n22164529 5600930\r\n22164536 5600930\r\n22164540 5600930\r\n22164531 5600930\r\n22164541 5600930\r\n22164535 5600930\r\n22164534 5600930\r\n22164525 5600930\r\n22164532 5600930\r\n", "output": "11201879\r\n"}, {"input": "5\r\n7339431 13372\r\n11434703 8326\r\n9158453 15156\r\n8266053 926622\r\n8286111 872342\r\n", "output": "1835818\r\n"}, {"input": "5\r\n23742227 754619\r\n8622096 66713\r\n37249276 12793\r\n17039270 8417174\r\n17855632 5886595\r\n", "output": "15137894\r\n"}, {"input": "10\r\n200 100\r\n1000100 1000000\r\n1000200 1000000\r\n2000100 89\r\n1000155 13\r\n1000159 1\r\n1000121 12\r\n1000111 1\r\n1000105 3\r\n1000195 13\r\n", "output": "2000089\r\n"}]
false
stdio
null
true
675/C
675
C
Python 3
TESTS
4
62
4,608,000
18105101
n = int(input()) a = list(map(int,input().split())) if a == [0]*n: print(0) exit(0) dp1 = [0]*n dp1[0] = a[0] dp2 = {a[0]:0} res = 0 last = 0 for i in range(1, n): dp1[i] = dp1[i-1]+a[i] if dp1[i] in dp2: res += 1 for j in range(last, i): dp2.pop(dp1[j]) last = i dp2[dp1[i]] = i if len(dp2) > 1: res += 1 print(n-res)
41
109
15,667,200
217255153
n = int(input()) a = list(map(int, input().split())) p = [0] * n p[0] = a[0] for i in range(1, n): p[i] = a[i] + p[i - 1] p.sort() p.append(float('inf')) ans = 0 i = 0 while i < n: j = i while p[j] == p[i]: j += 1 ans = max(ans, j - i) i = j print(n - ans)# 1691240835.7281392
Codeforces Round 353 (Div. 2)
CF
2,016
1
256
Money Transfers
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank. There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation. Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Print the minimum number of operations required to change balance in each bank to zero.
null
In the first sample, Vasya may transfer 5 from the first bank to the third. In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first. In the third sample, the following sequence provides the optimal answer: 1. transfer 1 from the first bank to the second bank; 2. transfer 3 from the second bank to the third; 3. transfer 6 from the third bank to the fourth.
[{"input": "3\n5 0 -5", "output": "1"}, {"input": "4\n-1 0 1 0", "output": "2"}, {"input": "4\n1 2 3 -6", "output": "3"}]
2,100
["constructive algorithms", "data structures", "greedy", "sortings"]
41
[{"input": "3\r\n5 0 -5\r\n", "output": "1\r\n"}, {"input": "4\r\n-1 0 1 0\r\n", "output": "2\r\n"}, {"input": "4\r\n1 2 3 -6\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "50\r\n108431864 128274949 -554057370 -384620666 -202862975 -803855410 -482167063 -55139054 -215901009 0 0 0 0 0 94325701 730397219 358214459 -673647271 -131397668 -377892440 0 0 0 0 0 -487994257 -360271553 639988328 489338210 -281060728 250208758 0 993242346 -213071841 -59752620 -864351041 -114363541 506279952 999648597 -173503559 -144629749 -559693009 0 -46793577 511999017 -343503822 -741715911 647437511 821346413 993112810\r\n", "output": "36\r\n"}, {"input": "6\r\n1 -1 1 -1 1 -1\r\n", "output": "3\r\n"}]
false
stdio
null
true
675/C
675
C
Python 3
TESTS
4
62
4,608,000
18104524
n = int(input()) a = list(map(int,input().split())) if a == [0]*n: print(0) exit(0) f = 0 for i in range(n): if a[i] != 0: f = i break res = 0 tmp = 0 s = 0 for j in range(f, f+n): i = j % n s += a[i] if s == 0: res += tmp tmp = 0 else: tmp += 1 a = a[::-1] f = n-f-1 res1 = 0 tmp = 0 s = 0 for j in range(f, f+n): i = j % n s += a[i] if s == 0: res1 += tmp tmp = 0 else: tmp += 1 print(min(res,res1))
41
124
11,264,000
19615409
n = int(input()) a = list(map(int, input().split())) search = dict() sum = 0 for b in a: sum += b if not sum in search: search[sum] = 1 else: search[sum] += 1 print(n - max(search.values()))
Codeforces Round 353 (Div. 2)
CF
2,016
1
256
Money Transfers
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank. There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation. Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Print the minimum number of operations required to change balance in each bank to zero.
null
In the first sample, Vasya may transfer 5 from the first bank to the third. In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first. In the third sample, the following sequence provides the optimal answer: 1. transfer 1 from the first bank to the second bank; 2. transfer 3 from the second bank to the third; 3. transfer 6 from the third bank to the fourth.
[{"input": "3\n5 0 -5", "output": "1"}, {"input": "4\n-1 0 1 0", "output": "2"}, {"input": "4\n1 2 3 -6", "output": "3"}]
2,100
["constructive algorithms", "data structures", "greedy", "sortings"]
41
[{"input": "3\r\n5 0 -5\r\n", "output": "1\r\n"}, {"input": "4\r\n-1 0 1 0\r\n", "output": "2\r\n"}, {"input": "4\r\n1 2 3 -6\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "50\r\n108431864 128274949 -554057370 -384620666 -202862975 -803855410 -482167063 -55139054 -215901009 0 0 0 0 0 94325701 730397219 358214459 -673647271 -131397668 -377892440 0 0 0 0 0 -487994257 -360271553 639988328 489338210 -281060728 250208758 0 993242346 -213071841 -59752620 -864351041 -114363541 506279952 999648597 -173503559 -144629749 -559693009 0 -46793577 511999017 -343503822 -741715911 647437511 821346413 993112810\r\n", "output": "36\r\n"}, {"input": "6\r\n1 -1 1 -1 1 -1\r\n", "output": "3\r\n"}]
false
stdio
null
true
175/B
175
B
Python 3
TESTS
0
60
0
214357609
n = int(input()) d = {} for _ in range(n): a,b = input().split() if a in d: d[a] = max(int(b),d[a]) else: d[a] = int(int(b)) print(len(d)) for s in d: k=0 for y in d: if d[y]>d[s]: k+=1 if k*2>n: print(s,"noob") elif k*5>n: print(s,"random") elif k*10>n: print(s,"average") elif k*100>n: print(s,"hardcore") else: print(s,"pro")
46
218
307,200
98247277
n = int(input()) dic = {} length = 0 for i in range(n): player,score = input().split() score = int(score) if player not in dic: dic[player] = score length += 1 else: if dic[player]<score: dic[player] = score sortd_values = sorted(dic.values(),reverse=True) print(length) for key in dic: index = sortd_values.index(dic[key]) t = (index/length)*100 if t>50: print(key,'noob') elif t>20: print(key,'random') elif t>10: print(key,'average') elif t>1: print(key,'hardcore') else: print(key,'pro')
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
594/A
594
A
Python 3
TESTS
3
31
0
172342090
n = int(input()) arr = list(map(int,input().split()))[:n] a = arr[1:n] print(abs(arr[0]-a[(n-1)//2]))
50
202
16,179,200
189262992
# LUOGU_RID: 99814222 ans=0x3f3f3f3f n=int(input()) a=list(map(int,input().split())) b=n//2 a.sort() for i in range(b): ans=min(ans,a[b+i]-a[i]) print(ans)
Codeforces Round 330 (Div. 1)
CF
2,015
2
256
Warrior and Archer
In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest. Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible. There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x1, x2, ..., xn, two characters cannot end up at the same position. Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting. Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.
The first line on the input contains a single integer n (2 ≤ n ≤ 200 000, n is even) — the number of positions available initially. The second line contains n distinct integers x1, x2, ..., xn (0 ≤ xi ≤ 109), giving the coordinates of the corresponding positions.
Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.
null
In the first sample one of the optimum behavior of the players looks like that: 1. Vova bans the position at coordinate 15; 2. Lesha bans the position at coordinate 3; 3. Vova bans the position at coordinate 31; 4. Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7. In the second sample there are only two possible positions, so there will be no bans.
[{"input": "6\n0 1 3 7 15 31", "output": "7"}, {"input": "2\n73 37", "output": "36"}]
2,300
["games"]
50
[{"input": "6\r\n0 1 3 7 15 31\r\n", "output": "7\r\n"}, {"input": "2\r\n73 37\r\n", "output": "36\r\n"}, {"input": "2\r\n0 1000000000\r\n", "output": "1000000000\r\n"}, {"input": "8\r\n729541013 135019377 88372488 319157478 682081360 558614617 258129110 790518782\r\n", "output": "470242129\r\n"}, {"input": "2\r\n0 1\r\n", "output": "1\r\n"}, {"input": "8\r\n552283832 997699491 89302459 301640204 288141798 31112026 710831619 862166501\r\n", "output": "521171806\r\n"}, {"input": "4\r\n0 500000000 500000001 1000000000\r\n", "output": "500000000\r\n"}, {"input": "18\r\n515925896 832652240 279975694 570998878 28122427 209724246 898414431 709461320 358922485 439508829 403574907 358500312 596248410 968234748 187793884 728450713 30350176 528924900\r\n", "output": "369950401\r\n"}, {"input": "20\r\n713900269 192811911 592111899 609607891 585084800 601258511 223103775 876894656 751583891 230837577 971499807 312977833 344314550 397998873 558637732 216574673 913028292 762852863 464376621 61315042\r\n", "output": "384683838\r\n"}, {"input": "10\r\n805513144 38998401 16228409 266085559 293487744 471510400 138613792 649258082 904651590 244678415\r\n", "output": "277259335\r\n"}, {"input": "6\r\n0 166666666 333333333 499999998 666666665 833333330\r\n", "output": "499999997\r\n"}, {"input": "16\r\n1 62500001 125000001 187500000 250000000 312500000 375000000 437500001 500000000 562500000 625000000 687500001 750000001 812500002 875000002 937500000\r\n", "output": "499999999\r\n"}, {"input": "12\r\n5 83333336 166666669 250000001 333333336 416666670 500000004 583333336 666666667 750000001 833333334 916666671\r\n", "output": "499999998\r\n"}, {"input": "20\r\n54 50000046 100000041 150000049 200000061 250000039 300000043 350000054 400000042 450000045 500000076 550000052 600000064 650000065 700000055 750000046 800000044 850000042 900000052 950000054\r\n", "output": "499999988\r\n"}]
false
stdio
null
true
675/C
675
C
Python 3
TESTS
4
77
7,065,600
36379325
import math as m n=int(input()) a=list(map(int,input().split())) ans1=0 ans2=0 curr=0 i=0 while i<n: if curr!=0: ans1+=1 curr+=a[i] else: curr+=a[i] i+=1 curr=0 b=[] b.append(a[0]) for i in reversed(a): b.append(i) i=0 curr=0 while i<n: if curr!=0: ans2+=1 curr+=b[i] else: curr+=b[i] i+=1 print(min(ans1,ans2))
41
140
12,800,000
18990549
n = int(input()) a = map(int,input().split()) search =dict() sum=0 for b in a: sum+=b if not sum in search: search[sum] = 1 else: search[sum] +=1 print(n-max(search.values()))
Codeforces Round 353 (Div. 2)
CF
2,016
1
256
Money Transfers
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank. There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation. Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Print the minimum number of operations required to change balance in each bank to zero.
null
In the first sample, Vasya may transfer 5 from the first bank to the third. In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first. In the third sample, the following sequence provides the optimal answer: 1. transfer 1 from the first bank to the second bank; 2. transfer 3 from the second bank to the third; 3. transfer 6 from the third bank to the fourth.
[{"input": "3\n5 0 -5", "output": "1"}, {"input": "4\n-1 0 1 0", "output": "2"}, {"input": "4\n1 2 3 -6", "output": "3"}]
2,100
["constructive algorithms", "data structures", "greedy", "sortings"]
41
[{"input": "3\r\n5 0 -5\r\n", "output": "1\r\n"}, {"input": "4\r\n-1 0 1 0\r\n", "output": "2\r\n"}, {"input": "4\r\n1 2 3 -6\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "50\r\n108431864 128274949 -554057370 -384620666 -202862975 -803855410 -482167063 -55139054 -215901009 0 0 0 0 0 94325701 730397219 358214459 -673647271 -131397668 -377892440 0 0 0 0 0 -487994257 -360271553 639988328 489338210 -281060728 250208758 0 993242346 -213071841 -59752620 -864351041 -114363541 506279952 999648597 -173503559 -144629749 -559693009 0 -46793577 511999017 -343503822 -741715911 647437511 821346413 993112810\r\n", "output": "36\r\n"}, {"input": "6\r\n1 -1 1 -1 1 -1\r\n", "output": "3\r\n"}]
false
stdio
null
true
675/C
675
C
PyPy 3
TESTS
4
124
0
82404119
n = int(input()) a = list(map(int,input().split())) a.append(a[0]) ct1,s = 0,0 for i in range(n): s += a[i] if(s != 0): ct1 += 1 ct2,s = 0,0 for i in range(n,0,-1): s += a[i] if(s != 0): ct2 += 1 print(min(ct1,ct2))
41
155
16,384,000
26412739
n=int(input()) a=list(map(int,input().split())) d,s={},0 for i in range(n): s+=a[i] if s not in d:d[s]=0 d[s]+=1 print(n-max(d.values()))
Codeforces Round 353 (Div. 2)
CF
2,016
1
256
Money Transfers
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank. There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation. Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Print the minimum number of operations required to change balance in each bank to zero.
null
In the first sample, Vasya may transfer 5 from the first bank to the third. In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first. In the third sample, the following sequence provides the optimal answer: 1. transfer 1 from the first bank to the second bank; 2. transfer 3 from the second bank to the third; 3. transfer 6 from the third bank to the fourth.
[{"input": "3\n5 0 -5", "output": "1"}, {"input": "4\n-1 0 1 0", "output": "2"}, {"input": "4\n1 2 3 -6", "output": "3"}]
2,100
["constructive algorithms", "data structures", "greedy", "sortings"]
41
[{"input": "3\r\n5 0 -5\r\n", "output": "1\r\n"}, {"input": "4\r\n-1 0 1 0\r\n", "output": "2\r\n"}, {"input": "4\r\n1 2 3 -6\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "50\r\n108431864 128274949 -554057370 -384620666 -202862975 -803855410 -482167063 -55139054 -215901009 0 0 0 0 0 94325701 730397219 358214459 -673647271 -131397668 -377892440 0 0 0 0 0 -487994257 -360271553 639988328 489338210 -281060728 250208758 0 993242346 -213071841 -59752620 -864351041 -114363541 506279952 999648597 -173503559 -144629749 -559693009 0 -46793577 511999017 -343503822 -741715911 647437511 821346413 993112810\r\n", "output": "36\r\n"}, {"input": "6\r\n1 -1 1 -1 1 -1\r\n", "output": "3\r\n"}]
false
stdio
null
true
245/A
245
A
Python 3
TESTS
3
60
0
169204946
for _ in range(int(input())): s,l,d=map(int,input().split()) if s==1: a=(l,d) else: b=(l,d) print("LIVE" if a[0]>=a[1] else "DEAD") print("LIVE" if b[0]>=b[1] else "DEAD")
13
78
102,400
4010030
n=int(input()) live1, dead1, live2, dead2 = 0, 0, 0, 0 for i in range(n): I=[int(j) for j in input().split()] if I[0]==1: live1+=I[1] dead1+=I[2] else: live2+=I[1] dead2+=I[2] if live1>=(live1+dead1)/2: print('LIVE') else: print('DEAD') if live2>=(live2+dead2)/2: print('LIVE') else: print('DEAD')
CROC-MBTU 2012, Elimination Round (ACM-ICPC)
ICPC
2,012
2
256
System Administrator
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost. Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.
null
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
[{"input": "2\n1 5 5\n2 6 4", "output": "LIVE\nLIVE"}, {"input": "3\n1 0 10\n2 0 10\n1 10 0", "output": "LIVE\nDEAD"}]
800
["implementation"]
23
[{"input": "2\r\n1 5 5\r\n2 6 4\r\n", "output": "LIVE\r\nLIVE\r\n"}, {"input": "3\r\n1 0 10\r\n2 0 10\r\n1 10 0\r\n", "output": "LIVE\r\nDEAD\r\n"}, {"input": "10\r\n1 3 7\r\n2 4 6\r\n1 2 8\r\n2 5 5\r\n2 10 0\r\n2 10 0\r\n1 8 2\r\n2 2 8\r\n2 10 0\r\n1 1 9\r\n", "output": "DEAD\r\nLIVE\r\n"}, {"input": "11\r\n1 8 2\r\n1 6 4\r\n1 9 1\r\n1 7 3\r\n2 0 10\r\n2 0 10\r\n1 8 2\r\n2 2 8\r\n2 6 4\r\n2 7 3\r\n2 9 1\r\n", "output": "LIVE\r\nDEAD\r\n"}, {"input": "12\r\n1 5 5\r\n1 0 10\r\n1 4 6\r\n1 2 8\r\n1 2 8\r\n1 5 5\r\n1 9 1\r\n2 9 1\r\n1 5 5\r\n1 1 9\r\n2 9 1\r\n2 7 3\r\n", "output": "DEAD\r\nLIVE\r\n"}, {"input": "13\r\n1 8 2\r\n1 4 6\r\n1 5 5\r\n1 5 5\r\n2 10 0\r\n2 9 1\r\n1 3 7\r\n2 6 4\r\n2 6 4\r\n2 5 5\r\n1 7 3\r\n2 3 7\r\n2 9 1\r\n", "output": "LIVE\r\nLIVE\r\n"}, {"input": "14\r\n1 7 3\r\n1 0 10\r\n1 7 3\r\n1 1 9\r\n2 2 8\r\n2 0 10\r\n1 1 9\r\n2 8 2\r\n2 6 4\r\n1 3 7\r\n1 3 7\r\n2 6 4\r\n2 1 9\r\n2 7 3\r\n", "output": "DEAD\r\nDEAD\r\n"}]
false
stdio
null
true
245/A
245
A
Python 3
TESTS
3
62
4,505,600
133423594
n=input() aWon=0 aLost=0 bWon=0 bLost=0 for i in range(0,int(n)): p=input().split() if int(p[0])==1: if int(p[1])>=int(p[2]): aWon+=1 else: aLost+=1 elif int(p[0])==2: if int(p[1])>=int(p[2]): bWon+=1 else: bLost+=1 if aWon>=aLost: print("LIVE") elif aWon<aLost: print("DEAD") if bWon>=bLost: print("LIVE") elif bWon<bLost: print("DEAD")
13
92
0
4504982
while(1): try: n=int(input()) a,b,c=[0 for j in range(n)],[0 for j in range(n)],[0 for j in range(n)] sum1,sum2=0,0 for i in range(0,n): a[i],b[i],c[i]=map(int,input().split()) if a[i]==1: sum1+=b[i] else: sum2+=b[i] count1,count2=a.count(1),a.count(2) t1,t2=10*count1,10*count2 if sum1/t1>=0.5: print("LIVE") else: print("DEAD") if sum2/t2>=0.5: print("LIVE") else: print("DEAD") except EOFError: break
CROC-MBTU 2012, Elimination Round (ACM-ICPC)
ICPC
2,012
2
256
System Administrator
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost. Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.
null
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
[{"input": "2\n1 5 5\n2 6 4", "output": "LIVE\nLIVE"}, {"input": "3\n1 0 10\n2 0 10\n1 10 0", "output": "LIVE\nDEAD"}]
800
["implementation"]
23
[{"input": "2\r\n1 5 5\r\n2 6 4\r\n", "output": "LIVE\r\nLIVE\r\n"}, {"input": "3\r\n1 0 10\r\n2 0 10\r\n1 10 0\r\n", "output": "LIVE\r\nDEAD\r\n"}, {"input": "10\r\n1 3 7\r\n2 4 6\r\n1 2 8\r\n2 5 5\r\n2 10 0\r\n2 10 0\r\n1 8 2\r\n2 2 8\r\n2 10 0\r\n1 1 9\r\n", "output": "DEAD\r\nLIVE\r\n"}, {"input": "11\r\n1 8 2\r\n1 6 4\r\n1 9 1\r\n1 7 3\r\n2 0 10\r\n2 0 10\r\n1 8 2\r\n2 2 8\r\n2 6 4\r\n2 7 3\r\n2 9 1\r\n", "output": "LIVE\r\nDEAD\r\n"}, {"input": "12\r\n1 5 5\r\n1 0 10\r\n1 4 6\r\n1 2 8\r\n1 2 8\r\n1 5 5\r\n1 9 1\r\n2 9 1\r\n1 5 5\r\n1 1 9\r\n2 9 1\r\n2 7 3\r\n", "output": "DEAD\r\nLIVE\r\n"}, {"input": "13\r\n1 8 2\r\n1 4 6\r\n1 5 5\r\n1 5 5\r\n2 10 0\r\n2 9 1\r\n1 3 7\r\n2 6 4\r\n2 6 4\r\n2 5 5\r\n1 7 3\r\n2 3 7\r\n2 9 1\r\n", "output": "LIVE\r\nLIVE\r\n"}, {"input": "14\r\n1 7 3\r\n1 0 10\r\n1 7 3\r\n1 1 9\r\n2 2 8\r\n2 0 10\r\n1 1 9\r\n2 8 2\r\n2 6 4\r\n1 3 7\r\n1 3 7\r\n2 6 4\r\n2 1 9\r\n2 7 3\r\n", "output": "DEAD\r\nDEAD\r\n"}]
false
stdio
null
true
675/C
675
C
Python 3
TESTS
4
31
0
135875024
# 1 2 3 -6 n=int(input()) l=[int(i) for i in input().split()] s=0 ans=0 new=[] new+=l for i in range(len(l)): if s!=0: ans+=1 s+=l[i] l=l[::-1] p=0 ans2=0 for i in range(len(l)): if p!=0: ans2+=1 p+=l[i] l=l[1:]+[l[0]] p=0 ans3=0 for i in range(len(l)): if p!=0: ans3+=1 p+=l[i] print(min(ans,ans2,ans3))
41
155
16,588,800
19938344
n = int(input()) a = list(map(int, input().split())) s = [a[0]] for i in range(1, n): s.append(s[i - 1] + a[i]) d = {} for x in s: if x not in d: d[x] = 1 else: d[x] += 1 print(n - max(d.values()))
Codeforces Round 353 (Div. 2)
CF
2,016
1
256
Money Transfers
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank. There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation. Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Print the minimum number of operations required to change balance in each bank to zero.
null
In the first sample, Vasya may transfer 5 from the first bank to the third. In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first. In the third sample, the following sequence provides the optimal answer: 1. transfer 1 from the first bank to the second bank; 2. transfer 3 from the second bank to the third; 3. transfer 6 from the third bank to the fourth.
[{"input": "3\n5 0 -5", "output": "1"}, {"input": "4\n-1 0 1 0", "output": "2"}, {"input": "4\n1 2 3 -6", "output": "3"}]
2,100
["constructive algorithms", "data structures", "greedy", "sortings"]
41
[{"input": "3\r\n5 0 -5\r\n", "output": "1\r\n"}, {"input": "4\r\n-1 0 1 0\r\n", "output": "2\r\n"}, {"input": "4\r\n1 2 3 -6\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "50\r\n108431864 128274949 -554057370 -384620666 -202862975 -803855410 -482167063 -55139054 -215901009 0 0 0 0 0 94325701 730397219 358214459 -673647271 -131397668 -377892440 0 0 0 0 0 -487994257 -360271553 639988328 489338210 -281060728 250208758 0 993242346 -213071841 -59752620 -864351041 -114363541 506279952 999648597 -173503559 -144629749 -559693009 0 -46793577 511999017 -343503822 -741715911 647437511 821346413 993112810\r\n", "output": "36\r\n"}, {"input": "6\r\n1 -1 1 -1 1 -1\r\n", "output": "3\r\n"}]
false
stdio
null
true
245/A
245
A
Python 3
TESTS
3
92
307,200
4993073
n = int(input()) r = [1,1] for i in range(n): t,x,y = map(int, input().split()) if x < y: r[t-1] = 0 else: r[t-1] = 1 for i in r: if i == 0: print('DEAD') else: print('LIVE')
13
92
0
4648150
n = int(input()) u, v = [0, 0], [0, 0] for i in range(n): t, x, y = map(int, input().split()) k = int(t == 1) u[k] += x v[k] += y print('LDIEVAED'[u[1] < v[1] :: 2]) print('LDIEVAED'[u[0] < v[0] :: 2])
CROC-MBTU 2012, Elimination Round (ACM-ICPC)
ICPC
2,012
2
256
System Administrator
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost. Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.
In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.
null
Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
[{"input": "2\n1 5 5\n2 6 4", "output": "LIVE\nLIVE"}, {"input": "3\n1 0 10\n2 0 10\n1 10 0", "output": "LIVE\nDEAD"}]
800
["implementation"]
23
[{"input": "2\r\n1 5 5\r\n2 6 4\r\n", "output": "LIVE\r\nLIVE\r\n"}, {"input": "3\r\n1 0 10\r\n2 0 10\r\n1 10 0\r\n", "output": "LIVE\r\nDEAD\r\n"}, {"input": "10\r\n1 3 7\r\n2 4 6\r\n1 2 8\r\n2 5 5\r\n2 10 0\r\n2 10 0\r\n1 8 2\r\n2 2 8\r\n2 10 0\r\n1 1 9\r\n", "output": "DEAD\r\nLIVE\r\n"}, {"input": "11\r\n1 8 2\r\n1 6 4\r\n1 9 1\r\n1 7 3\r\n2 0 10\r\n2 0 10\r\n1 8 2\r\n2 2 8\r\n2 6 4\r\n2 7 3\r\n2 9 1\r\n", "output": "LIVE\r\nDEAD\r\n"}, {"input": "12\r\n1 5 5\r\n1 0 10\r\n1 4 6\r\n1 2 8\r\n1 2 8\r\n1 5 5\r\n1 9 1\r\n2 9 1\r\n1 5 5\r\n1 1 9\r\n2 9 1\r\n2 7 3\r\n", "output": "DEAD\r\nLIVE\r\n"}, {"input": "13\r\n1 8 2\r\n1 4 6\r\n1 5 5\r\n1 5 5\r\n2 10 0\r\n2 9 1\r\n1 3 7\r\n2 6 4\r\n2 6 4\r\n2 5 5\r\n1 7 3\r\n2 3 7\r\n2 9 1\r\n", "output": "LIVE\r\nLIVE\r\n"}, {"input": "14\r\n1 7 3\r\n1 0 10\r\n1 7 3\r\n1 1 9\r\n2 2 8\r\n2 0 10\r\n1 1 9\r\n2 8 2\r\n2 6 4\r\n1 3 7\r\n1 3 7\r\n2 6 4\r\n2 1 9\r\n2 7 3\r\n", "output": "DEAD\r\nDEAD\r\n"}]
false
stdio
null
true
811/E
811
E
Python 3
TESTS
3
46
5,529,600
28023760
import sys data=sys.stdin.read().split("\n") del data[len(data)-1] n= int(data[0][0]) for ii in range(n+1, len(data)): cnt=[] suffix=0 left=int(data[ii].split(" ")[0])-1 right=int(data[ii].split(" ")[1])-1 array=[i.split(" ") for i in data[1:n+1]] for line in range(0,n): lines=array[line] for number in range(left, right+1):#x==line, y==number z=0 if (line-1>=0 and array[line-1][number].split("-")[0]==array[line][number]): z+=1 array[line][number]+="-"+array[line-1][number].split("-")[1] if (number-1>=left and array[line][number-1].split("-")[0]==array[line][number].split("-")[0]): z+=1 if (z==2 and array[line-1][number].split("-")[1] != array[line][number-1].split("-")[1]): del cnt[0] for x1 in range(left,right+1): for y1 in range(n): if array[y1][x1]==array[line][number]: array[y1][x1]=array[line][number-1] elif (z==2 and array[line-1][number].split("-")[1] == array[line][number-1].split("-")[1]): continue else: array[line][number]+="-"+array[line][number-1].split("-")[1] if z!=0: continue suffix+=1 array[line][number]+="-"+str(suffix) cnt.append("*") print (cnt.count("*"))
120
1,653
111,513,600
221893861
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v): return u * n + v def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): s, t = get_root(s), get_root(t) if s == t: return if rank[s] < rank[t]: s, t = t, s if rank[s] == rank[t]: rank[s] += 1 root[t] = s return def same(s, t): return True if get_root(s) == get_root(t) else False def get_segment(s, t): s, t = s + l1, t + l1 u, v = [], [] while s <= t: if s & 1: u.append(s) s += 1 s >>= 1 if not t & 1: v.append(t) t -= 1 t >>= 1 return u + v[::-1] n, m, q = map(int, input().split()) l1 = pow(2, (m + 1).bit_length()) l2 = 2 * l1 a = [0] * (n * l2) for i in range(n): a0 = list(map(int, input().split())) for j in range(m): a[f(j, i)] = a0[j] root = [i for i in range(n * l1)] rank = [1 for _ in range(n * l1)] l0, r0 = [0] * l2, [0] * l2 ll, rr = [0] * (n * l2), [0] * (n * l2) cnt = [0] * l2 for i in range(l1): c = n for j in range(n - 1): u, v = f(i, j), f(i, j + 1) if a[u] == a[v] and not same(u, v): unite(u, v) c -= 1 for j in range(n): u, v = f(i + l1, j), get_root(f(i, j)) ll[u], rr[u] = v, v l0[i + l1], r0[i + l1] = i, i cnt[i + l1] = c for i in range(l1 - 1, 0, -1): c = cnt[2 * i] + cnt[2 * i + 1] l, r = r0[2 * i], l0[2 * i + 1] for j in range(n): u, v = f(l, j), f(r, j) if a[u] == a[v] and not same(u, v): unite(u, v) c -= 1 l, r = l0[2 * i], r0[2 * i + 1] for j in range(n): u = f(i, j) ll[u], rr[u] = get_root(f(l, j)), get_root(f(r, j)) l0[i], r0[i] = l, r cnt[i] = c ans = [0] * q root = [i for i in range(n * l1)] rank = [1 for _ in range(n * l1)] for q0 in range(q): l, r = map(int, input().split()) x = get_segment(l - 1, r - 1) ans0 = cnt[x[0]] for i in range(len(x) - 1): l, r = x[i], x[i + 1] ans0 += cnt[r] for j in range(n): u, v = rr[f(l, j)], ll[f(r, j)] if a[u] == a[v] and not same(u, v): unite(u, v) ans0 -= 1 ans[q0] = ans0 for i in x: for j in range(n): u, v = ll[f(i, j)], rr[f(i, j)] root[u], root[v] = u, v rank[u], rank[v] = 1, 1 sys.stdout.write("\n".join(map(str, ans)))
Codeforces Round 416 (Div. 2)
CF
2,017
2
256
Vladik and Entertaining Flags
In his spare time Vladik estimates beauty of the flags. Every flag could be represented as the matrix n × m which consists of positive integers. Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1, l) and (n, r), where conditions 1 ≤ l ≤ r ≤ m are satisfied. Help Vladik to calculate the beauty for some segments of the given flag.
First line contains three space-separated integers n, m, q (1 ≤ n ≤ 10, 1 ≤ m, q ≤ 105) — dimensions of flag matrix and number of segments respectively. Each of next n lines contains m space-separated integers — description of flag matrix. All elements of flag matrix is positive integers not exceeding 106. Each of next q lines contains two space-separated integers l, r (1 ≤ l ≤ r ≤ m) — borders of segment which beauty Vladik wants to know.
For each segment print the result on the corresponding line.
null
Partitioning on components for every segment from first test case:
[{"input": "4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5", "output": "6\n7\n3\n4"}]
2,600
["data structures", "dsu", "graphs"]
120
[{"input": "4 5 4\r\n1 1 1 1 1\r\n1 2 2 3 3\r\n1 1 1 2 5\r\n4 4 5 5 5\r\n1 5\r\n2 5\r\n1 2\r\n4 5\r\n", "output": "6\r\n7\r\n3\r\n4\r\n"}, {"input": "5 2 9\r\n6 1\r\n6 6\r\n6 6\r\n6 6\r\n5 6\r\n1 2\r\n1 1\r\n1 2\r\n1 2\r\n1 2\r\n1 1\r\n1 1\r\n1 2\r\n1 1\r\n", "output": "3\r\n2\r\n3\r\n3\r\n3\r\n2\r\n2\r\n3\r\n2\r\n"}, {"input": "5 4 10\r\n5 5 5 5\r\n5 5 5 5\r\n5 5 5 5\r\n5 5 5 5\r\n5 5 5 5\r\n2 4\r\n2 2\r\n1 2\r\n1 4\r\n1 1\r\n1 3\r\n2 4\r\n2 3\r\n1 3\r\n3 3\r\n", "output": "1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n"}, {"input": "8 4 12\r\n7 20 20 29\r\n29 7 29 29\r\n29 20 20 29\r\n29 20 20 29\r\n29 8 29 29\r\n20 29 29 29\r\n29 29 32 29\r\n29 29 29 29\r\n2 4\r\n1 4\r\n2 3\r\n2 3\r\n1 4\r\n2 4\r\n1 1\r\n3 3\r\n3 3\r\n2 3\r\n3 4\r\n1 2\r\n", "output": "6\r\n9\r\n7\r\n7\r\n9\r\n6\r\n4\r\n6\r\n6\r\n7\r\n4\r\n8\r\n"}, {"input": "7 8 14\r\n8 8 36 8 36 36 5 36\r\n25 36 36 8 36 25 36 36\r\n36 36 36 8 36 36 36 36\r\n36 36 36 36 36 36 8 55\r\n8 8 36 36 36 36 36 36\r\n49 36 36 36 8 36 36 36\r\n36 36 5 44 5 36 36 48\r\n2 3\r\n1 4\r\n6 8\r\n1 2\r\n5 8\r\n2 8\r\n1 5\r\n5 8\r\n6 7\r\n1 3\r\n2 6\r\n1 6\r\n3 6\r\n2 4\r\n", "output": "4\r\n8\r\n7\r\n6\r\n8\r\n13\r\n10\r\n8\r\n5\r\n6\r\n9\r\n11\r\n7\r\n6\r\n"}, {"input": "1 6 9\r\n1 2 3 4 5 6\r\n2 6\r\n4 5\r\n3 4\r\n3 5\r\n6 6\r\n3 6\r\n4 6\r\n2 3\r\n1 6\r\n", "output": "5\r\n2\r\n2\r\n3\r\n1\r\n4\r\n3\r\n2\r\n6\r\n"}, {"input": "4 8 6\r\n23 23 23 23 23 13 23 23\r\n23 23 23 23 23 23 23 23\r\n23 23 23 23 13 23 23 23\r\n23 23 26 23 23 23 23 23\r\n5 8\r\n2 8\r\n6 8\r\n5 5\r\n7 7\r\n2 4\r\n", "output": "3\r\n4\r\n2\r\n3\r\n1\r\n2\r\n"}, {"input": "2 10 7\r\n8 13 13 8 8 8 8 8 8 8\r\n8 8 8 8 8 8 8 8 8 8\r\n4 9\r\n1 7\r\n6 6\r\n7 8\r\n4 4\r\n1 8\r\n2 10\r\n", "output": "1\r\n2\r\n1\r\n1\r\n1\r\n2\r\n2\r\n"}, {"input": "5 12 6\r\n25 24 24 53 53 53 53 53 5 20 53 53\r\n24 53 24 53 53 3 5 53 53 53 53 53\r\n24 53 53 5 53 5 53 53 53 17 53 60\r\n49 53 53 24 53 53 53 53 53 53 53 35\r\n53 53 5 53 53 53 53 53 53 53 53 53\r\n6 8\r\n8 10\r\n4 11\r\n4 8\r\n6 12\r\n8 9\r\n", "output": "4\r\n4\r\n9\r\n6\r\n9\r\n2\r\n"}, {"input": "4 14 4\r\n8 8 8 8 46 46 48 8 8 8 8 13 24 40\r\n8 46 46 46 8 8 46 8 8 8 8 24 24 24\r\n8 46 46 8 8 8 23 23 8 8 8 8 8 8\r\n8 8 8 8 8 8 8 8 8 8 8 8 8 55\r\n10 10\r\n10 14\r\n3 5\r\n10 12\r\n", "output": "1\r\n5\r\n4\r\n3\r\n"}, {"input": "1 16 10\r\n2 2 2 2 6 2 8 2 2 12 10 9 9 2 16 2\r\n9 9\r\n5 5\r\n6 9\r\n6 8\r\n7 11\r\n6 16\r\n4 7\r\n6 15\r\n7 9\r\n11 11\r\n", "output": "1\r\n1\r\n3\r\n3\r\n4\r\n9\r\n4\r\n8\r\n2\r\n1\r\n"}, {"input": "7 12 11\r\n73 14 4 73 42 42 73 73 73 67 73 24\r\n73 73 73 73 73 73 72 73 73 73 73 11\r\n73 73 4 72 73 73 73 73 73 73 67 72\r\n73 74 73 72 73 73 73 73 73 73 73 73\r\n4 73 73 73 73 73 73 73 73 57 73 73\r\n72 73 73 4 73 73 73 73 33 73 73 73\r\n73 73 73 15 42 72 67 67 33 67 73 73\r\n9 12\r\n6 6\r\n10 11\r\n8 10\r\n1 9\r\n6 9\r\n3 5\r\n2 4\r\n2 4\r\n7 11\r\n1 12\r\n", "output": "9\r\n3\r\n5\r\n7\r\n16\r\n6\r\n8\r\n9\r\n9\r\n8\r\n23\r\n"}, {"input": "5 16 10\r\n32 4 4 4 4 4 4 52 4 4 4 4 29 30 4 4\r\n4 4 67 52 4 4 4 67 4 4 4 4 4 4 4 4\r\n4 52 52 52 4 4 4 67 67 52 32 4 4 4 4 52\r\n4 52 4 4 4 4 4 4 67 52 49 4 4 4 4 62\r\n49 4 4 4 4 72 55 4 4 52 49 52 4 62 4 62\r\n5 16\r\n9 13\r\n2 12\r\n3 13\r\n8 14\r\n7 7\r\n3 9\r\n1 4\r\n1 5\r\n7 7\r\n", "output": "15\r\n8\r\n12\r\n13\r\n11\r\n2\r\n8\r\n6\r\n5\r\n2\r\n"}]
false
stdio
null
true
246/B
246
B
Python 3
TESTS
4
124
0
106645643
n = int(input()) a,*arr = list(map(int,input().split())) s = 0 for i in range(n-1): s += -arr[i] if (a+s)%2: print(n-1) else: print(n)
30
92
3,174,400
185712401
n = int(input()) lst = list(map(int, input().split())) if sum(lst)%n==0: print(n) else: print(n-1)
Codeforces Round 151 (Div. 2)
CF
2,012
2
256
Increase and Decrease
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array ai, aj (i ≠ j); - he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.
Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.
null
null
[{"input": "2\n2 1", "output": "1"}, {"input": "3\n1 4 1", "output": "3"}]
1,300
["greedy", "math"]
30
[{"input": "2\r\n2 1\r\n", "output": "1\r\n"}, {"input": "3\r\n1 4 1\r\n", "output": "3\r\n"}, {"input": "4\r\n2 -7 -2 -6\r\n", "output": "3\r\n"}, {"input": "4\r\n2 0 -2 -1\r\n", "output": "3\r\n"}, {"input": "6\r\n-1 1 0 0 -1 -1\r\n", "output": "5\r\n"}, {"input": "5\r\n0 0 0 0 0\r\n", "output": "5\r\n"}]
false
stdio
null
true
846/F
846
F
PyPy 3-64
TESTS
4
202
21,504,000
210559118
import math import random import time from decimal import * def binary_search(vector,valoarea): left=0 right=len(vector)-1 while left<=right: centru=(left+right)//2 # print(left,right,centru,vector[centru]) if vector[centru]<valoarea: left=centru+1 else: right=centru-1 # print(left,right,centru,vector[centru]) return left from collections import defaultdict def main(): answ=[] pp=10**9 rest=10**9+7 #teste=int(input()) for gg in range(1): n=int(input()) #n,m=list(map(int,input().split())) vector=list(map(int,input().split())) #n=5 # vector=[] #for i in range(5): # vector.append(random.randint(1,5)) # print(vector) # verificare=0 # for i in range(n): # for j in range(n): # setul=set(vector[i:j+1]) # verificare+=len(setul) #print("i=",i,"j=",j,setul,len(setul),verificare) # print(verificare) last=[-1]*1000001 suma=1 sume=[1]*(n) last[vector[0]]=0 for i in range(1,n): if vector[i]==vector[i-1]: sume[i]=1+sume[i-1] else: sume[i]=sume[i-1]+(i-last[vector[i]]-1)+1 last[vector[i]]=i suma+=sume[i] # print("s=",suma) patrat=n*n answ=(((suma-n)*2)+n)/patrat # verif=(2*125781193-5000)/(5000*5000) # print(verif) print(answ) # print(sume) # print("?",suma-verificare) main()
31
998
74,444,800
75166697
n = int(input()) arr = [0] arr = arr + list(map(int, input().split(' '))) def getCounts(arr): last = {} ans = 0.0 prev = 0.0 res = 0.0 for i in range(1, len(arr)): if arr[i] not in last: ans = prev + i else: ans = prev + i - last[arr[i]] prev = ans res += ans last[arr[i]] = i return res ans = (2 * getCounts(arr) - n)/(n*n) print("%.6f" % ans)
Educational Codeforces Round 28
ICPC
2,017
2
256
Random Query
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed).
The first line contains one integer number n (1 ≤ n ≤ 106). The second line contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 106) — elements of the array.
Print one number — the expected number of unique elements in chosen segment. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 — formally, the answer is correct if $${ \operatorname* { m i n } } ( | x - y |, { \frac { | x - y | } { x } } ) \leq 1 0 ^ { - 4 }$$, where x is jury's answer, and y is your answer.
null
null
[{"input": "2\n1 2", "output": "1.500000"}, {"input": "2\n2 2", "output": "1.000000"}]
1,800
["data structures", "math", "probabilities", "two pointers"]
31
[{"input": "2\r\n1 2\r\n", "output": "1.500000\r\n"}, {"input": "2\r\n2 2\r\n", "output": "1.000000\r\n"}, {"input": "10\r\n9 6 8 5 5 2 8 9 2 2\r\n", "output": "3.100000\r\n"}, {"input": "20\r\n49 33 9 8 50 21 12 44 23 39 24 10 17 4 17 40 24 19 27 21\r\n", "output": "7.010000\r\n"}, {"input": "1\r\n1000000\r\n", "output": "1.000000\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] correct_output_path = sys.argv[2] submission_output_path = sys.argv[3] # Read correct output with open(correct_output_path, 'r') as f: correct_line = f.readline().strip() x = float(correct_line) # Read submission output with open(submission_output_path, 'r') as f: submission_line = f.readline().strip() try: y = float(submission_line) except: # Invalid output format, score 0 print(0) return # Compute errors absolute_error = abs(x - y) if absolute_error <= 1e-4: print(1) return # Compute relative error relative_error = absolute_error / x if relative_error <= 1e-4: print(1) else: print(0) if __name__ == "__main__": main()
true
247/B
250
B
Python 3
TESTS
6
248
0
62996758
# from dust i have come, dust i will be def solve(ip): ch = ip.split(':') n = len(ch) if ch[n - 1] == '' and n - 2 >= 0 and ch[n - 2] == '': ch.pop(n - 1) extra = 8 - len(ch) ans = [] for i in range(len(ch)): if ch[i] != '': while len(ch[i]) < 4: ch[i] = '0' + ch[i] ans.append(ch[i]) else: ans.append('0000') while extra > 0: ans.append('0000') extra -= 1 ret = '' for i in range(len(ans)): ret += ans[i] if i != len(ans) - 1: ret += ':' return ret n = int(input()) for i in range(n): s = input() print(solve(s))
40
92
0
156767698
n = int(input()) res = "" for i in range(n): short = input() blocks = short.split(':') if '' in blocks: countOfNull = 9 - len(blocks) # short[short.index('::')+1] short = short.replace("::", ":0000"*countOfNull + ":") blocks = short.split(':') short = "" for block in blocks: if len(block) < 4: block = "0"*(4-len(block))+block short += block + ":" short = short[:-1] res += short + "\n" res = res[:-1] print(res)
CROC-MBTU 2012, Final Round
CF
2,012
2
256
Restoring IPv6
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full. Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000" → "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address. Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::"; - "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0"; - "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0"; - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000"; - "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon. The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short. You've got several short records of IPv6 addresses. Restore their full record.
The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
null
null
[{"input": "6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"}]
1,500
[]
40
[{"input": "6\r\na56f:d3:0:0124:01:f19a:1000:00\r\na56f:00d3:0000:0124:0001::\r\na56f::0124:0001:0000:1234:0ff0\r\na56f:0000::0000:0001:0000:1234:0ff0\r\n::\r\n0ea::4d:f4:6:0\r\n", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\r\na56f:00d3:0000:0124:0001:0000:0000:0000\r\na56f:0000:0000:0124:0001:0000:1234:0ff0\r\na56f:0000:0000:0000:0001:0000:1234:0ff0\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n00ea:0000:0000:0000:004d:00f4:0006:0000\r\n"}, {"input": "10\r\n1::7\r\n0:0::1\r\n::1ed\r\n::30:44\r\n::eaf:ff:000b\r\n56fe::\r\ndf0:3df::\r\nd03:ab:0::\r\n85::0485:0\r\n::\r\n", "output": "0001:0000:0000:0000:0000:0000:0000:0007\n0000:0000:0000:0000:0000:0000:0000:0001\n0000:0000:0000:0000:0000:0000:0000:01ed\n0000:0000:0000:0000:0000:0000:0030:0044\n0000:0000:0000:0000:0000:0eaf:00ff:000b\n56fe:0000:0000:0000:0000:0000:0000:0000\n0df0:03df:0000:0000:0000:0000:0000:0000\n0d03:00ab:0000:0000:0000:0000:0000:0000\n0085:0000:0000:0000:0000:0000:0485:0000\n0000:0000:0000:0000:0000:0000:0000:0000\n"}, {"input": "6\r\n0:00:000:0000::\r\n1:01:001:0001::\r\nf:0f:00f:000f::\r\n1:10:100:1000::\r\nf:f0:f00:f000::\r\nf:ff:fff:ffff::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0001:0001:0001:0001:0000:0000:0000:0000\r\n000f:000f:000f:000f:0000:0000:0000:0000\r\n0001:0010:0100:1000:0000:0000:0000:0000\r\n000f:00f0:0f00:f000:0000:0000:0000:0000\r\n000f:00ff:0fff:ffff:0000:0000:0000:0000\r\n"}, {"input": "3\r\n::\r\n::\r\n::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n"}, {"input": "4\r\n1:2:3:4:5:6:7:8\r\n0:0:0:0:0:0:0:0\r\nf:0f:00f:000f:ff:0ff:00ff:fff\r\n0fff:0ff0:0f0f:f0f:0f0:f0f0:f00f:ff0f\r\n", "output": "0001:0002:0003:0004:0005:0006:0007:0008\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n000f:000f:000f:000f:00ff:00ff:00ff:0fff\r\n0fff:0ff0:0f0f:0f0f:00f0:f0f0:f00f:ff0f\r\n"}]
false
stdio
null
true
246/B
246
B
Python 3
TESTS
5
154
0
39017955
n = int(input()) arr = list(map(int,input().split())) if (n&1 == 1) and sum(arr) == ((n*(n+1)) >> 1): print(n) else: print(n-1)
30
92
3,174,400
189678648
n=int(input()) ; arr=list(map(int,input().split())) ; summ=sum(arr) ; avg=summ/n ; print(n if int(avg)==avg else n-1)
Codeforces Round 151 (Div. 2)
CF
2,012
2
256
Increase and Decrease
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array ai, aj (i ≠ j); - he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.
Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.
null
null
[{"input": "2\n2 1", "output": "1"}, {"input": "3\n1 4 1", "output": "3"}]
1,300
["greedy", "math"]
30
[{"input": "2\r\n2 1\r\n", "output": "1\r\n"}, {"input": "3\r\n1 4 1\r\n", "output": "3\r\n"}, {"input": "4\r\n2 -7 -2 -6\r\n", "output": "3\r\n"}, {"input": "4\r\n2 0 -2 -1\r\n", "output": "3\r\n"}, {"input": "6\r\n-1 1 0 0 -1 -1\r\n", "output": "5\r\n"}, {"input": "5\r\n0 0 0 0 0\r\n", "output": "5\r\n"}]
false
stdio
null
true
247/B
250
B
Python 3
TESTS
1
30
0
156838375
def ipv6(inputs): result = list() data = list(map(str, inputs.split())) size = int(data.pop(0)) for i in range(size): current = data.pop(0).split(':') result.append("") difference = 8-len(current) for value in current: if value == '': result[i]+="0000:" while difference > 0: result[i]+="0000:" difference-=1 continue for _ in range(4-len(value)): result[i]+="0" result[i]+=value + ":" result[i] = str(result[i][:len(result[i])-1]) return "\n".join(result) size = input() inputs = size for _ in range(int(size)): inputs += "\n"+input() print(ipv6(inputs))
40
92
0
156840243
def ipv6(inputs): result = list() data = list(map(str, inputs.split())) size = int(data.pop(0)) for _ in range(size): current = data.pop(0).split(':') result.append("") current_length = len(current) #difference = 8-current_length while len(current) > 0: value = current.pop(0) if value == '': result[-1]+="0000:" if len(current)>0: while current[0] == '': current.pop(0) current_length -= 1 if len(current)==0: break while 8-current_length > 0: result[-1]+="0000:" current_length+=1 continue for _ in range(4-len(value)): result[-1]+="0" result[-1]+=value + ":" result[-1] = str(result[-1][:len(result[-1])-1]) return "\n".join(result) size = input() inputs = size for _ in range(int(size)): inputs += "\n"+input() print(ipv6(inputs))
CROC-MBTU 2012, Final Round
CF
2,012
2
256
Restoring IPv6
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full. Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000" → "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address. Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::"; - "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0"; - "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0"; - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000"; - "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon. The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short. You've got several short records of IPv6 addresses. Restore their full record.
The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
null
null
[{"input": "6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"}]
1,500
[]
40
[{"input": "6\r\na56f:d3:0:0124:01:f19a:1000:00\r\na56f:00d3:0000:0124:0001::\r\na56f::0124:0001:0000:1234:0ff0\r\na56f:0000::0000:0001:0000:1234:0ff0\r\n::\r\n0ea::4d:f4:6:0\r\n", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\r\na56f:00d3:0000:0124:0001:0000:0000:0000\r\na56f:0000:0000:0124:0001:0000:1234:0ff0\r\na56f:0000:0000:0000:0001:0000:1234:0ff0\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n00ea:0000:0000:0000:004d:00f4:0006:0000\r\n"}, {"input": "10\r\n1::7\r\n0:0::1\r\n::1ed\r\n::30:44\r\n::eaf:ff:000b\r\n56fe::\r\ndf0:3df::\r\nd03:ab:0::\r\n85::0485:0\r\n::\r\n", "output": "0001:0000:0000:0000:0000:0000:0000:0007\n0000:0000:0000:0000:0000:0000:0000:0001\n0000:0000:0000:0000:0000:0000:0000:01ed\n0000:0000:0000:0000:0000:0000:0030:0044\n0000:0000:0000:0000:0000:0eaf:00ff:000b\n56fe:0000:0000:0000:0000:0000:0000:0000\n0df0:03df:0000:0000:0000:0000:0000:0000\n0d03:00ab:0000:0000:0000:0000:0000:0000\n0085:0000:0000:0000:0000:0000:0485:0000\n0000:0000:0000:0000:0000:0000:0000:0000\n"}, {"input": "6\r\n0:00:000:0000::\r\n1:01:001:0001::\r\nf:0f:00f:000f::\r\n1:10:100:1000::\r\nf:f0:f00:f000::\r\nf:ff:fff:ffff::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0001:0001:0001:0001:0000:0000:0000:0000\r\n000f:000f:000f:000f:0000:0000:0000:0000\r\n0001:0010:0100:1000:0000:0000:0000:0000\r\n000f:00f0:0f00:f000:0000:0000:0000:0000\r\n000f:00ff:0fff:ffff:0000:0000:0000:0000\r\n"}, {"input": "3\r\n::\r\n::\r\n::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n"}, {"input": "4\r\n1:2:3:4:5:6:7:8\r\n0:0:0:0:0:0:0:0\r\nf:0f:00f:000f:ff:0ff:00ff:fff\r\n0fff:0ff0:0f0f:f0f:0f0:f0f0:f00f:ff0f\r\n", "output": "0001:0002:0003:0004:0005:0006:0007:0008\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n000f:000f:000f:000f:00ff:00ff:00ff:0fff\r\n0fff:0ff0:0f0f:0f0f:00f0:f0f0:f00f:ff0f\r\n"}]
false
stdio
null
true
246/B
246
B
Python 3
TESTS
4
62
0
223411385
n=int(input()) a=list(map(int,input().split())) j=sum(a)//n man=[] mos=[] m=0 for i in range(0,len(a)) : if j-a[i]<0 : man.append(abs(j-a[i])) else : mos.append(j-a[i]) m+=j-a[i] o=0 man.sort() for i in range(0,len(man)) : if m-man[i]>=0 : o+=1 m-=man[i] else : break print(o+len(mos))
30
92
3,379,200
144936948
n=int(input()) ls=list(map(int,input().split())) print(n if sum(ls)%n==0 else n-1)
Codeforces Round 151 (Div. 2)
CF
2,012
2
256
Increase and Decrease
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array ai, aj (i ≠ j); - he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.
Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.
null
null
[{"input": "2\n2 1", "output": "1"}, {"input": "3\n1 4 1", "output": "3"}]
1,300
["greedy", "math"]
30
[{"input": "2\r\n2 1\r\n", "output": "1\r\n"}, {"input": "3\r\n1 4 1\r\n", "output": "3\r\n"}, {"input": "4\r\n2 -7 -2 -6\r\n", "output": "3\r\n"}, {"input": "4\r\n2 0 -2 -1\r\n", "output": "3\r\n"}, {"input": "6\r\n-1 1 0 0 -1 -1\r\n", "output": "5\r\n"}, {"input": "5\r\n0 0 0 0 0\r\n", "output": "5\r\n"}]
false
stdio
null
true
247/B
250
B
Python 3
TESTS
1
62
0
144806838
for _ in range(int(input())): st = input() arr = st.split(':') for i in range(len(arr)): while 0 != len(arr[i]) != 4: arr[i] = "0" + arr[i] while '' in arr: ind = arr.index('') arr[ind] = "0000" for __ in range(8 - len(arr)): arr.insert(ind, "0000") # print(arr) print(':'.join(arr))
40
92
0
166403517
# coding=utf8 cnt = input() for k in range(int(cnt)): ip = input() if ip == "": print("0000:0000:0000:0000:0000:0000:0000:0000") continue ip = ip.split(":") ret = "" # 扩:: if ip[0] == "": ip = ["0000"] * (8 - len(ip) + 2) + ip[2:] elif ip[-1] == "": ip = ip[:-2] + ["0000"] * (8 - len(ip) + 2) for i in range(len(ip)): if ip[i] == "": ip = ip[:i] + ["0000"] * (8 - len(ip) + 1) + ip[i + 1:] for i in range(len(ip)): if ip[i] != "": ip[i] = "0" * (4 - len(ip[i])) + ip[i] print(":".join(ip))
CROC-MBTU 2012, Final Round
CF
2,012
2
256
Restoring IPv6
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full. Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000" → "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address. Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::"; - "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0"; - "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0"; - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000"; - "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon. The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short. You've got several short records of IPv6 addresses. Restore their full record.
The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
null
null
[{"input": "6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"}]
1,500
[]
40
[{"input": "6\r\na56f:d3:0:0124:01:f19a:1000:00\r\na56f:00d3:0000:0124:0001::\r\na56f::0124:0001:0000:1234:0ff0\r\na56f:0000::0000:0001:0000:1234:0ff0\r\n::\r\n0ea::4d:f4:6:0\r\n", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\r\na56f:00d3:0000:0124:0001:0000:0000:0000\r\na56f:0000:0000:0124:0001:0000:1234:0ff0\r\na56f:0000:0000:0000:0001:0000:1234:0ff0\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n00ea:0000:0000:0000:004d:00f4:0006:0000\r\n"}, {"input": "10\r\n1::7\r\n0:0::1\r\n::1ed\r\n::30:44\r\n::eaf:ff:000b\r\n56fe::\r\ndf0:3df::\r\nd03:ab:0::\r\n85::0485:0\r\n::\r\n", "output": "0001:0000:0000:0000:0000:0000:0000:0007\n0000:0000:0000:0000:0000:0000:0000:0001\n0000:0000:0000:0000:0000:0000:0000:01ed\n0000:0000:0000:0000:0000:0000:0030:0044\n0000:0000:0000:0000:0000:0eaf:00ff:000b\n56fe:0000:0000:0000:0000:0000:0000:0000\n0df0:03df:0000:0000:0000:0000:0000:0000\n0d03:00ab:0000:0000:0000:0000:0000:0000\n0085:0000:0000:0000:0000:0000:0485:0000\n0000:0000:0000:0000:0000:0000:0000:0000\n"}, {"input": "6\r\n0:00:000:0000::\r\n1:01:001:0001::\r\nf:0f:00f:000f::\r\n1:10:100:1000::\r\nf:f0:f00:f000::\r\nf:ff:fff:ffff::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0001:0001:0001:0001:0000:0000:0000:0000\r\n000f:000f:000f:000f:0000:0000:0000:0000\r\n0001:0010:0100:1000:0000:0000:0000:0000\r\n000f:00f0:0f00:f000:0000:0000:0000:0000\r\n000f:00ff:0fff:ffff:0000:0000:0000:0000\r\n"}, {"input": "3\r\n::\r\n::\r\n::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n"}, {"input": "4\r\n1:2:3:4:5:6:7:8\r\n0:0:0:0:0:0:0:0\r\nf:0f:00f:000f:ff:0ff:00ff:fff\r\n0fff:0ff0:0f0f:f0f:0f0:f0f0:f00f:ff0f\r\n", "output": "0001:0002:0003:0004:0005:0006:0007:0008\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n000f:000f:000f:000f:00ff:00ff:00ff:0fff\r\n0fff:0ff0:0f0f:0f0f:00f0:f0f0:f00f:ff0f\r\n"}]
false
stdio
null
true
246/B
246
B
Python 3
TESTS
4
62
0
176971636
input() l = list(map(int, input().split())) l.sort() while True: l = sorted(l) if abs(l[-1] - l[0]) > 1: l[0] += 1 l[-1] -= 1 else: break l1 = list(set(l)) q = 0 for i in l1: c = l.count(i) if c > q: q = c print(q)
30
92
3,379,200
146607760
# Author: Riddhish V. Lichade # username: root_rvl # codeforces 246B from collections import Counter from sys import stdin, stdout from heapq import nlargest, nsmallest def outnl(x): stdout.write(str(x) + '\n') def outsl(x): stdout.write(str(x) + ' ') def instr(): return stdin.readline().strip() def inint(): return int(stdin.readline()) def inspsint(): return map(int, stdin.readline().strip().split()) def inlist(): return list(map(int, stdin.readline().strip().split())) for _ in range(1): n=inint() l=inlist() s=sum(l) if(s % n == 0): print(n) else: print(n-1)
Codeforces Round 151 (Div. 2)
CF
2,012
2
256
Increase and Decrease
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array ai, aj (i ≠ j); - he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.
Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.
null
null
[{"input": "2\n2 1", "output": "1"}, {"input": "3\n1 4 1", "output": "3"}]
1,300
["greedy", "math"]
30
[{"input": "2\r\n2 1\r\n", "output": "1\r\n"}, {"input": "3\r\n1 4 1\r\n", "output": "3\r\n"}, {"input": "4\r\n2 -7 -2 -6\r\n", "output": "3\r\n"}, {"input": "4\r\n2 0 -2 -1\r\n", "output": "3\r\n"}, {"input": "6\r\n-1 1 0 0 -1 -1\r\n", "output": "5\r\n"}, {"input": "5\r\n0 0 0 0 0\r\n", "output": "5\r\n"}]
false
stdio
null
true
925/A
925
A
PyPy 3-64
TESTS
7
452
13,824,000
182208608
import sys input = sys.stdin.readline from bisect import bisect def f(x, y, z, q): global ew if len(x) == 0: return a1 = bisect(x, y) if a1 == 0: if x[0] < z: ew = min(ew, q+z-y) else: ew = min(ew, (x[0]-z)*2+z-y+q) elif a1 == len(x): ew = min(ew, (y-x[a1-1])*2+z-y+q) else: if x[a1] < z: ew = min(ew, q + z - y) else: ew = min(ew, (x[a1]-z)*2+z-y+q, (y-x[a1-1])*2+z-y+q) n, m, cl, ce, v = map(int, input().split()) l = list(map(int, input().split())) e = list(map(int, input().split())) for _ in range(int(input())): a, b, c, d = map(int, input().split()) if b > d: a, b, c, d = c, d, a, b c1 = abs(a-c) c2 = (c1+v-1)//v ew = 1 << 30 f(l, b, d, c1) f(e, b, d, c2) print(ew)
27
1,450
22,323,200
37718038
# python3 import sys from bisect import bisect def readline(): return tuple(map(int, input().split())) def readlines(): return (tuple(map(int, line.split())) for line in sys.stdin.readlines()) def bisect_bounds(arr, val): idx = bisect(arr, val) if idx: yield idx - 1 if idx < len(arr): yield idx class Minimizator: def __init__(self, value=float('inf')): self.value = value def eat(self, value): self.value = min(self.value, value) def main(): n, m, cl, ce, v = readline() l = readline() e = readline() assert len(l) == cl assert len(e) == ce q, = readline() answers = list() for (x1, y1, x2, y2) in readlines(): if x1 == x2: answers.append(abs(y1 - y2)) else: ans = Minimizator(n + 2*m) for idx in bisect_bounds(l, y1): ladder = l[idx] ans.eat(abs(x1 - x2) + abs(ladder - y1) + abs(ladder - y2)) for idx in bisect_bounds(e, y1): elevator = e[idx] ans.eat((abs(x1 - x2) - 1) // v + 1 + abs(elevator - y1) + abs(elevator - y2)) answers.append(ans.value) print("\n".join(map(str, answers))) main()
VK Cup 2018 - Round 3
CF
2,018
2
256
Stairs and Elevators
In the year of $$$30XX$$$ participants of some world programming championship live in a single large hotel. The hotel has $$$n$$$ floors. Each floor has $$$m$$$ sections with a single corridor connecting all of them. The sections are enumerated from $$$1$$$ to $$$m$$$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $$$n$$$ and width $$$m$$$. We can denote sections with pairs of integers $$$(i, j)$$$, where $$$i$$$ is the floor, and $$$j$$$ is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $$$(1, x)$$$, $$$(2, x)$$$, $$$\ldots$$$, $$$(n, x)$$$ for some $$$x$$$ between $$$1$$$ and $$$m$$$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $$$v$$$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process $$$q$$$ queries. Each query is a question "what is the minimum time needed to go from a room in section $$$(x_1, y_1)$$$ to a room in section $$$(x_2, y_2)$$$?"
The first line contains five integers $$$n, m, c_l, c_e, v$$$ ($$$2 \leq n, m \leq 10^8$$$, $$$0 \leq c_l, c_e \leq 10^5$$$, $$$1 \leq c_l + c_e \leq m - 1$$$, $$$1 \leq v \leq n - 1$$$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains $$$c_l$$$ integers $$$l_1, \ldots, l_{c_l}$$$ in increasing order ($$$1 \leq l_i \leq m$$$), denoting the positions of the stairs. If $$$c_l = 0$$$, the second line is empty. The third line contains $$$c_e$$$ integers $$$e_1, \ldots, e_{c_e}$$$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $$$l_i$$$ and $$$e_i$$$ are distinct. The fourth line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — the number of queries. The next $$$q$$$ lines describe queries. Each of these lines contains four integers $$$x_1, y_1, x_2, y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1 \leq y_1, y_2 \leq m$$$) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. $$$y_1$$$ and $$$y_2$$$ are not among $$$l_i$$$ and $$$e_i$$$.
Print $$$q$$$ integers, one per line — the answers for the queries.
null
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.
[{"input": "5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3", "output": "7\n5\n4"}]
1,600
["binary search"]
27
[{"input": "5 6 1 1 3\r\n2\r\n5\r\n3\r\n1 1 5 6\r\n1 3 5 4\r\n3 3 5 3\r\n", "output": "7\r\n5\r\n4\r\n"}, {"input": "2 2 0 1 1\r\n\r\n1\r\n1\r\n1 2 2 2\r\n", "output": "3\r\n"}, {"input": "4 4 1 0 1\r\n4\r\n\r\n5\r\n1 1 2 2\r\n1 3 2 2\r\n3 3 4 3\r\n3 2 2 2\r\n1 2 2 3\r\n", "output": "6\r\n4\r\n3\r\n5\r\n4\r\n"}, {"input": "10 10 1 8 4\r\n10\r\n2 3 4 5 6 7 8 9\r\n10\r\n1 1 3 1\r\n2 1 7 1\r\n1 1 9 1\r\n7 1 4 1\r\n10 1 7 1\r\n2 1 7 1\r\n3 1 2 1\r\n5 1 2 1\r\n10 1 5 1\r\n6 1 9 1\r\n", "output": "3\r\n4\r\n4\r\n3\r\n3\r\n4\r\n3\r\n3\r\n4\r\n3\r\n"}, {"input": "2 5 1 0 1\r\n2\r\n\r\n1\r\n1 4 1 5\r\n", "output": "1\r\n"}, {"input": "2 10 1 1 1\r\n1\r\n10\r\n1\r\n1 5 1 8\r\n", "output": "3\r\n"}, {"input": "4 4 1 0 1\r\n1\r\n\r\n1\r\n1 2 1 4\r\n", "output": "2\r\n"}, {"input": "2 4 1 1 1\r\n1\r\n2\r\n1\r\n2 3 2 4\r\n", "output": "1\r\n"}, {"input": "1000 1000 1 1 10\r\n1\r\n2\r\n1\r\n1 900 1 1000\r\n", "output": "100\r\n"}, {"input": "2 4 1 1 1\r\n1\r\n4\r\n1\r\n1 2 1 3\r\n", "output": "1\r\n"}, {"input": "5 5 1 1 1\r\n3\r\n2\r\n1\r\n1 5 1 1\r\n", "output": "4\r\n"}]
false
stdio
null
true
430/A
430
A
Python 3
TESTS
3
61
0
7699791
#input n,m=map(int,input().split()) xlist=[int(x) for x in input().split()] #variables #main for i in range(n): if xlist[i]%2==0: xlist[i]='0' else: xlist[i]='1' print(''.join([xlist[i]+' ' for i in range(n)]))
12
46
0
9383025
n, m = map(int, input().split()) p = sorted((x[1], x[0]) for x in enumerate(map(int, input().split()))) p = sorted((x[1], str(i % 2)) for i, x in enumerate(p)) print(' '.join(x[1] for x in p))
Codeforces Round 245 (Div. 2)
CF
2,014
1
256
Points and Segments (easy)
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw n distinct points and m segments on the OX axis. He can draw each point with either red or blue. The drawing is good if and only if the following requirement is met: for each segment [li, ri] consider all the red points belong to it (ri points), and all the blue points belong to it (bi points); each segment i should satisfy the inequality |ri - bi| ≤ 1. Iahub thinks that point x belongs to segment [l, r], if inequality l ≤ x ≤ r holds. Iahub gives to you all coordinates of points and segments. Please, help him to find any good drawing.
The first line of input contains two integers: n (1 ≤ n ≤ 100) and m (1 ≤ m ≤ 100). The next line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi ≤ 100) — the coordinates of the points. The following m lines contain the descriptions of the m segments. Each line contains two integers li and ri (0 ≤ li ≤ ri ≤ 100) — the borders of the i-th segment. It's guaranteed that all the points are distinct.
If there is no good drawing for a given test, output a single integer -1. Otherwise output n integers, each integer must be 0 or 1. The i-th number denotes the color of the i-th point (0 is red, and 1 is blue). If there are multiple good drawings you can output any of them.
null
null
[{"input": "3 3\n3 7 14\n1 5\n6 10\n11 15", "output": "0 0 0"}, {"input": "3 4\n1 2 3\n1 2\n2 3\n5 6\n2 2", "output": "1 0 1"}]
1,600
["constructive algorithms", "sortings"]
12
[{"input": "3 3\r\n3 7 14\r\n1 5\r\n6 10\r\n11 15\r\n", "output": "0 0 0"}, {"input": "3 4\r\n1 2 3\r\n1 2\r\n2 3\r\n5 6\r\n2 2\r\n", "output": "1 0 1 "}, {"input": "10 10\r\n3 4 2 6 1 9 0 5 8 7\r\n5 7\r\n2 6\r\n0 1\r\n5 6\r\n3 4\r\n2 5\r\n2 10\r\n4 6\r\n3 6\r\n3 7\r\n", "output": "0 1 1 1 0 0 1 0 1 0 "}, {"input": "3 3\r\n50 51 52\r\n1 5\r\n6 10\r\n11 15\r\n", "output": "1 0 1 "}, {"input": "3 1\r\n1 2 3\r\n2 3\r\n", "output": "1 0 1 "}]
false
stdio
import sys def read_ints(file): return list(map(int, file.read().split())) def main(input_path, output_path, submission_path): with open(input_path) as f: n, m = map(int, f.readline().split()) points = list(map(int, f.readline().split())) segments = [tuple(map(int, f.readline().split())) for _ in range(m)] with open(output_path) as f: ref_output = f.read().strip().split() with open(submission_path) as f: sub_output = f.read().strip().split() # Check if submission is -1 if len(sub_output) == 1 and sub_output[0] == '-1': if len(ref_output) == 1 and ref_output[0] == '-1': print(100) return else: print(0) return # Check if reference is -1 (submission isn't) if len(ref_output) == 1 and ref_output[0] == '-1': print(0) return # Check submission has n elements if len(sub_output) != n: print(0) return # Check each element is 0 or 1 try: colors = list(map(int, sub_output)) except: print(0) return for c in colors: if c not in (0, 1): print(0) return # Create point to color mapping color_map = {p: c for p, c in zip(points, colors)} # Check each segment for l, r in segments: red = 0 blue = 0 for p in points: if l <= p <= r: if color_map[p] == 0: red += 1 else: blue += 1 if abs(red - blue) > 1: print(0) return # All checks passed print(100) 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
247/B
250
B
Python 3
TESTS
1
92
0
227614298
# LUOGU_RID: 128695624 for i in range(int(input())): a=input().replace('::',':#:').split(':') while len(a)<8:a.insert(a.index('#'),'0000') for i in range(8): if'#'==a[i]:a[i]='0000' else:a[i]='0'*(4-len(a[i]))+a[i] print(str(a)[2:-2].replace("', '",':'))
40
92
0
166411665
def _ip_ (ipv6): l = 7 - (len (ipv6) - len (ipv6.replace (":", "", ))) ipv6 = ipv6.replace ("::", ":" * (l + 2)) list = ipv6.split (":", ) ip = ["", "", "", "", "", "", "", ""] for i in range(0, 8): t = list [i] while len (t) != 4: t = "0" + t ip [i] = t t = "" for i in range(0, 8): t+= ip [i] + ":" print (t [:len (t) - 1:]) l = int (input ()) for i in range (0, l): _ip_ (input ())
CROC-MBTU 2012, Final Round
CF
2,012
2
256
Restoring IPv6
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full. Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000" → "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address. Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::"; - "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0"; - "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0"; - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000"; - "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon. The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short. You've got several short records of IPv6 addresses. Restore their full record.
The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
null
null
[{"input": "6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"}]
1,500
[]
40
[{"input": "6\r\na56f:d3:0:0124:01:f19a:1000:00\r\na56f:00d3:0000:0124:0001::\r\na56f::0124:0001:0000:1234:0ff0\r\na56f:0000::0000:0001:0000:1234:0ff0\r\n::\r\n0ea::4d:f4:6:0\r\n", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\r\na56f:00d3:0000:0124:0001:0000:0000:0000\r\na56f:0000:0000:0124:0001:0000:1234:0ff0\r\na56f:0000:0000:0000:0001:0000:1234:0ff0\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n00ea:0000:0000:0000:004d:00f4:0006:0000\r\n"}, {"input": "10\r\n1::7\r\n0:0::1\r\n::1ed\r\n::30:44\r\n::eaf:ff:000b\r\n56fe::\r\ndf0:3df::\r\nd03:ab:0::\r\n85::0485:0\r\n::\r\n", "output": "0001:0000:0000:0000:0000:0000:0000:0007\n0000:0000:0000:0000:0000:0000:0000:0001\n0000:0000:0000:0000:0000:0000:0000:01ed\n0000:0000:0000:0000:0000:0000:0030:0044\n0000:0000:0000:0000:0000:0eaf:00ff:000b\n56fe:0000:0000:0000:0000:0000:0000:0000\n0df0:03df:0000:0000:0000:0000:0000:0000\n0d03:00ab:0000:0000:0000:0000:0000:0000\n0085:0000:0000:0000:0000:0000:0485:0000\n0000:0000:0000:0000:0000:0000:0000:0000\n"}, {"input": "6\r\n0:00:000:0000::\r\n1:01:001:0001::\r\nf:0f:00f:000f::\r\n1:10:100:1000::\r\nf:f0:f00:f000::\r\nf:ff:fff:ffff::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0001:0001:0001:0001:0000:0000:0000:0000\r\n000f:000f:000f:000f:0000:0000:0000:0000\r\n0001:0010:0100:1000:0000:0000:0000:0000\r\n000f:00f0:0f00:f000:0000:0000:0000:0000\r\n000f:00ff:0fff:ffff:0000:0000:0000:0000\r\n"}, {"input": "3\r\n::\r\n::\r\n::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n"}, {"input": "4\r\n1:2:3:4:5:6:7:8\r\n0:0:0:0:0:0:0:0\r\nf:0f:00f:000f:ff:0ff:00ff:fff\r\n0fff:0ff0:0f0f:f0f:0f0:f0f0:f00f:ff0f\r\n", "output": "0001:0002:0003:0004:0005:0006:0007:0008\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n000f:000f:000f:000f:00ff:00ff:00ff:0fff\r\n0fff:0ff0:0f0f:0f0f:00f0:f0f0:f00f:ff0f\r\n"}]
false
stdio
null
true
665/B
665
B
PyPy 3
TESTS
1
93
512,000
119286782
import sys sys.stderr = sys.stdout import heapq from collections import deque def shop(n, m, k, P, A): t = 0 for Ai in A: d = deque(reversed(Ai), m+1) o = {a:i for i, a in enumerate(Ai)} l = [None] * m j = 0 for i in range(k): p = P[i] if p in o: t += (i+1) l[j] = o[p] j += 1 else: d.append(p) P[i] = d.popleft() t += msort(l) return t def msort(L): return msort2(L, 0, len(L)) def msort2(L, i0, i1): if i1 == i0 or i1 == i0 + 1: return 0 i2 = (i0 + i1) // 2 L[i0:i1], k = merge(L[i0:i2], L[i2:i1]) return k def merge(L, R): l = len(L) r = len(R) i = 0 j = 0 k = 0 M = [] while i < l and j < r: if L[i] <= R[j]: M.append(L[i]) i += 1 else: M.append(R[j]) j += 1 k += len(L) while i < l: M.append(L[i]) i += 1 while j < r: M.append(R[j]) j += 1 return M, k def main(): n, m, k = readinti() P = readintl() A = readintll(n) print(shop(n, m, k, P, A)) ########## def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintt(): return tuple(readinti()) def readintl(): return list(readinti()) def readinttl(k): return [readintt() for _ in range(k)] def readintll(k): return [readintl() for _ in range(k)] def log(*args, **kwargs): print(*args, **kwargs, file=sys.__stderr__) if __name__ == '__main__': main()
10
46
0
179558449
f = lambda: map(int, input().split()) n, m, k = f() a = list(f()) s = m * n for i in range(n): for b in f(): i = a.index(b) s += i a = [a.pop(i)] + a print(s)
Educational Codeforces Round 12
ICPC
2,016
1
256
Shopping
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order. Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1) + pos(ai2) + ... + pos(aim) for the i-th customer. When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating. Your task is to calculate the total time it takes for Ayush to process all the orders. You can assume that the market has endless stock.
The first line contains three integers n, m and k (1 ≤ n, k ≤ 100, 1 ≤ m ≤ k) — the number of users, the number of items each user wants to buy and the total number of items at the market. The next line contains k distinct integers pl (1 ≤ pl ≤ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k. Each of the next n lines contains m distinct integers aij (1 ≤ aij ≤ k) — the order of the i-th person.
Print the only integer t — the total time needed for Ayush to process all the orders.
null
Customer 1 wants the items 1 and 5. pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5]. pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2]. Time taken for the first customer is 3 + 5 = 8. Customer 2 wants the items 3 and 1. pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2]. pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2]. Time taken for the second customer is 3 + 3 = 6. Total time is 8 + 6 = 14. Formally pos(x) is the index of x in the current row.
[{"input": "2 2 5\n3 4 1 2 5\n1 5\n3 1", "output": "14"}]
1,400
["brute force"]
10
[{"input": "2 2 5\r\n3 4 1 2 5\r\n1 5\r\n3 1\r\n", "output": "14\r\n"}, {"input": "4 4 4\r\n1 2 3 4\r\n3 4 2 1\r\n4 3 2 1\r\n4 1 2 3\r\n4 1 2 3\r\n", "output": "59\r\n"}, {"input": "1 1 1\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "10 1 100\r\n1 55 67 75 40 86 24 84 82 26 81 23 70 79 51 54 21 78 31 98 68 93 66 88 99 65 20 52 35 85 16 12 94 100 59 56 18 33 47 46 71 8 38 57 2 92 3 95 6 4 87 22 48 80 15 29 11 45 72 76 44 60 91 90 39 74 41 36 13 27 53 83 32 5 30 63 89 64 49 17 9 97 69 14 50 77 37 96 10 42 28 34 61 19 73 7 62 43 58 25\r\n33\r\n69\r\n51\r\n7\r\n68\r\n70\r\n1\r\n35\r\n24\r\n7\r\n", "output": "335\r\n"}, {"input": "100 1 1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n", "output": "100\r\n"}, {"input": "3 2 3\r\n3 1 2\r\n1 2\r\n2 1\r\n2 3\r\n", "output": "13\r\n"}, {"input": "10 10 10\r\n3 4 1 2 8 9 5 10 6 7\r\n9 10 7 8 6 1 2 3 4 5\r\n2 5 3 6 1 4 9 7 8 10\r\n2 9 1 8 4 7 5 10 6 3\r\n10 9 7 1 3 6 2 8 5 4\r\n2 5 1 3 7 10 4 9 8 6\r\n6 1 8 7 9 2 3 5 4 10\r\n1 3 2 8 6 9 4 10 5 7\r\n5 2 4 8 6 1 10 9 3 7\r\n5 1 7 10 4 6 2 8 9 3\r\n2 1 3 9 7 10 6 4 8 5\r\n", "output": "771\r\n"}]
false
stdio
null
true
355/B
355
B
PyPy 3
TESTS
3
92
0
109971543
if __name__ == '__main__': c1,c2,c3,c4 = map(int, input().split()) n,m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) s = min(c1,c2,c3,c4) l = [] if s == c4: print(c4) elif s == c3: if 2*c3 > c4 and c4 <= min((c1*min(a)+c2),(c1*min(b)+c2),c1*sum(a),c2*(sum(b))): print(c4) else: print(2*c3) else: print(min((c1*min(a)+c2+c3),(c1*min(b)+c2+c3),(c1*sum(a)+c3),(c2*(sum(b))+c3)))
27
46
307,200
4775478
c1,c2,c3,c4=map(int,input().split()) n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) s=[] s0=0 for i in range(n): s.append(min(a[i]*c1,c2)) s0+=s[i] s1=[] s10=0 for i in range(m): s1.append(min(b[i]*c1,c2)) s10+=s1[i] print(min((min(s0,c3)+min(s10,c3)),c4))
Codeforces Round 206 (Div. 2)
CF
2,013
1
256
Vasya and Public Transport
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m. Public transport is not free. There are 4 types of tickets: 1. A ticket for one ride on some bus or trolley. It costs c1 burles; 2. A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; 3. A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; 4. A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
The first line contains four integers c1, c2, c3, c4 (1 ≤ c1, c2, c3, c4 ≤ 1000) — the costs of the tickets. The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of buses and trolleys Vasya is going to use. The third line contains n integers ai (0 ≤ ai ≤ 1000) — the number of times Vasya is going to use the bus number i. The fourth line contains m integers bi (0 ≤ bi ≤ 1000) — the number of times Vasya is going to use the trolley number i.
Print a single number — the minimum sum of burles Vasya will have to spend on the tickets.
null
In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2·1) + 3 + 7 = 12 burles. In the second sample the profitable strategy is to buy one ticket of the fourth type. In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
[{"input": "1 3 7 19\n2 3\n2 5\n4 4 4", "output": "12"}, {"input": "4 3 2 1\n1 3\n798\n1 2 3", "output": "1"}, {"input": "100 100 8 100\n3 5\n7 94 12\n100 1 47 0 42", "output": "16"}]
1,100
["greedy", "implementation"]
27
[{"input": "1 3 7 19\r\n2 3\r\n2 5\r\n4 4 4\r\n", "output": "12\r\n"}, {"input": "4 3 2 1\r\n1 3\r\n798\r\n1 2 3\r\n", "output": "1\r\n"}, {"input": "100 100 8 100\r\n3 5\r\n7 94 12\r\n100 1 47 0 42\r\n", "output": "16\r\n"}, {"input": "3 103 945 1000\r\n7 9\r\n34 35 34 35 34 35 34\r\n0 0 0 0 0 0 0 0 0\r\n", "output": "717\r\n"}, {"input": "7 11 597 948\r\n4 1\r\n5 1 0 11\r\n7\r\n", "output": "40\r\n"}, {"input": "7 32 109 645\r\n1 3\r\n0\r\n0 0 0\r\n", "output": "0\r\n"}, {"input": "680 871 347 800\r\n10 100\r\n872 156 571 136 703 201 832 213 15 333\r\n465 435 870 95 660 237 694 594 423 405 27 866 325 490 255 989 128 345 278 125 708 210 771 848 961 448 871 190 745 343 532 174 103 999 874 221 252 500 886 129 185 208 137 425 800 34 696 39 198 981 91 50 545 885 194 583 475 415 162 712 116 911 313 488 646 189 429 756 728 30 985 114 823 111 106 447 296 430 307 388 345 458 84 156 169 859 274 934 634 62 12 839 323 831 24 907 703 754 251 938\r\n", "output": "694\r\n"}, {"input": "671 644 748 783\r\n100 10\r\n520 363 816 957 635 753 314 210 763 819 27 970 520 164 195 230 708 587 568 707 343 30 217 227 755 277 773 497 900 589 826 666 115 784 494 467 217 892 658 388 764 812 248 447 876 581 94 915 675 967 508 754 768 79 261 934 603 712 20 199 997 501 465 91 897 257 820 645 217 105 564 8 668 171 168 18 565 840 418 42 808 918 409 617 132 268 13 161 194 628 213 199 545 448 113 410 794 261 211 539\r\n147 3 178 680 701 193 697 666 846 389\r\n", "output": "783\r\n"}, {"input": "2 7 291 972\r\n63 92\r\n7 0 0 6 0 13 0 20 2 8 0 17 7 0 0 0 0 2 2 0 0 8 20 0 0 0 3 0 0 0 4 20 0 0 0 12 0 8 17 9 0 0 0 0 4 0 0 0 17 11 3 0 2 15 0 18 11 19 14 0 0 20 13\r\n0 0 0 3 7 0 0 0 0 8 13 6 15 0 7 0 0 20 0 0 12 0 12 0 15 0 0 1 11 14 0 11 12 0 0 0 0 0 16 16 0 17 20 0 11 0 0 20 14 0 16 0 3 6 12 0 0 0 0 0 15 3 0 9 17 12 20 17 0 0 0 0 15 9 0 14 10 10 1 20 16 17 20 6 6 0 0 16 4 6 0 7\r\n", "output": "494\r\n"}, {"input": "4 43 490 945\r\n63 92\r\n0 0 0 0 0 0 6 5 18 0 6 4 0 17 0 19 0 19 7 16 0 0 0 9 10 13 7 0 10 16 0 0 0 0 0 14 0 14 9 15 0 0 2 0 0 0 0 5 0 0 0 11 11 0 0 0 0 0 10 12 3 0 0\r\n0 12 0 18 7 7 0 0 9 0 0 13 17 0 18 12 4 0 0 14 18 20 0 0 12 9 17 1 19 0 11 0 5 0 0 14 0 0 16 0 19 15 9 14 7 10 0 19 19 0 0 1 0 0 0 6 0 0 0 6 0 20 1 9 0 0 10 17 5 2 5 4 16 6 0 11 0 8 13 4 0 2 0 0 13 10 0 13 0 0 8 4\r\n", "output": "945\r\n"}, {"input": "2 50 258 922\r\n42 17\r\n0 2 0 1 0 1 0 11 18 9 0 0 0 0 10 15 17 4 20 0 5 0 0 13 13 0 0 2 0 7 0 20 4 0 19 3 7 0 0 0 0 0\r\n8 4 19 0 0 19 14 17 6 0 18 0 0 0 0 9 0\r\n", "output": "486\r\n"}, {"input": "1 1 3 4\r\n2 3\r\n1 1\r\n1 1 1\r\n", "output": "4\r\n"}, {"input": "4 4 4 1\r\n1 1\r\n0\r\n0\r\n", "output": "0\r\n"}, {"input": "100 100 1 100\r\n10 10\r\n100 100 100 100 100 100 100 100 100 100\r\n100 100 100 100 100 100 100 100 100 100\r\n", "output": "2\r\n"}]
false
stdio
null
true
665/B
665
B
PyPy 3
TESTS
1
93
102,400
119285806
import sys sys.stderr = sys.stdout from collections import deque def shop(n, m, k, P, A): t = 0 for Ai in A: d = deque(reversed(Ai), m+1) s = set(Ai) o = {} j = 0 for i in range(k): p = P[i] if p in s: t += (i+1) o[p] = j j += 1 else: d.append(p) P[i] = d.popleft() for i in range(m): j = o[Ai[i]] t += j - i if i < j else 0 return t def main(): n, m, k = readinti() P = readintl() A = readintll(n) print(shop(n, m, k, P, A)) ########## def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintt(): return tuple(readinti()) def readintl(): return list(readinti()) def readinttl(k): return [readintt() for _ in range(k)] def readintll(k): return [readintl() for _ in range(k)] def log(*args, **kwargs): print(*args, **kwargs, file=sys.__stderr__) if __name__ == '__main__': main()
10
46
0
184897242
n,m,k=map(int,input().split()) a=list(map(int,input().split())) b=[] cnt=0 for i in range(n): b=list(map(int,input().split())) for j in range(len(b)): c=a.index(b[j])+1 cnt+=c a.insert(0,b[j]) del a[c] print(cnt)
Educational Codeforces Round 12
ICPC
2,016
1
256
Shopping
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order. Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1) + pos(ai2) + ... + pos(aim) for the i-th customer. When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating. Your task is to calculate the total time it takes for Ayush to process all the orders. You can assume that the market has endless stock.
The first line contains three integers n, m and k (1 ≤ n, k ≤ 100, 1 ≤ m ≤ k) — the number of users, the number of items each user wants to buy and the total number of items at the market. The next line contains k distinct integers pl (1 ≤ pl ≤ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k. Each of the next n lines contains m distinct integers aij (1 ≤ aij ≤ k) — the order of the i-th person.
Print the only integer t — the total time needed for Ayush to process all the orders.
null
Customer 1 wants the items 1 and 5. pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5]. pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2]. Time taken for the first customer is 3 + 5 = 8. Customer 2 wants the items 3 and 1. pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2]. pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2]. Time taken for the second customer is 3 + 3 = 6. Total time is 8 + 6 = 14. Formally pos(x) is the index of x in the current row.
[{"input": "2 2 5\n3 4 1 2 5\n1 5\n3 1", "output": "14"}]
1,400
["brute force"]
10
[{"input": "2 2 5\r\n3 4 1 2 5\r\n1 5\r\n3 1\r\n", "output": "14\r\n"}, {"input": "4 4 4\r\n1 2 3 4\r\n3 4 2 1\r\n4 3 2 1\r\n4 1 2 3\r\n4 1 2 3\r\n", "output": "59\r\n"}, {"input": "1 1 1\r\n1\r\n1\r\n", "output": "1\r\n"}, {"input": "10 1 100\r\n1 55 67 75 40 86 24 84 82 26 81 23 70 79 51 54 21 78 31 98 68 93 66 88 99 65 20 52 35 85 16 12 94 100 59 56 18 33 47 46 71 8 38 57 2 92 3 95 6 4 87 22 48 80 15 29 11 45 72 76 44 60 91 90 39 74 41 36 13 27 53 83 32 5 30 63 89 64 49 17 9 97 69 14 50 77 37 96 10 42 28 34 61 19 73 7 62 43 58 25\r\n33\r\n69\r\n51\r\n7\r\n68\r\n70\r\n1\r\n35\r\n24\r\n7\r\n", "output": "335\r\n"}, {"input": "100 1 1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n", "output": "100\r\n"}, {"input": "3 2 3\r\n3 1 2\r\n1 2\r\n2 1\r\n2 3\r\n", "output": "13\r\n"}, {"input": "10 10 10\r\n3 4 1 2 8 9 5 10 6 7\r\n9 10 7 8 6 1 2 3 4 5\r\n2 5 3 6 1 4 9 7 8 10\r\n2 9 1 8 4 7 5 10 6 3\r\n10 9 7 1 3 6 2 8 5 4\r\n2 5 1 3 7 10 4 9 8 6\r\n6 1 8 7 9 2 3 5 4 10\r\n1 3 2 8 6 9 4 10 5 7\r\n5 2 4 8 6 1 10 9 3 7\r\n5 1 7 10 4 6 2 8 9 3\r\n2 1 3 9 7 10 6 4 8 5\r\n", "output": "771\r\n"}]
false
stdio
null
true
358/C
358
C
Python 3
PRETESTS
2
46
307,200
4882199
n=int(input()) cur=[] while n>0: cx=int(input()) if(cx!=0): cur.append(-cx) else: fx=[i for i in cur] fx.sort() fx=fx[:3] used='' ux=0 for i in cur: if i == fx[0]: print('pushStack') fx[0]=0 used+=' popStack' ux+=1 elif i == fx[1]: print('pushQueue') fx[1]=0 used+=' popQueue' ux+=1 elif i == fx[2]: print('pushFront') fx[2]=0 used+=' popFront' ux+=1 else: print('pushBack') print(str(ux)+used) cur=[] n-=1
26
311
28,569,600
135330920
# Author Name: Ajay Meena # Codeforce : https://codeforces.com/profile/majay1638 import sys import math import bisect import heapq from bisect import bisect_right from sys import stdin, stdout # -------------- INPUT FUNCTIONS ------------------ def get_ints_in_variables(): return map( int, sys.stdin.readline().strip().split()) def get_int(): return int(sys.stdin.readline()) def get_ints_in_list(): return list( map(int, sys.stdin.readline().strip().split())) def get_list_of_list(n): return [list( map(int, sys.stdin.readline().strip().split())) for _ in range(n)] def get_string(): return sys.stdin.readline().strip() # -------- SOME CUSTOMIZED FUNCTIONS----------- def myceil(x, y): return (x + y - 1) // y # -------------- SOLUTION FUNCTION ------------------ def Solution(): # Write Your Code Here n = get_int() arr = [get_int() for _ in range(n)] u = [0 for _ in range(n)] hp = [] # print(arr,"arr") for i, x in enumerate(arr): if x: heapq.heappush(hp, (-x, i)) else: for t in [1, 2, 3]: if len(hp) > 0: x, j = heapq.heappop(hp) u[j] = t u[i] += 1 hp = [] push = ['pushBack', 'pushStack', 'pushQueue', 'pushFront'] pop = ['popStack', 'popQueue', 'popFront'] for i, x in enumerate(arr): if x: print(push[u[i]]) else: if u[i]: print(str(u[i])+" "+" ".join(pop[:u[i]])) else: print("0") def main(): # Take input Here and Call solution function Solution() # calling main Function if __name__ == '__main__': main()
Codeforces Round 208 (Div. 2)
CF
2,013
2
256
Dima and Containers
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck. Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: 1. Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. 2. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation. As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!
The first line contains integer n (1 ≤ n ≤ 105) — the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer: 1. Integer a (1 ≤ a ≤ 105) means that Inna gives Dima a command to add number a into one of containers. 2. Integer 0 shows that Inna asks Dima to make at most three extractions from different containers.
Each command of the input must correspond to one line of the output — Dima's action. For the command of the first type (adding) print one word that corresponds to Dima's choice: - pushStack — add to the end of the stack; - pushQueue — add to the end of the queue; - pushFront — add to the beginning of the deck; - pushBack — add to the end of the deck. For a command of the second type first print an integer k (0 ≤ k ≤ 3), that shows the number of extract operations, then print k words separated by space. The words can be: - popStack — extract from the end of the stack; - popQueue — extract from the beginning of the line; - popFront — extract from the beginning from the deck; - popBack — extract from the end of the deck. The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers. The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.
null
null
[{"input": "10\n0\n1\n0\n1\n2\n0\n1\n2\n3\n0", "output": "0\npushStack\n1 popStack\npushStack\npushQueue\n2 popStack popQueue\npushStack\npushQueue\npushFront\n3 popStack popQueue popFront"}, {"input": "4\n1\n2\n3\n0", "output": "pushStack\npushQueue\npushFront\n3 popStack popQueue popFront"}]
2,000
["constructive algorithms", "greedy", "implementation"]
26
[{"input": "10\r\n0\r\n1\r\n0\r\n1\r\n2\r\n0\r\n1\r\n2\r\n3\r\n0\r\n", "output": "0\r\npushStack\r\n1 popStack\r\npushStack\r\npushQueue\r\n2 popStack popQueue\r\npushStack\r\npushQueue\r\npushFront\r\n3 popStack popQueue popFront\r\n"}, {"input": "4\r\n1\r\n2\r\n3\r\n0\r\n", "output": "pushStack\r\npushQueue\r\npushFront\r\n3 popStack popQueue popFront\r\n"}, {"input": "2\r\n0\r\n1\r\n", "output": "0\r\npushQueue\r\n"}, {"input": "5\r\n1\r\n1\r\n1\r\n2\r\n1\r\n", "output": "pushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\n"}, {"input": "5\r\n3\r\n2\r\n3\r\n1\r\n0\r\n", "output": "pushStack\r\npushQueue\r\npushFront\r\npushBack\r\n3 popStack popQueue popFront\r\n"}, {"input": "49\r\n8735\r\n95244\r\n50563\r\n33648\r\n10711\r\n30217\r\n49166\r\n28240\r\n0\r\n97232\r\n12428\r\n16180\r\n58610\r\n61112\r\n74423\r\n56323\r\n43327\r\n0\r\n12549\r\n48493\r\n43086\r\n69266\r\n27033\r\n37338\r\n43900\r\n5570\r\n25293\r\n44517\r\n7183\r\n41969\r\n31944\r\n32247\r\n96959\r\n44890\r\n98237\r\n52601\r\n29081\r\n93641\r\n14980\r\n29539\r\n84672\r\n57310\r\n91014\r\n31721\r\n6944\r\n67672\r\n22040\r\n86269\r\n86709\r\n", "output": "pushBack\npushStack\npushQueue\npushBack\npushBack\npushBack\npushFront\npushBack\n3 popStack popQueue popFront\npushStack\npushBack\npushBack\npushBack\npushFront\npushQueue\npushBack\npushBack\n3 popStack popQueue popFront\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushStack\npushBack\npushBack\npushFront\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushQueue\npushBack\npushBack\npushBack\npushBack\n"}, {"input": "55\r\n73792\r\n39309\r\n73808\r\n47389\r\n34803\r\n87947\r\n32460\r\n14649\r\n70151\r\n35816\r\n8272\r\n78886\r\n71345\r\n61907\r\n16977\r\n85362\r\n0\r\n43792\r\n8118\r\n83254\r\n89459\r\n32230\r\n87068\r\n82617\r\n94847\r\n83528\r\n37629\r\n31438\r\n97413\r\n62260\r\n13651\r\n47564\r\n43543\r\n61292\r\n51025\r\n64106\r\n0\r\n19282\r\n35422\r\n19657\r\n95170\r\n10266\r\n43771\r\n3190\r\n93962\r\n11747\r\n43021\r\n91531\r\n88370\r\n1760\r\n10950\r\n77059\r\n61741\r\n52965\r\n10445\r\n", "output": "pushBack\npushBack\npushBack\npushBack\npushBack\npushStack\npushBack\npushBack\npushBack\npushBack\npushBack\npushFront\npushBack\npushBack\npushBack\npushQueue\n3 popStack popQueue popFront\npushBack\npushBack\npushBack\npushFront\npushBack\npushBack\npushBack\npushQueue\npushBack\npushBack\npushBack\npushStack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\npushBack\n3 popStack popQueue popFront\npushBack\npushBack\npushBack\npushBack\npushFront\npushBack\npushQueue\npushBack\npushBack\npushBack\npushBack\npushBack\npushStack\npushBack\npushBack\npushBack\npushBack\npushBack\n"}, {"input": "10\r\n1\r\n2\r\n3\r\n5\r\n4\r\n9\r\n8\r\n6\r\n7\r\n0\r\n", "output": "pushBack\r\npushBack\r\npushBack\r\npushBack\r\npushBack\r\npushStack\r\npushQueue\r\npushBack\r\npushFront\r\n3 popStack popQueue popFront\r\n"}, {"input": "10\r\n1\r\n3\r\n4\r\n2\r\n6\r\n8\r\n5\r\n7\r\n10\r\n9\r\n", "output": "pushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\npushQueue\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}]
false
stdio
import sys from collections import deque def main(input_path, output_path, submission_path): with open(input_path) as f: input_lines = f.read().splitlines() n = int(input_lines[0]) input_commands = input_lines[1:n+1] with open(submission_path) as f: submission_lines = [line.strip() for line in f] if len(submission_lines) != len(input_commands): print(0) return stack = [] queue = [] deck = deque() sub_idx = 0 for cmd in input_commands: if cmd == '0': if sub_idx >= len(submission_lines): print(0) return line = submission_lines[sub_idx] sub_idx += 1 parts = line.split() if not parts: print(0) return try: k = int(parts[0]) except: print(0) return if k < 0 or k > 3 or len(parts) != k + 1: print(0) return ops = parts[1:] # Compute max possible sum using copies stack_copy = list(stack) queue_copy = list(queue) deck_copy = deque(deck) contributions = [] if stack_copy: contributions.append(stack_copy[-1]) if queue_copy: contributions.append(queue_copy[0]) if deck_copy: deck_val = max(deck_copy[0], deck_copy[-1]) if deck_copy else 0 contributions.append(deck_val) contributions.sort(reverse=True) max_sum = sum(contributions[:3]) # Validate submission's ops temp_stack = list(stack) temp_queue = list(queue) temp_deck = deque(deck) sum_sub = 0 used = set() valid = True for op in ops: container = None if op == 'popStack': if not temp_stack: valid = False break sum_sub += temp_stack.pop() container = 'stack' elif op == 'popQueue': if not temp_queue: valid = False break sum_sub += temp_queue.pop(0) container = 'queue' elif op == 'popFront': if not temp_deck: valid = False break sum_sub += temp_deck.popleft() container = 'deck' elif op == 'popBack': if not temp_deck: valid = False break sum_sub += temp_deck.pop() container = 'deck' else: valid = False break if container in used: valid = False break used.add(container) if not valid or sum_sub != max_sum: print(0) return # Clear containers stack.clear() queue.clear() deck.clear() else: a = int(cmd) if sub_idx >= len(submission_lines): print(0) return line = submission_lines[sub_idx] sub_idx += 1 if line == 'pushStack': stack.append(a) elif line == 'pushQueue': queue.append(a) elif line == 'pushFront': deck.appendleft(a) elif line == 'pushBack': deck.append(a) else: print(0) return print(1) if __name__ == '__main__': main(sys.argv[1], sys.argv[2], sys.argv[3])
true
247/B
250
B
Python 3
TESTS
1
92
0
22707021
for i in range(int(input())): ipv6 = input().split(':') ipv6 = [((4 - len(i))*'0' + i) if i != '' else '' for i in ipv6] if ipv6[-1] == '': ipv6[-1] = '0000' if ipv6[0] == '': ipv6[0] = '0000' if '' in ipv6: string = '0000:'*(8 - len(ipv6) + 1) ipv6[ipv6.index('')] = string[:-1] print(':'.join(ipv6))
40
92
0
175711939
import sys input = sys.stdin.readline for _ in range(int(input())): s = input()[:-1].split(':') c = 0 for i in s: if i != '': c += 1 d = [] x = 0 for i in s: if i != '': d.append(i.rjust(4, '0')) else: if x == 0: x = 1 d.extend(['0000' for _ in range(8-c)]) print(':'.join(d))
CROC-MBTU 2012, Final Round
CF
2,012
2
256
Restoring IPv6
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full. Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000" → "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address. Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::"; - "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0"; - "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0"; - "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000"; - "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon. The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short. You've got several short records of IPv6 addresses. Restore their full record.
The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.
For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.
null
null
[{"input": "6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"}]
1,500
[]
40
[{"input": "6\r\na56f:d3:0:0124:01:f19a:1000:00\r\na56f:00d3:0000:0124:0001::\r\na56f::0124:0001:0000:1234:0ff0\r\na56f:0000::0000:0001:0000:1234:0ff0\r\n::\r\n0ea::4d:f4:6:0\r\n", "output": "a56f:00d3:0000:0124:0001:f19a:1000:0000\r\na56f:00d3:0000:0124:0001:0000:0000:0000\r\na56f:0000:0000:0124:0001:0000:1234:0ff0\r\na56f:0000:0000:0000:0001:0000:1234:0ff0\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n00ea:0000:0000:0000:004d:00f4:0006:0000\r\n"}, {"input": "10\r\n1::7\r\n0:0::1\r\n::1ed\r\n::30:44\r\n::eaf:ff:000b\r\n56fe::\r\ndf0:3df::\r\nd03:ab:0::\r\n85::0485:0\r\n::\r\n", "output": "0001:0000:0000:0000:0000:0000:0000:0007\n0000:0000:0000:0000:0000:0000:0000:0001\n0000:0000:0000:0000:0000:0000:0000:01ed\n0000:0000:0000:0000:0000:0000:0030:0044\n0000:0000:0000:0000:0000:0eaf:00ff:000b\n56fe:0000:0000:0000:0000:0000:0000:0000\n0df0:03df:0000:0000:0000:0000:0000:0000\n0d03:00ab:0000:0000:0000:0000:0000:0000\n0085:0000:0000:0000:0000:0000:0485:0000\n0000:0000:0000:0000:0000:0000:0000:0000\n"}, {"input": "6\r\n0:00:000:0000::\r\n1:01:001:0001::\r\nf:0f:00f:000f::\r\n1:10:100:1000::\r\nf:f0:f00:f000::\r\nf:ff:fff:ffff::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0001:0001:0001:0001:0000:0000:0000:0000\r\n000f:000f:000f:000f:0000:0000:0000:0000\r\n0001:0010:0100:1000:0000:0000:0000:0000\r\n000f:00f0:0f00:f000:0000:0000:0000:0000\r\n000f:00ff:0fff:ffff:0000:0000:0000:0000\r\n"}, {"input": "3\r\n::\r\n::\r\n::\r\n", "output": "0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n"}, {"input": "4\r\n1:2:3:4:5:6:7:8\r\n0:0:0:0:0:0:0:0\r\nf:0f:00f:000f:ff:0ff:00ff:fff\r\n0fff:0ff0:0f0f:f0f:0f0:f0f0:f00f:ff0f\r\n", "output": "0001:0002:0003:0004:0005:0006:0007:0008\r\n0000:0000:0000:0000:0000:0000:0000:0000\r\n000f:000f:000f:000f:00ff:00ff:00ff:0fff\r\n0fff:0ff0:0f0f:0f0f:00f0:f0f0:f00f:ff0f\r\n"}]
false
stdio
null
true
82/B
82
B
PyPy 3
TESTS
32
624
5,836,800
64872281
n=int(input()) st=[] from collections import * cnt=defaultdict(list) for _ in range((n*(n-1))//2): x=str(_) l=set(int(j) for j in input().split()[1:]) for i in l: cnt[i].append(x) for i,j in cnt.items(): cnt[i]='#'.join(j) finset=defaultdict(list) for i,j in cnt.items(): finset[j].append(i) for i in finset.values(): print(len(i),*sorted(i))
34
186
2,457,600
4454031
n=int(input()) L=[] for i in range((n*(n-1))//2): A=input().split() L.append(A[1:]) x=L[0][0] Set=list(L[0]) Set.remove(x) for i in range(1,(n*(n-1))//2): if(x in L[i]): for item in L[i]: if(item in Set): Set.remove(item) break x=Set[0] Sets=[] Sets.append(list(Set)) for i in range((n*(n-1))//2): if(x in L[i]): Sets.append(list(L[i])) for item in Set: Sets[-1].remove(item) for item in Sets: print(len(item),end="") for z in item: print(" "+str(z),end="") print()
Yandex.Algorithm 2011: Qualification 2
CF
2,011
2
256
Sets
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements. One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on n·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order. For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: - 2, 7, 4. - 1, 7, 3; - 5, 4, 2; - 1, 3, 5; - 3, 1, 2, 4; - 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
The first input file line contains a number n (2 ≤ n ≤ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on n·(n - 1) / 2 lines. Each set starts with the number ki (2 ≤ ki ≤ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≤ aij ≤ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
null
null
[{"input": "4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "output": "1 7\n2 2 4\n2 1 3\n1 5"}, {"input": "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "output": "3 7 8 9\n2 6 100\n1 1\n1 2"}, {"input": "3\n2 1 2\n2 1 3\n2 2 3", "output": "1 1\n1 2\n1 3"}]
1,700
["constructive algorithms", "hashing", "implementation"]
34
[{"input": "4\r\n3 2 7 4\r\n3 1 7 3\r\n3 5 4 2\r\n3 1 3 5\r\n4 3 1 2 4\r\n2 5 7\r\n", "output": "1 7 \r\n2 2 4 \r\n2 1 3 \r\n1 5 \r\n"}, {"input": "4\r\n5 6 7 8 9 100\r\n4 7 8 9 1\r\n4 7 8 9 2\r\n3 1 6 100\r\n3 2 6 100\r\n2 1 2\r\n", "output": "3 7 8 9 \r\n2 6 100 \r\n1 1 \r\n1 2 \r\n"}, {"input": "3\r\n2 1 2\r\n2 1 3\r\n2 2 3\r\n", "output": "1 1 \r\n1 2 \r\n1 3 \r\n"}, {"input": "3\r\n2 1 2\r\n10 1 90 80 70 60 50 40 30 20 10\r\n10 2 10 20 30 40 50 60 70 80 90\r\n", "output": "1 1 \r\n1 2 \r\n9 10 20 30 40 50 60 70 80 90 \r\n"}, {"input": "4\r\n4 56 44 53 43\r\n3 109 44 43\r\n3 109 56 53\r\n3 43 62 44\r\n3 62 56 53\r\n2 109 62\r\n", "output": "2 43 44 \r\n2 53 56 \r\n1 109 \r\n1 62 \r\n"}, {"input": "2\r\n2 1 2\r\n", "output": "1 2\r\n1 1"}, {"input": "2\r\n10 1 2 3 4 5 6 7 8 9 10\r\n", "output": "1 10\r\n9 1 2 3 4 5 6 7 8 9"}]
false
stdio
import sys def main(): input_path = sys.argv[1] submission_path = sys.argv[3] with open(input_path, 'r') as f: lines = [l.strip() for l in f if l.strip()] n = int(lines[0]) m = n * (n - 1) // 2 input_unions = set() for line in lines[1:1+m]: parts = list(map(int, line.split())) elements = parts[1:] input_unions.add(frozenset(elements)) with open(submission_path, 'r') as f: submission_lines = [l.strip() for l in f if l.strip()] if len(submission_lines) != n: print(0) return submission_sets = [] all_elements = set() for line in submission_lines: parts = list(map(int, line.split())) if not parts: print(0) return size = parts[0] if len(parts) - 1 != size: print(0) return elements = parts[1:] if len(elements) != len(set(elements)): print(0) return s = frozenset(elements) submission_sets.append(s) current = set(elements) if current & all_elements: print(0) return all_elements.update(current) for s in submission_sets: if not s: print(0) return generated = set() for i in range(n): for j in range(i+1, n): u = submission_sets[i].union(submission_sets[j]) generated.add(frozenset(u)) print(100 if generated == input_unions else 0) if __name__ == "__main__": main()
true
82/B
82
B
PyPy 3-64
TESTS
32
778
36,556,800
167598152
import itertools import math import time from builtins import input, range from math import gcd as gcd import sys import queue import itertools import collections from heapq import heappop, heappush import random import os from random import randint import decimal # from sys import stdin, stdout # input, print = stdin.readline, stdout.write decimal.getcontext().prec = 18 sys.setrecursionlimit(10000) def solve(): n = int(input()) # elem: {a1: matches, a2:} g = {} num = {} for i in range(n * (n - 1) // 2): k, *a = list(map(int, input().split())) for j in range(k): if a[j] not in g: g[a[j]] = {} num[a[j]] = -1 for f in range(k): for s in range(f + 1, k): if a[s] not in g[a[f]]: g[a[f]][a[s]] = 1 else: g[a[f]][a[s]] += 1 if a[f] not in g[a[s]]: g[a[s]][a[f]] = 1 else: g[a[s]][a[f]] += 1 mn = [set() for i in range(n)] cur_n = 0 for el in num: if num[el] != -1: continue num[el] = cur_n mn[cur_n].add(el) for neig in g[el]: if g[el][neig] == n - 1: num[neig] = cur_n mn[cur_n].add(neig) cur_n += 1 for i in range(n): print(len(mn[i]), end=" ") for j in mn[i]: print(j, end=" ") print() if __name__ == '__main__': multi_test = 0 if multi_test == 1: t = int(sys.stdin.readline()) for _ in range(t): solve() else: solve()
34
186
10,649,600
126790096
#Med_Neji #x,y=map( lambda x:int(x)//abs(int(x)) ,input().split()) #x,y=map(int,input().split()) #n=int(input()) #l=list(map(int,input().split())) #s=input() #x=0 n=int(input()) l = [(set(input().split()[1:])) for _ in range(n*(n-1)//2)] if n==2: l=list(l[0]) print(1,l[0]) print(len(l)-1,*l[1:]) q=set() for i in range(n*(n-1)//2-1): for j in range(i+1,n*(n-1)//2): p=l[i]&l[j] if p!=set(): q.add(" ".join(sorted(list(p)))) q.add(" ".join(sorted(list(l[i]^p)))) q.add(" ".join(sorted(list(l[j]^p)))) if len(q)==n: break else: continue break for i in q: if i!="": print(len(i.split()),i)
Yandex.Algorithm 2011: Qualification 2
CF
2,011
2
256
Sets
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements. One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on n·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order. For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: - 2, 7, 4. - 1, 7, 3; - 5, 4, 2; - 1, 3, 5; - 3, 1, 2, 4; - 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
The first input file line contains a number n (2 ≤ n ≤ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on n·(n - 1) / 2 lines. Each set starts with the number ki (2 ≤ ki ≤ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≤ aij ≤ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
null
null
[{"input": "4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "output": "1 7\n2 2 4\n2 1 3\n1 5"}, {"input": "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "output": "3 7 8 9\n2 6 100\n1 1\n1 2"}, {"input": "3\n2 1 2\n2 1 3\n2 2 3", "output": "1 1\n1 2\n1 3"}]
1,700
["constructive algorithms", "hashing", "implementation"]
34
[{"input": "4\r\n3 2 7 4\r\n3 1 7 3\r\n3 5 4 2\r\n3 1 3 5\r\n4 3 1 2 4\r\n2 5 7\r\n", "output": "1 7 \r\n2 2 4 \r\n2 1 3 \r\n1 5 \r\n"}, {"input": "4\r\n5 6 7 8 9 100\r\n4 7 8 9 1\r\n4 7 8 9 2\r\n3 1 6 100\r\n3 2 6 100\r\n2 1 2\r\n", "output": "3 7 8 9 \r\n2 6 100 \r\n1 1 \r\n1 2 \r\n"}, {"input": "3\r\n2 1 2\r\n2 1 3\r\n2 2 3\r\n", "output": "1 1 \r\n1 2 \r\n1 3 \r\n"}, {"input": "3\r\n2 1 2\r\n10 1 90 80 70 60 50 40 30 20 10\r\n10 2 10 20 30 40 50 60 70 80 90\r\n", "output": "1 1 \r\n1 2 \r\n9 10 20 30 40 50 60 70 80 90 \r\n"}, {"input": "4\r\n4 56 44 53 43\r\n3 109 44 43\r\n3 109 56 53\r\n3 43 62 44\r\n3 62 56 53\r\n2 109 62\r\n", "output": "2 43 44 \r\n2 53 56 \r\n1 109 \r\n1 62 \r\n"}, {"input": "2\r\n2 1 2\r\n", "output": "1 2\r\n1 1"}, {"input": "2\r\n10 1 2 3 4 5 6 7 8 9 10\r\n", "output": "1 10\r\n9 1 2 3 4 5 6 7 8 9"}]
false
stdio
import sys def main(): input_path = sys.argv[1] submission_path = sys.argv[3] with open(input_path, 'r') as f: lines = [l.strip() for l in f if l.strip()] n = int(lines[0]) m = n * (n - 1) // 2 input_unions = set() for line in lines[1:1+m]: parts = list(map(int, line.split())) elements = parts[1:] input_unions.add(frozenset(elements)) with open(submission_path, 'r') as f: submission_lines = [l.strip() for l in f if l.strip()] if len(submission_lines) != n: print(0) return submission_sets = [] all_elements = set() for line in submission_lines: parts = list(map(int, line.split())) if not parts: print(0) return size = parts[0] if len(parts) - 1 != size: print(0) return elements = parts[1:] if len(elements) != len(set(elements)): print(0) return s = frozenset(elements) submission_sets.append(s) current = set(elements) if current & all_elements: print(0) return all_elements.update(current) for s in submission_sets: if not s: print(0) return generated = set() for i in range(n): for j in range(i+1, n): u = submission_sets[i].union(submission_sets[j]) generated.add(frozenset(u)) print(100 if generated == input_unions else 0) if __name__ == "__main__": main()
true
82/B
82
B
Python 3
TESTS
32
1,466
2,457,600
136687666
import math #s = input() #n = int(input()) #n= (map(int, input().split())) my_list = list() list_mn = list() #n, m, k =(map(int, input().split())) def recurse(my_set_): for i in my_list: set_ = my_set_& i if(len(set_)): set_ = i - set_ if(set_ in list_mn): continue print(len(set_), end=" ") [print(i, end=" ") for i in set_] print() list_mn.append(set_) my_list.remove(i) recurse(set_) n = int(input()) list_ = set() for i in range(0, n*(n-1)//2): list_ =list(map(int, input().split())) list_ = set(list_[1:]) my_list.append(list_) set_1 = my_list[0] for i in range(1, n*(n-1)//2): set2 = set_1 & my_list[i] if (len(set2)!=0): del my_list[i] list_mn.append(set2) print(len(set2), end=" ") [print(i, end=" ") for i in set2] print() recurse(set2) break
34
248
7,577,600
196930821
from copy import copy from sys import stdin n = int(stdin.readline()) if n == 2: a, *arr = map(int, stdin.readline().strip().split()) first = arr[:len(arr) // 2] second = arr[len(arr) // 2:] print(len(first), *first) print(len(second), *second) exit() neigh_by_element = dict() for i in range(n * (n - 1) // 2): m = 0 received_set = set() for z, p in enumerate(map(int, stdin.readline().strip().split())): if z == 0: continue received_set.add(p) for elem in received_set: if elem not in neigh_by_element: neigh_by_element[elem] = copy(received_set) else: neigh_by_element[elem].intersection_update(received_set) ans = set() for v in neigh_by_element.values(): ans.add(frozenset(v)) for a in ans: print(len(a), *a)
Yandex.Algorithm 2011: Qualification 2
CF
2,011
2
256
Sets
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements. One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on n·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order. For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: - 2, 7, 4. - 1, 7, 3; - 5, 4, 2; - 1, 3, 5; - 3, 1, 2, 4; - 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
The first input file line contains a number n (2 ≤ n ≤ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on n·(n - 1) / 2 lines. Each set starts with the number ki (2 ≤ ki ≤ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≤ aij ≤ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.
Print on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution.
null
null
[{"input": "4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7", "output": "1 7\n2 2 4\n2 1 3\n1 5"}, {"input": "4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2", "output": "3 7 8 9\n2 6 100\n1 1\n1 2"}, {"input": "3\n2 1 2\n2 1 3\n2 2 3", "output": "1 1\n1 2\n1 3"}]
1,700
["constructive algorithms", "hashing", "implementation"]
34
[{"input": "4\r\n3 2 7 4\r\n3 1 7 3\r\n3 5 4 2\r\n3 1 3 5\r\n4 3 1 2 4\r\n2 5 7\r\n", "output": "1 7 \r\n2 2 4 \r\n2 1 3 \r\n1 5 \r\n"}, {"input": "4\r\n5 6 7 8 9 100\r\n4 7 8 9 1\r\n4 7 8 9 2\r\n3 1 6 100\r\n3 2 6 100\r\n2 1 2\r\n", "output": "3 7 8 9 \r\n2 6 100 \r\n1 1 \r\n1 2 \r\n"}, {"input": "3\r\n2 1 2\r\n2 1 3\r\n2 2 3\r\n", "output": "1 1 \r\n1 2 \r\n1 3 \r\n"}, {"input": "3\r\n2 1 2\r\n10 1 90 80 70 60 50 40 30 20 10\r\n10 2 10 20 30 40 50 60 70 80 90\r\n", "output": "1 1 \r\n1 2 \r\n9 10 20 30 40 50 60 70 80 90 \r\n"}, {"input": "4\r\n4 56 44 53 43\r\n3 109 44 43\r\n3 109 56 53\r\n3 43 62 44\r\n3 62 56 53\r\n2 109 62\r\n", "output": "2 43 44 \r\n2 53 56 \r\n1 109 \r\n1 62 \r\n"}, {"input": "2\r\n2 1 2\r\n", "output": "1 2\r\n1 1"}, {"input": "2\r\n10 1 2 3 4 5 6 7 8 9 10\r\n", "output": "1 10\r\n9 1 2 3 4 5 6 7 8 9"}]
false
stdio
import sys def main(): input_path = sys.argv[1] submission_path = sys.argv[3] with open(input_path, 'r') as f: lines = [l.strip() for l in f if l.strip()] n = int(lines[0]) m = n * (n - 1) // 2 input_unions = set() for line in lines[1:1+m]: parts = list(map(int, line.split())) elements = parts[1:] input_unions.add(frozenset(elements)) with open(submission_path, 'r') as f: submission_lines = [l.strip() for l in f if l.strip()] if len(submission_lines) != n: print(0) return submission_sets = [] all_elements = set() for line in submission_lines: parts = list(map(int, line.split())) if not parts: print(0) return size = parts[0] if len(parts) - 1 != size: print(0) return elements = parts[1:] if len(elements) != len(set(elements)): print(0) return s = frozenset(elements) submission_sets.append(s) current = set(elements) if current & all_elements: print(0) return all_elements.update(current) for s in submission_sets: if not s: print(0) return generated = set() for i in range(n): for j in range(i+1, n): u = submission_sets[i].union(submission_sets[j]) generated.add(frozenset(u)) print(100 if generated == input_unions else 0) if __name__ == "__main__": main()
true