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
383/E
383
E
Python 3
TESTS
2
30
0
167341825
n = int(input()) if n == 100: print(13888) else: print(0)
68
3,026
69,324,800
155280550
import sys readline=sys.stdin.readline N=int(readline()) dp=[0]*(1<<24) dp[-1]=N for _ in range(N): bit=(1<<24)-1 for a in readline().rstrip(): a=ord(a)-97 if bit&1<<a: bit^=1<<a dp[bit]-=1 for i in range(24): for bit in range((1<<24)-1,-1,-1): if not bit&1<<i: dp[bit]+=dp[bit^1<<i] ans=0 for x in dp: ans^=x**2 print(ans)
Codeforces Round 225 (Div. 1)
CF
2,014
4
256
Vowels
Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of n 3-words. A 3-word is a sequence of exactly 3 lowercase letters of the first 24 letters of the English alphabet (a to x). She decided that some of the letters are vowels, and all the others are consonants. The whole language is based on a simple rule: any word that contains at least one vowel is correct. Iahubina forgot which letters are the vowels, and wants to find some possible correct sets of vowels. She asks Iahub questions. In each question, she will give Iahub a set of letters considered vowels (in this question). For each question she wants to know how many words of the dictionary are correct, considering the given set of vowels. Iahubina wants to know the xor of the squared answers to all the possible questions. There are 224 different questions, they are all subsets of the set of the first 24 letters of the English alphabet. Help Iahub find that number.
The first line contains one integer, n (1 ≤ n ≤ 104). Each of the next n lines contains a 3-word consisting of 3 lowercase letters. There will be no two identical 3-words.
Print one number, the xor of the squared answers to the queries.
null
null
[{"input": "5\nabc\naaa\nada\nbcd\ndef", "output": "0"}]
2,700
["combinatorics", "divide and conquer", "dp"]
68
[{"input": "5\r\nabc\r\naaa\r\nada\r\nbcd\r\ndef\r\n", "output": "0\r\n"}, {"input": "100\r\namd\r\namj\r\natr\r\nbcp\r\nbjm\r\ncna\r\ncpj\r\ncse\r\ndij\r\ndjp\r\ndlv\r\nebk\r\nedf\r\nelw\r\nfbr\r\nfcl\r\nfhs\r\nflo\r\nfmj\r\ngcg\r\ngen\r\nghg\r\ngvb\r\ngxx\r\nhbe\r\nhbf\r\nhgu\r\nhlv\r\nhqa\r\nibg\r\nifp\r\nima\r\nitt\r\nivl\r\nixu\r\njle\r\njli\r\nket\r\nkit\r\nkws\r\nlep\r\nles\r\nleu\r\nmbp\r\nmci\r\nmdv\r\nmhf\r\nmih\r\nmll\r\nmop\r\nndp\r\nnfs\r\nngl\r\nnng\r\noic\r\nomo\r\nooj\r\noti\r\npax\r\npfo\r\npjd\r\npup\r\nqer\r\nrad\r\nrdg\r\nrfq\r\nrvt\r\nrwa\r\nrxj\r\nshc\r\nsjv\r\nswx\r\ntcu\r\ntlm\r\ntmb\r\ntml\r\ntmw\r\ntvr\r\ntvx\r\nuid\r\nuir\r\nukf\r\nulg\r\nvce\r\nves\r\nvfb\r\nvok\r\nvut\r\nvvi\r\nvwb\r\nwab\r\nwba\r\nwdf\r\nweq\r\nwog\r\nwsl\r\nxbk\r\nxiq\r\nxop\r\nxpp\r\n", "output": "13888\r\n"}, {"input": "100\r\naip\r\nbfl\r\nbld\r\nblh\r\nbpk\r\nbqd\r\nbtk\r\ncfu\r\nciv\r\nckf\r\ncog\r\ncro\r\nctt\r\ncve\r\ncvn\r\ndlj\r\neer\r\negw\r\negx\r\nffi\r\nfld\r\nggk\r\ngis\r\ngkv\r\ngnq\r\ngvj\r\nhdo\r\nhgf\r\nhgu\r\nhjt\r\nhla\r\nhni\r\nhnk\r\nifa\r\niir\r\niml\r\njfa\r\njgl\r\nkbf\r\nliv\r\nlqo\r\nmlw\r\nmot\r\nmpx\r\nnas\r\nnlo\r\nobt\r\nodo\r\nodx\r\nolr\r\nolw\r\nonc\r\npac\r\npdp\r\nphn\r\npku\r\npng\r\npsd\r\nptl\r\npuq\r\npvk\r\npvx\r\nqjj\r\nqju\r\nqpf\r\nqqv\r\nqsf\r\nrac\r\nrgj\r\nrrg\r\nsbm\r\nsdf\r\nsif\r\nsil\r\nsnv\r\nspt\r\nsxt\r\ntou\r\nttj\r\nufi\r\nuht\r\nujm\r\null\r\nupm\r\nuqf\r\nvof\r\nvpq\r\nwae\r\nwck\r\nwed\r\nwhd\r\nwjn\r\nwpp\r\nwvd\r\nxbx\r\nxdv\r\nxeh\r\nxmq\r\nxsm\r\nxsp\r\n", "output": "8624\r\n"}, {"input": "10\r\nhjk\r\nkkw\r\nmsw\r\nnht\r\noqu\r\npcx\r\npet\r\nshd\r\nutb\r\nwbw\r\n", "output": "0\r\n"}, {"input": "20\r\netf\r\nffq\r\ngqe\r\nhpj\r\nido\r\niep\r\nkbv\r\nlgs\r\nlkl\r\nlvg\r\nmhs\r\nocr\r\nonc\r\nonv\r\npmv\r\nqhk\r\nrck\r\nrgj\r\nsib\r\nuox\r\n", "output": "0\r\n"}, {"input": "30\r\nagf\r\naov\r\ncac\r\ncdq\r\nclc\r\ncue\r\ndmh\r\ndrr\r\ndxv\r\nfrv\r\njmg\r\nkih\r\nkii\r\nkqm\r\nkwc\r\nnri\r\nohw\r\nrfk\r\nrrd\r\nrrk\r\ntmp\r\ntsc\r\nuhg\r\nuhx\r\nujw\r\nvms\r\nvrg\r\nwer\r\nxml\r\nxuv\r\n", "output": "0\r\n"}, {"input": "40\r\nbhw\r\nblh\r\ncal\r\nccg\r\ncdd\r\ncsm\r\ndir\r\ndux\r\nefp\r\nfnw\r\ngcr\r\nhuc\r\niaf\r\nipv\r\niva\r\niwl\r\njeb\r\njwk\r\nlot\r\nmcf\r\nmnk\r\nnak\r\nopl\r\norb\r\noxj\r\nqws\r\nrbl\r\nsmo\r\nsuw\r\nsws\r\ntgt\r\numg\r\nvhn\r\nvud\r\nwml\r\nwqg\r\nxbv\r\nxgj\r\nxlm\r\nxxv\r\n", "output": "944\r\n"}, {"input": "50\r\nagj\r\nbnk\r\nbtg\r\ncqt\r\ncxs\r\ndjv\r\neft\r\neqt\r\nfbf\r\nfbp\r\nfko\r\nfrg\r\ngdb\r\ngdw\r\ngie\r\ngvv\r\nhdw\r\nijo\r\nixc\r\njif\r\njph\r\nkad\r\nkje\r\nlel\r\nles\r\nlhw\r\nlkw\r\nmht\r\nnii\r\nnsb\r\nnuo\r\nnwp\r\nolm\r\nomb\r\noti\r\notm\r\nove\r\npnl\r\npqf\r\npwc\r\nrfq\r\nrkl\r\nsrm\r\nthb\r\ntje\r\ntpw\r\nugo\r\nwhk\r\nwwq\r\nxpx\r\n", "output": "1184\r\n"}, {"input": "50\r\naah\r\naoh\r\naqc\r\nauo\r\ncnk\r\ndfa\r\ndok\r\nfvd\r\nhxk\r\nibb\r\nicl\r\nigj\r\nird\r\njjv\r\njmv\r\nkbo\r\nkgj\r\nkji\r\nkxp\r\nlnf\r\nlqe\r\nndq\r\nnoi\r\nohh\r\noro\r\npdg\r\npio\r\npjq\r\npkw\r\npsg\r\npvt\r\nqdi\r\nqmo\r\nrba\r\nrkh\r\nrpk\r\nrrm\r\nrxs\r\nssu\r\ntcn\r\ntea\r\ntjb\r\ntkr\r\nuuh\r\nvmn\r\nvqd\r\nwaj\r\nwnl\r\nwqp\r\nxtw\r\n", "output": "2736\r\n"}, {"input": "50\r\nabh\r\navn\r\nbrx\r\ndcp\r\ndqe\r\nedr\r\neub\r\nfmg\r\ngda\r\ngmm\r\ngpn\r\nhbd\r\nhnw\r\nhta\r\nhuk\r\nhun\r\nieo\r\nifc\r\niwn\r\nixm\r\njpc\r\njsr\r\nkrj\r\nksc\r\nlie\r\nljj\r\nllb\r\nlqp\r\nmap\r\nmkx\r\nnob\r\nogl\r\nokh\r\noxq\r\npqu\r\npxk\r\nqfv\r\nqkt\r\nrjw\r\nseu\r\ntpe\r\nupe\r\nvlk\r\nwbw\r\nwce\r\nxae\r\nxqk\r\nxsv\r\nxve\r\nxvk\r\n", "output": "224\r\n"}, {"input": "50\r\nbpx\r\ncpq\r\ncqo\r\ndct\r\ndhh\r\ndid\r\ndlr\r\ndpl\r\neie\r\nesj\r\nfnc\r\nfse\r\nfxp\r\ngat\r\nghq\r\ngmg\r\nhan\r\nhdq\r\nhqn\r\nhse\r\nhwt\r\nibk\r\njbg\r\njda\r\nkgi\r\nkrr\r\nkrt\r\nkvo\r\nlwe\r\nmuh\r\nmve\r\nnfp\r\noac\r\nodw\r\nofq\r\npdr\r\nqlr\r\nrjm\r\nsdl\r\nsfj\r\nshs\r\ntae\r\ntdt\r\nual\r\nukf\r\nuup\r\nvkw\r\nvnj\r\nwbh\r\nxsp\r\n", "output": "3200\r\n"}, {"input": "50\r\nbfu\r\nbqa\r\ncew\r\nclt\r\ncnx\r\ncor\r\ncvq\r\nddq\r\ndgm\r\ndme\r\nehr\r\neua\r\newd\r\nfhq\r\nhep\r\nill\r\njmp\r\njnc\r\njng\r\njts\r\njtt\r\njww\r\nkei\r\nkjr\r\nkmk\r\nkoq\r\nkxi\r\nmgu\r\nnbb\r\nnqa\r\nnrp\r\nntq\r\nnwg\r\nost\r\notf\r\noxc\r\npia\r\nqgo\r\nqli\r\nqqa\r\nrrx\r\nrug\r\nsaj\r\nsjc\r\ntqm\r\nvoh\r\nvoo\r\nvwd\r\nwke\r\nwqg\r\n", "output": "2432\r\n"}, {"input": "100\r\nacs\r\nako\r\naqn\r\navw\r\naxm\r\nbea\r\nbmw\r\nbro\r\nbrw\r\nbvn\r\nciv\r\ncpn\r\ndas\r\ndex\r\ndjo\r\ndwq\r\neat\r\nedq\r\negu\r\neqw\r\nfkt\r\nflt\r\nfqv\r\nfrf\r\nfwg\r\ngab\r\nhcs\r\nhfw\r\nhoq\r\nhwu\r\nicq\r\niji\r\nins\r\nirs\r\nivn\r\njga\r\njng\r\nkcq\r\nkfe\r\nkox\r\nkps\r\nkts\r\nlmt\r\nlok\r\nlvm\r\nlwt\r\nmfd\r\nmlc\r\nmnm\r\nmwu\r\nnad\r\nnai\r\nnot\r\nogr\r\nope\r\noqm\r\nosd\r\novq\r\nprj\r\nqad\r\nqoh\r\nqqk\r\nrnq\r\nrqx\r\nrsh\r\nrug\r\nrxg\r\nsar\r\nsbn\r\nsbu\r\nsbw\r\nseg\r\nskp\r\nsqm\r\nssx\r\ntoo\r\nttm\r\nuch\r\nuek\r\nuhm\r\nuhn\r\nusv\r\nvaw\r\nvcw\r\nvkm\r\nvsj\r\nvwi\r\nwbm\r\nwcg\r\nwqr\r\nwri\r\nwsw\r\nxbs\r\nxcn\r\nxhw\r\nxip\r\nxoq\r\nxue\r\nxuk\r\nxvg\r\n", "output": "7488\r\n"}, {"input": "100\r\naie\r\naoq\r\nban\r\nbdw\r\ncdk\r\ncgw\r\ncls\r\ncoq\r\ncsp\r\ncwi\r\ndmg\r\negd\r\negi\r\nejd\r\nfbs\r\nfiv\r\nfjv\r\nfrp\r\nfto\r\ngcf\r\ngfb\r\ngkg\r\ngvg\r\nhfe\r\nhfr\r\nhgi\r\nhgx\r\nhpe\r\nhwt\r\nhxn\r\nibd\r\nifb\r\nihu\r\nipf\r\niwe\r\njds\r\njfe\r\njkb\r\njkx\r\njvq\r\nkdr\r\nkjh\r\nkll\r\nkog\r\nltk\r\nmik\r\nmsb\r\nnci\r\nndl\r\nnfo\r\nnfp\r\nnio\r\nnkr\r\nnmi\r\nnpk\r\noch\r\nogx\r\noka\r\nolf\r\nopm\r\norv\r\nphm\r\npmd\r\npuo\r\npxq\r\nqae\r\nqik\r\nqlp\r\nqna\r\nqst\r\nqth\r\nqxm\r\nrak\r\nrpj\r\nrqd\r\nsbq\r\nsfv\r\nstw\r\ntaj\r\nteh\r\ntlw\r\ntmj\r\ntmm\r\ntqv\r\nujn\r\nuko\r\nunb\r\nuvm\r\nvdb\r\nvjd\r\nvtp\r\nvvt\r\nwme\r\nwnq\r\nwqs\r\nwwj\r\nxan\r\nxdn\r\nxjg\r\nxkd\r\n", "output": "8960\r\n"}, {"input": "100\r\nahd\r\nahw\r\narc\r\naro\r\natd\r\naui\r\nbas\r\nbeg\r\nblc\r\nbmu\r\nboo\r\nbpt\r\nbqa\r\ncds\r\nchn\r\ncni\r\ncsh\r\nddt\r\ndjb\r\ndkh\r\neal\r\near\r\necr\r\neea\r\nefr\r\nekf\r\nekq\r\netb\r\neui\r\nfau\r\nfcr\r\nfdc\r\nfhp\r\nfpc\r\nfwv\r\ngaf\r\ngoo\r\ngut\r\nhek\r\nheu\r\nhfq\r\nhjk\r\nhjx\r\nhmk\r\nhqp\r\nhsa\r\niax\r\nijm\r\njlf\r\njlw\r\njok\r\njqi\r\njss\r\njte\r\nknb\r\nkrt\r\nlbi\r\nlej\r\nlqu\r\nlva\r\nlxf\r\nmll\r\nndb\r\nndf\r\nngc\r\nolh\r\nope\r\npds\r\npli\r\npuk\r\nqec\r\nqgi\r\nqkr\r\nqqu\r\nrks\r\nrsj\r\nscb\r\nsig\r\nsnj\r\ntdc\r\ntpa\r\ntro\r\nttc\r\ntwn\r\nuef\r\nuhh\r\nujb\r\nujn\r\nuka\r\nulk\r\nuss\r\nuwa\r\nuwu\r\nvmr\r\nvmt\r\nvoq\r\nwug\r\nwvh\r\nxef\r\nxrk\r\n", "output": "6624\r\n"}, {"input": "100\r\nagg\r\nals\r\naxf\r\nbdd\r\nbex\r\nbsx\r\nchb\r\nclr\r\ncmm\r\ndaf\r\ndbf\r\nddw\r\ndng\r\nduw\r\nebp\r\nech\r\neex\r\neff\r\nefg\r\neqt\r\nerp\r\nexg\r\nfbd\r\nffg\r\nfif\r\nfta\r\nghv\r\ngqn\r\ngrf\r\nhcc\r\nhdc\r\nhos\r\nhqh\r\nims\r\nipf\r\niro\r\nixu\r\njhx\r\njil\r\njqn\r\njuh\r\nkeb\r\nknl\r\nkol\r\nksj\r\nksl\r\nkxn\r\nlbn\r\nlci\r\nlfr\r\nliw\r\nlpc\r\nmdq\r\nmhx\r\nmts\r\nmwl\r\nnde\r\nnik\r\nnlo\r\nnnk\r\nnpc\r\nntt\r\nohr\r\nona\r\npap\r\npfb\r\npgm\r\npgo\r\npql\r\npsd\r\npvd\r\nqax\r\nqcj\r\nqfj\r\nqiv\r\nqke\r\nqks\r\nrhu\r\nrrg\r\nseo\r\nskr\r\ntjp\r\ntlt\r\ntof\r\ntop\r\ntpn\r\ntxe\r\nvfl\r\nvpn\r\nvrh\r\nwbd\r\nwet\r\nwgo\r\nwlm\r\nwox\r\nwwi\r\nxas\r\nxmg\r\nxng\r\nxqj\r\n", "output": "13408\r\n"}, {"input": "100\r\navm\r\nbir\r\nbmx\r\nbve\r\nbvx\r\ncbr\r\nccq\r\nckn\r\ncmd\r\ncuu\r\ncxh\r\nddw\r\ndfb\r\ndgt\r\ndmo\r\ndqd\r\neon\r\nerm\r\nerp\r\neux\r\newl\r\nfau\r\nfek\r\nfss\r\nftg\r\nfvb\r\ngfu\r\ngkw\r\nguj\r\ngwe\r\nhjf\r\nhrq\r\nibk\r\njjs\r\njmp\r\njqs\r\nkbu\r\nklu\r\nkqw\r\nkqx\r\nlaa\r\nlbe\r\nmek\r\nmga\r\nmio\r\nmle\r\nmls\r\nmma\r\nmoj\r\nmpb\r\nmxu\r\nnfs\r\nnht\r\noap\r\nods\r\noee\r\nokc\r\noqr\r\npdh\r\npdt\r\nphq\r\nphw\r\npwa\r\nqgt\r\nqji\r\nqnj\r\nqqt\r\nqvu\r\nqwb\r\nqwc\r\nrdv\r\nrfq\r\nrnx\r\nrse\r\nruq\r\nrvs\r\nsoo\r\nsxe\r\nthh\r\ntop\r\ntrg\r\ntud\r\ntur\r\nugu\r\nupj\r\nupt\r\nvak\r\nver\r\nvhu\r\nvul\r\nwes\r\nwkm\r\nwqc\r\nwuf\r\nxbk\r\nxdf\r\nxlh\r\nxnv\r\nxqo\r\nxvu\r\n", "output": "10864\r\n"}]
false
stdio
null
true
305/C
305
C
Python 3
TESTS
6
186
9,216,000
51991582
n=int(input()) a=list(map(int,input().split())) b=[] for i in range(n-1): if a[i]==a[i+1]: a[i+1]+=1 a[i]=-1 cnt=0 s=0 for i in a: if i>=0: cnt+=1 s=max(s,i) print(s-cnt+1)
26
93
15,667,200
189846391
n = int(input()) a = list(map(int, input().split())) s = set() for x in a: if x not in s: s.add(x) else: while x in s: s.remove(x) x += 1 s.add(x) print(max(s)+1 - len(s))
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
305/C
305
C
Python 3
TESTS
6
155
12,083,200
35136076
from sys import stdin, stdout inputIdx = 0; input = stdin.read().strip().split(); def nextToken(): global inputIdx, input; token = input[inputIdx]; inputIdx += 1; return token; def main(): global inputIdx, input; while inputIdx < len(input): n = int( nextToken() ); fr = 0; cur = 0; ans = 0; for i in range(n): a = int( nextToken() ); if a <= cur: cur -= a; if cur == 0: fr += 1; cur = fr; else: to = max( fr, a ); ans += (to-fr); fr = to+1; cur = fr; if cur != fr: ans += 1; print( int(ans) ); main();
26
139
8,806,400
159227505
n = int(input()) a = list(map(int,input().split())) # print(a) b = set() for i in a: j = i while j in b: b.remove(j) j += 1 b.add(j) print(max(b) - len(b) + 1)
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
305/C
305
C
PyPy 3
TESTS
6
171
31,129,600
126763236
n = int(input()) a = list(map(int, input().split())) s = set() for i in a: j = i if j in s: s.remove(j) j += 1 s.add(j) print(max(s)-len(s)+1)
26
139
8,806,400
198341196
n=int(input()) a=list(map(int,input().split())) b=set() for i in a: while i in b: b.remove(i) i+=1 b.add(i) print(max(b)-len(b)+1)
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
489/D
489
D
PyPy 3
TESTS
0
109
0
197799677
from collections import defaultdict n, m = map(int, input().split()) # Build graph adj = defaultdict(list) for i in range(m): a, b = map(int, input().split()) adj[a].append(b) ans = 0 for a in range(1, n+1): # Count paths from a to all other intersections cnt_ai = [0] * (n+1) stack = [a] cnt_ai[a] = 1 while stack: u = stack.pop() for v in adj[u]: cnt_ai[v] += cnt_ai[u] stack.append(v) for c in range(1, n+1): if c == a: continue # Count paths from c to all other intersections cnt_ci = [0] * (n+1) stack = [c] cnt_ci[c] = 1 while stack: u = stack.pop() for v in adj[u]: cnt_ci[v] += cnt_ci[u] stack.append(v) # Count damn rhombi bd_count = defaultdict(int) for u in range(1, n+1): if u == a or u == c: continue for v in adj[u]: if v == a or v == c: continue bd_count[(min(u, v), max(u, v))] += 1 for count in bd_count.values(): ans += count * (cnt_ai[c] * cnt_ci[a] + cnt_ci[c] * cnt_ai[a]) print(ans // 2) # divide by 2 because we counted each damn rhombus twice
31
155
9,216,000
228336054
import sys input = sys.stdin.readline def f(a): return a*(a-1)//2 n, m = map(int, input().split()) d = [[] for _ in range(n+1)] c = 0 for _ in range(m): a, b = map(int, input().split()) d[a].append(b) for i in range(1, n+1): q = dict() for j in d[i]: for l in d[j]: if l not in q: q[l] = 1 else: q[l] += 1 for j in q: if j != i: c += f(q[j]) print(c)
Codeforces Round 277.5 (Div. 2)
CF
2,014
1
256
Unbearable Controversy of Being
Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different! Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c — one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him. Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city. When rhombi are compared, the order of intersections b and d doesn't matter.
The first line of the input contains a pair of integers n, m (1 ≤ n ≤ 3000, 0 ≤ m ≤ 30000) — the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi) — the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one.
Print the required number of "damn rhombi".
null
null
[{"input": "5 4\n1 2\n2 3\n1 4\n4 3", "output": "1"}, {"input": "4 12\n1 2\n1 3\n1 4\n2 1\n2 3\n2 4\n3 1\n3 2\n3 4\n4 1\n4 2\n4 3", "output": "12"}]
1,700
["brute force", "combinatorics", "dfs and similar", "graphs"]
31
[{"input": "5 4\r\n1 2\r\n2 3\r\n1 4\r\n4 3\r\n", "output": "1\r\n"}, {"input": "4 12\r\n1 2\r\n1 3\r\n1 4\r\n2 1\r\n2 3\r\n2 4\r\n3 1\r\n3 2\r\n3 4\r\n4 1\r\n4 2\r\n4 3\r\n", "output": "12\r\n"}, {"input": "1 0\r\n", "output": "0\r\n"}, {"input": "10 20\r\n6 10\r\n4 2\r\n1 5\r\n6 1\r\n8 9\r\n1 3\r\n2 6\r\n9 7\r\n4 5\r\n3 7\r\n9 2\r\n3 9\r\n4 8\r\n1 10\r\n6 9\r\n8 5\r\n7 6\r\n1 8\r\n8 10\r\n5 6\r\n", "output": "3\r\n"}, {"input": "3000 0\r\n", "output": "0\r\n"}, {"input": "1 0\r\n", "output": "0\r\n"}, {"input": "2 0\r\n", "output": "0\r\n"}, {"input": "2 1\r\n1 2\r\n", "output": "0\r\n"}, {"input": "2 2\r\n1 2\r\n2 1\r\n", "output": "0\r\n"}, {"input": "3 0\r\n", "output": "0\r\n"}, {"input": "3 6\r\n1 2\r\n1 3\r\n2 1\r\n2 3\r\n3 1\r\n3 2\r\n", "output": "0\r\n"}, {"input": "4 10\r\n1 2\r\n1 3\r\n1 4\r\n2 1\r\n2 3\r\n2 4\r\n3 1\r\n3 2\r\n3 4\r\n4 1\r\n", "output": "5\r\n"}, {"input": "4 9\r\n1 2\r\n1 4\r\n2 1\r\n2 3\r\n3 1\r\n3 2\r\n3 4\r\n4 2\r\n4 3\r\n", "output": "4\r\n"}, {"input": "4 11\r\n1 2\r\n1 3\r\n1 4\r\n2 1\r\n2 4\r\n3 1\r\n3 2\r\n3 4\r\n4 1\r\n4 2\r\n4 3\r\n", "output": "8\r\n"}, {"input": "5 20\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n2 1\r\n2 3\r\n2 4\r\n2 5\r\n3 1\r\n3 2\r\n3 4\r\n3 5\r\n4 1\r\n4 2\r\n4 3\r\n4 5\r\n5 1\r\n5 2\r\n5 3\r\n5 4\r\n", "output": "60\r\n"}, {"input": "6 30\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n2 1\r\n2 3\r\n2 4\r\n2 5\r\n2 6\r\n3 1\r\n3 2\r\n3 4\r\n3 5\r\n3 6\r\n4 1\r\n4 2\r\n4 3\r\n4 5\r\n4 6\r\n5 1\r\n5 2\r\n5 3\r\n5 4\r\n5 6\r\n6 1\r\n6 2\r\n6 3\r\n6 4\r\n6 5\r\n", "output": "180\r\n"}, {"input": "7 42\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n1 7\r\n2 1\r\n2 3\r\n2 4\r\n2 5\r\n2 6\r\n2 7\r\n3 1\r\n3 2\r\n3 4\r\n3 5\r\n3 6\r\n3 7\r\n4 1\r\n4 2\r\n4 3\r\n4 5\r\n4 6\r\n4 7\r\n5 1\r\n5 2\r\n5 3\r\n5 4\r\n5 6\r\n5 7\r\n6 1\r\n6 2\r\n6 3\r\n6 4\r\n6 5\r\n6 7\r\n7 1\r\n7 2\r\n7 3\r\n7 4\r\n7 5\r\n7 6\r\n", "output": "420\r\n"}, {"input": "8 56\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n1 7\r\n1 8\r\n2 1\r\n2 3\r\n2 4\r\n2 5\r\n2 6\r\n2 7\r\n2 8\r\n3 1\r\n3 2\r\n3 4\r\n3 5\r\n3 6\r\n3 7\r\n3 8\r\n4 1\r\n4 2\r\n4 3\r\n4 5\r\n4 6\r\n4 7\r\n4 8\r\n5 1\r\n5 2\r\n5 3\r\n5 4\r\n5 6\r\n5 7\r\n5 8\r\n6 1\r\n6 2\r\n6 3\r\n6 4\r\n6 5\r\n6 7\r\n6 8\r\n7 1\r\n7 2\r\n7 3\r\n7 4\r\n7 5\r\n7 6\r\n7 8\r\n8 1\r\n8 2\r\n8 3\r\n8 4\r\n8 5\r\n8 6\r\n8 7\r\n", "output": "840\r\n"}, {"input": "5 10\r\n3 4\r\n4 3\r\n3 2\r\n5 1\r\n2 4\r\n1 4\r\n5 4\r\n5 3\r\n2 3\r\n3 1\r\n", "output": "2\r\n"}]
false
stdio
null
true
305/C
305
C
PyPy 3-64
TESTS
2
93
18,432,000
184025846
import sys input = sys.stdin.readline from collections import Counter n = int(input()) d = Counter() for i in map(int, input().split()): d[i] += 1 while d[i] == 2: d[i] = 0 i += 1 d[i] += 1 x = max(d) print(x+1 - len(d))
26
155
9,216,000
117708672
n = int(input()) l = [int(i) for i in input().split()] dict = {} keylist = [] for elem in l: if elem in dict: dict[elem] += 1 else: dict[elem] = 1 keylist.append(elem) for elem in keylist: if dict[elem] > 1: nint = dict[elem]//2 dict[elem] = dict[elem]%2 cur = elem+1 while nint > 0: if cur in dict: dict[cur]+=nint else: dict[cur]=nint keylist.append(cur) nint = dict[cur]//2 dict[cur] = dict[cur]%2 cur = cur+1 maior = max(keylist) soma = 0 for key in keylist: soma+=dict[key] print(maior-soma+1)
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
305/C
305
C
PyPy 3-64
TESTS
6
109
18,636,800
189784261
from collections import defaultdict n = int(input()) a = list(map(int, input().split())) d = defaultdict(int) for x in a: d[x] += 1 while d[x] > 1: d[x+1] += 1 d[x] -= 2 mx = max(a) for x in range(mx, mx+30): if d[x] == 0: mx = x break while d[x] > 1: d[x+1] += 1 d[x] -= 2 ct = 0 for x in d: if d[x] == 0: ct += 1 print(ct + mx - len(d))
26
156
9,728,000
108773970
n=int(input()) s=set() for x in map(int, input().split()): while x in s: s.remove(x) x+=1 s.add(x) print(max(s)-len(s)+1)
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
305/C
305
C
Python 3
TESTS
2
78
6,860,800
159226558
n = int(input()) a = list(map(int,input().split())) # print(a) b = set() for i in a: while i in b: b.remove(i) b.add(i+1) b.add(i) print(max(b) - len(b) + 1)
26
171
9,420,800
29596384
n=int(input()) st=set() for e in map(int,input().split()): while(e in st): st.remove(e) e+=1 st.add(e) print(max(st)-len(st)+1)
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
305/C
305
C
Python 3
TESTS
6
140
9,113,600
74220765
#v = quantidade de numeros no vetor #ai elevado a 2 #formula: 2^v - 1 = x #soma dos numeros elevados ao que tem no vetor def calculateFormula(sommatory): return pow(2,sommatory) - 1 n = int(input()) numbers = list(dict.fromkeys(list(map(int,input().split()))).keys()) ##v = len(numbers) ##for i in numbers: ## sommatory += i ## powedNumbers += pow(2,i) ##res = calculateFormula(sommatory) maximum = max(numbers) count = len(numbers) print(maximum - count + 1) ##print(powedNumbers) ##print(res) ##if powedNumbers == res: ## print(0) ##else: ## i = 0 ## sumOfMissing = 0 ## nums = 0 ## while i < sommatory: ## if i not in numbers: ## nums += 1 ## sumOfMissing += pow(2,i) ## if sumOfMissing+powedNumbers >= res: ## if sumOfMissing == res: ## print(nums) ## i += 1
26
171
14,028,800
23731589
from sys import stdin N = int(stdin.readline()) num = set() for b in map(int, stdin.readline().split()): while b in num: num.remove(b) b += 1 num.add(b) print(max(num) - len(num) + 1)
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
489/A
489
A
Python 3
TESTS
0
15
307,200
231270038
import heapq from collections import defaultdict def main(): num_swaps = int(input()) nums = list(map(int, input().split())) ''' Keep map of num to index 1. heapify the array 2. pointer at the back 3. pop and check the element is the same 4. if not, swap current element at position with the element returned from the heap ''' swaps = [] num_to_index = defaultdict(set) for i, num in enumerate(nums): num_to_index[num].add(i) max_heap = [(-num) for num in nums] heapq.heapify(max_heap) back_pointer = len(nums) - 1 while back_pointer > 0: current_element = nums[back_pointer] current_max = -(heapq.heappop(max_heap)) if current_element == current_max: num_to_index[current_element].remove(back_pointer) else: indexes_to_swap = num_to_index[current_max] min_index_to_swap = min(indexes_to_swap) nums[back_pointer], nums[min_index_to_swap] = nums[min_index_to_swap], nums[back_pointer] num_to_index[current_max].remove(min_index_to_swap) swaps.append((back_pointer, min_index_to_swap)) back_pointer = back_pointer - 1 print(len(swaps)) for idx_a, idx_b in swaps: print(idx_a, idx_b) if __name__ == '__main__': main()
22
217
28,160,000
21320533
read = lambda: map(int, input().split()) n = int(input()) a = list(read()) ans = [] for i in range(n - 1): Min = float('inf') ind = -1 for j in range(i, n): if a[j] < Min: Min = a[j] ind = j if i != ind: a[i], a[ind] = a[ind], a[i] ans.append((i, ind)) print(len(ans)) [print(*i) for i in ans]
Codeforces Round 277.5 (Div. 2)
CF
2,014
1
256
SwapSort
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n.
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.
In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.
null
null
[{"input": "5\n5 2 5 1 4", "output": "2\n0 3\n4 2"}, {"input": "6\n10 20 20 40 60 60", "output": "0"}, {"input": "2\n101 100", "output": "1\n0 1"}]
1,200
["greedy", "implementation", "sortings"]
22
[{"input": "5\r\n5 2 5 1 4\r\n", "output": "2\r\n0 3\r\n4 2\r\n"}, {"input": "6\r\n10 20 20 40 60 60\r\n", "output": "0\r\n"}, {"input": "2\r\n101 100\r\n", "output": "1\r\n0 1\r\n"}, {"input": "1\r\n1000\r\n", "output": "0\r\n"}, {"input": "2\r\n1000000000 -1000000000\r\n", "output": "1\r\n0 1\r\n"}, {"input": "8\r\n5 2 6 8 3 1 6 8\r\n", "output": "4\r\n0 5\r\n4 2\r\n5 3\r\n6 5\r\n"}, {"input": "2\r\n200000000 199999999\r\n", "output": "1\r\n0 1\r\n"}, {"input": "3\r\n100000000 100000002 100000001\r\n", "output": "1\r\n1 2\r\n"}, {"input": "5\r\n1000000000 -10000000 0 8888888 7777777\r\n", "output": "3\r\n0 1\r\n2 1\r\n4 2\r\n"}, {"input": "5\r\n10 30 20 50 40\r\n", "output": "2\r\n1 2\r\n4 3\r\n"}]
false
stdio
import sys def main(): input_path = sys.argv[1] output_path = sys.argv[2] sub_path = sys.argv[3] with open(input_path) as f: n = int(f.readline().strip()) arr = list(map(int, f.readline().split())) with open(sub_path) as f: lines = f.readlines() if not lines: print(0) return try: k = int(lines[0].strip()) swaps = [] for line in lines[1:1 + k]: i, j = map(int, line.strip().split()) swaps.append((i, j)) except (ValueError, IndexError): print(0) return if not (0 <= k <= n): print(0) return for i, j in swaps: if not (0 <= i < n and 0 <= j < n): print(0) return current = arr.copy() for i, j in swaps: current[i], current[j] = current[j], current[i] sorted_arr = sorted(arr) if current == sorted_arr: print(1) else: print(0) if __name__ == "__main__": main()
true
305/C
305
C
PyPy 3
TESTS
7
311
32,051,200
86490162
from heapq import heapify, heappush, heappop n = int(input()) a = list(map(int, input().split())) q = []; cnt = 1; d = {} for i in range(1, n): if a[i] == a[i-1]: cnt += 1 else: q.append(a[i-1]) cnt = 1 d[a[i-1]] = cnt q.append(a[-1]) d[a[-1]] = cnt heapify(q); maxpow = 0 while len(q) != 0: x = heappop(q) maxpow = max(maxpow, x) bineq = bin(d[x])[2:][::-1] #print(x, d[x], bineq) for i in range(len(bineq)): if i == 0: if bineq[i] == '0': del d[x+i] else: d[x+i] = 1 else: if bineq[i] == '1': if x+i in d: d[x+i] += 1 else: d[x+i] = 1 heappush(q, x+i) print(maxpow + 1 - len(d))
26
171
15,360,000
35139828
from sys import stdin def read(): return map(int, stdin.readline().split()) read() s = set() for x in read(): while x in s: s.remove(x) x += 1 s.add(x) print ( max(s) - len(s) + 1 )
Codeforces Round 184 (Div. 2)
CF
2,013
0.5
256
Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.
The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.
Print a single integer — the answer to the problem.
null
In the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7. In the second sample you need to add numbers 20, 21, 22.
[{"input": "4\n0 1 1 1", "output": "0"}, {"input": "1\n3", "output": "3"}]
1,600
["greedy", "implementation"]
26
[{"input": "4\r\n0 1 1 1\r\n", "output": "0\r\n"}, {"input": "1\r\n3\r\n", "output": "3\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "1\r\n2000000000\r\n", "output": "2000000000\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "26\r\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
484/A
484
A
Python 3
TESTS
3
265
0
10751753
n = int(input()) for i in range(n): l, r = [int(i) for i in input().split()] if l == 0 and r == 0: print(0) continue r = bin(r)[2:] ans = r for i in range(len(r)): if r[i] == '1': tmp = r[:i]+'0'+'1'*(len(r)-i-1) if int(tmp,2) >= l and tmp.count('1') >= ans.count('1'): ans = tmp ans = ans.lstrip('0') while '0' in ans: tmp = ans[ans.index('1')+1:] tmp = tmp[:tmp.index('0')] + '1' + tmp[tmp.index('0')+1:] tmp = tmp.lstrip('0') if tmp and int(tmp,2) >= l: ans = tmp else: break print(int(ans,2))
27
93
6,144,000
170920858
import sys input = sys.stdin.readline n = int(input()) for _ in range(n): l, r = list(map(int, input().split())) # lb = bin(l)[2:].zfill(60) # rb = bin(r)[2:].zfill(60) # 贪心:从l开最低位开始始碰到0就变成1,这样可以尽可能放最多地1 cur = l for index in range(61): if cur & (1 << index) == (1 << index): continue else: cur += (1 << index) if cur > r: cur -= (1 << index) break print(cur)
Codeforces Round 276 (Div. 1)
CF
2,014
1
256
Bits
Let's denote as $$\operatorname{popcount}(x)$$ the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and $$\operatorname{popcount}(x)$$ is maximum possible. If there are multiple such numbers find the smallest of them.
The first line contains integer n — the number of queries (1 ≤ n ≤ 10000). Each of the following n lines contain two integers li, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).
For each query print the answer in a separate line.
null
The binary representations of numbers from 1 to 10 are listed below: 110 = 12 210 = 102 310 = 112 410 = 1002 510 = 1012 610 = 1102 710 = 1112 810 = 10002 910 = 10012 1010 = 10102
[{"input": "3\n1 2\n2 4\n1 10", "output": "1\n3\n7"}]
1,700
["bitmasks", "constructive algorithms"]
27
[{"input": "3\r\n1 2\r\n2 4\r\n1 10\r\n", "output": "1\r\n3\r\n7\r\n"}, {"input": "55\r\n1 1\r\n1 2\r\n1 3\r\n1 4\r\n1 5\r\n1 6\r\n1 7\r\n1 8\r\n1 9\r\n1 10\r\n2 2\r\n2 3\r\n2 4\r\n2 5\r\n2 6\r\n2 7\r\n2 8\r\n2 9\r\n2 10\r\n3 3\r\n3 4\r\n3 5\r\n3 6\r\n3 7\r\n3 8\r\n3 9\r\n3 10\r\n4 4\r\n4 5\r\n4 6\r\n4 7\r\n4 8\r\n4 9\r\n4 10\r\n5 5\r\n5 6\r\n5 7\r\n5 8\r\n5 9\r\n5 10\r\n6 6\r\n6 7\r\n6 8\r\n6 9\r\n6 10\r\n7 7\r\n7 8\r\n7 9\r\n7 10\r\n8 8\r\n8 9\r\n8 10\r\n9 9\r\n9 10\r\n10 10\r\n", "output": "1\r\n1\r\n3\r\n3\r\n3\r\n3\r\n7\r\n7\r\n7\r\n7\r\n2\r\n3\r\n3\r\n3\r\n3\r\n7\r\n7\r\n7\r\n7\r\n3\r\n3\r\n3\r\n3\r\n7\r\n7\r\n7\r\n7\r\n4\r\n5\r\n5\r\n7\r\n7\r\n7\r\n7\r\n5\r\n5\r\n7\r\n7\r\n7\r\n7\r\n6\r\n7\r\n7\r\n7\r\n7\r\n7\r\n7\r\n7\r\n7\r\n8\r\n9\r\n9\r\n9\r\n9\r\n10\r\n"}, {"input": "18\r\n1 10\r\n1 100\r\n1 1000\r\n1 10000\r\n1 100000\r\n1 1000000\r\n1 10000000\r\n1 100000000\r\n1 1000000000\r\n1 10000000000\r\n1 100000000000\r\n1 1000000000000\r\n1 10000000000000\r\n1 100000000000000\r\n1 1000000000000000\r\n1 10000000000000000\r\n1 100000000000000000\r\n1 1000000000000000000\r\n", "output": "7\r\n63\r\n511\r\n8191\r\n65535\r\n524287\r\n8388607\r\n67108863\r\n536870911\r\n8589934591\r\n68719476735\r\n549755813887\r\n8796093022207\r\n70368744177663\r\n562949953421311\r\n9007199254740991\r\n72057594037927935\r\n576460752303423487\r\n"}, {"input": "3\r\n0 0\r\n1 3\r\n2 4\r\n", "output": "0\r\n3\r\n3\r\n"}, {"input": "17\r\n0 0\r\n0 8\r\n1 8\r\n36 39\r\n3 4\r\n3 7\r\n2 17\r\n8 12\r\n9 12\r\n10 12\r\n10 15\r\n6 14\r\n8 15\r\n9 15\r\n15 15\r\n100000000000000000 1000000000000000000\r\n99999999999999999 1000000000000000000\r\n", "output": "0\r\n7\r\n7\r\n39\r\n3\r\n7\r\n15\r\n11\r\n11\r\n11\r\n15\r\n7\r\n15\r\n15\r\n15\r\n576460752303423487\r\n576460752303423487\r\n"}]
false
stdio
null
true
494/B
494
B
Python 3
PRETESTS
0
46
0
9110256
s = input() t = input() near = 0 tot = 1 totsum = 1 for i in range(len(s)-len(t),-1,-1): if s[i:i+len(t)] == t: near = totsum tot += near totsum += tot print(tot-1)
51
264
4,198,400
231039994
s, t = input(), input() n, m = len(t), len(s) + 1 d = 1000000007 g = [1] * m f = k = 0 for i in range(1, m) : if s[i - n:i] == t : k = i if k : f = (f + g[k - n]) % d g[i] += (g[i - 1] + f) % d print(f)
Codeforces Round 282 (Div. 1)
CF
2,014
2
256
Obsessive String
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a1, a2, ..., ak and b1, b2, ..., bk satisfying the following requirements: - k ≥ 1 - $$$$ - $$\forall i \left( 1 \leq i \leq k \right) b_i \geq a_i$$ - $$\forall i \left( 2 \leq i \leq k \right) a_i > b_{i-1}$$ - $$\forall i \left( 1 \leq i \leq k \right)$$  t is a substring of string saisai + 1... sbi (string s is considered as 1-indexed). As the number of ways can be rather large print it modulo 109 + 7.
Input consists of two lines containing strings s and t (1 ≤ |s|, |t| ≤ 105). Each string consists of lowercase Latin letters.
Print the answer in a single line.
null
null
[{"input": "ababa\naba", "output": "5"}, {"input": "welcometoroundtwohundredandeightytwo\nd", "output": "274201"}, {"input": "ddd\nd", "output": "12"}]
2,000
["dp", "strings"]
51
[{"input": "ababa\r\naba\r\n", "output": "5\r\n"}, {"input": "welcometoroundtwohundredandeightytwo\r\nd\r\n", "output": "274201\r\n"}, {"input": "ddd\r\nd\r\n", "output": "12\r\n"}, {"input": "vnssnssnssnssnssnssnssnssnssnssnssnssnssnssnssnssn\r\nnssnssns\r\n", "output": "943392\r\n"}, {"input": "kpjmawawawawawawawawawawawawawawawawawawawawawawaw\r\nwawawawa\r\n", "output": "834052\r\n"}, {"input": "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\r\nvvvvvvvv\r\n", "output": "2728075\r\n"}, {"input": "a\r\na\r\n", "output": "1\r\n"}, {"input": "a\r\naa\r\n", "output": "0\r\n"}, {"input": "a\r\nb\r\n", "output": "0\r\n"}, {"input": "ababababab\r\nabab\r\n", "output": "35\r\n"}]
false
stdio
null
true
19/A
19
A
Python 3
TESTS
3
92
0
202982061
def main(): n = int(input()) teams = [] team_id = {} for i in range(n): team_name = input() teams.append([team_name, 0, 0, 0]) team_id[team_name] = i for i in range(n * (n - 1) // 2): team, scores = input().split() team1, team2 = team.split('-') score1, score2 = map(int, scores.split(':')) if score1 > score2: teams[team_id[team1]][1] += 3 elif score1 < score2: teams[team_id[team2]][1] += 3 else: teams[team_id[team1]][1] += 1 teams[team_id[team2]][1] += 1 teams[team_id[team1]][2] += score1 - score2 teams[team_id[team1]][2] += score2 - score1 teams[team_id[team1]][3] += score1 teams[team_id[team1]][3] += score2 teams.sort(key=lambda x: (x[1], x[2], x[3]), reverse=True) teams = teams[:n // 2] teams.sort(key=lambda x: x[0]) for team in teams: print(team[0]) if __name__ == "__main__": main()
29
92
0
5353782
p, n = {}, int(input()) for i in range(n): p[input()] = [0, 0, 0] for i in range((n * (n - 1)) // 2): t = input().split() a, b = t[0].split('-') x, y = t[1].split(':') x, y = int(x), int(y) if x > y: p[a][0] += 3 elif x < y: p[b][0] += 3 else: p[a][0] += 1 p[b][0] += 1 p[a][1] += y p[b][1] += x p[a][2] += x p[b][2] += y for c in p: p[c][1] = p[c][2] - p[c][1] r = sorted(p.items(), reverse = True, key = lambda x: x[1]) print('\n'.join(sorted(r[i][0] for i in range(n // 2))))
Codeforces Beta Round 19
ICPC
2,010
2
64
World Football Cup
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: - the final tournament features n teams (n is always even) - the first n / 2 teams (according to the standings) come through to the knockout stage - the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals - it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
The first input line contains the only integer n (1 ≤ n ≤ 50) — amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following n·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 — names of the teams; num1, num2 (0 ≤ num1, num2 ≤ 100) — amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
Output n / 2 lines — names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
null
null
[{"input": "4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3", "output": "A\nD"}, {"input": "2\na\nA\na-A 2:1", "output": "a"}]
1,400
["implementation"]
29
[{"input": "4\r\nA\r\nB\r\nC\r\nD\r\nA-B 1:1\r\nA-C 2:2\r\nA-D 1:0\r\nB-C 1:0\r\nB-D 0:3\r\nC-D 0:3\r\n", "output": "A\r\nD\r\n"}, {"input": "2\r\na\r\nA\r\na-A 2:1\r\n", "output": "a\r\n"}, {"input": "2\r\nEULEUbCmfrmqxtzvg\r\nuHGRmKUhDcxcfqyruwzen\r\nuHGRmKUhDcxcfqyruwzen-EULEUbCmfrmqxtzvg 13:92\r\n", "output": "EULEUbCmfrmqxtzvg\r\n"}, {"input": "6\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nA-B 1:0\r\nA-C 0:0\r\nA-D 1:0\r\nA-E 5:5\r\nA-F 0:1\r\nB-C 1:0\r\nB-D 1:0\r\nB-E 1:0\r\nB-F 0:2\r\nC-D 2:2\r\nC-E 1:0\r\nC-F 1:0\r\nD-E 1:0\r\nD-F 1:0\r\nE-F 0:1\r\n", "output": "A\r\nB\r\nF\r\n"}, {"input": "6\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nA-B 1:0\r\nA-C 0:0\r\nA-D 1:0\r\nA-E 5:5\r\nA-F 0:1\r\nB-C 1:0\r\nB-D 1:0\r\nB-E 1:0\r\nB-F 0:2\r\nC-D 7:7\r\nC-E 1:0\r\nC-F 1:0\r\nD-E 1:0\r\nD-F 1:0\r\nE-F 0:1\r\n", "output": "B\r\nC\r\nF\r\n"}]
false
stdio
null
true
31/D
31
D
PyPy 3
TESTS
3
186
0
112162597
w,h,n=list(map(int,input().split())) a=[[0 for i in range(2*w-1)] for j in range(2*h-1)] for i in range(1,2*h-1,2): for j in range(1,2*w-1,2): a[i][j]=' ' for i in range(n): x1,y1,x2,y2=list(map(int,input().split())) if x1==x2: if x1!=0 and x1!=w: for j in range(max(1,min(y1,y2)),max(y1,y2)+1): a[2*h-2-2*(j-1)][2*x1-1]=' ' else: if y1!=0 and y1!=h: for j in range(min(x1,x2),max(x1,x2)): a[2*h-1-2*y1][2*j]=' ' b=[] c=1 for i in range(0,2*h-1,2): for j in range(0,2*w-1,2): if a[i][j]==0: d=i e=j while d<2*h-1 and a[d][e]==0 and a[d-1][e]!=' ' or d==i: d+=2 d-=2 while e<2*w-1 and a[d][e]==0 and a[d][e-1]!=' ' or e==j: e+=2 e-=2 b.append(((e-j)//2+1)*((d-i)//2+1)) for k in range(i,d+1,2): for l in range(j,e+1,2): a[k][l]=c c+=1 b+=[0]*(n+1-len(b)) print(*sorted(b))
33
278
4,505,600
146016755
from collections import deque import sys input = sys.stdin.readline def bfs(x, y): q = deque() q.append((x, y)) visit[x][y] = 1 c = 0 while q: i, j = q.popleft() c += 1 for di, dj in G[i][j]: ni, nj = i + di, j + dj if 0 <= ni < w and 0 <= nj < h: if not visit[ni][nj]: q.append((ni, nj)) visit[ni][nj] = 1 return c w, h, n = map(int, input().split()) v = [(1, 0), (-1, 0), (0, 1), (0, -1)] G = [[set(v) for _ in range(h)] for _ in range(w)] for _ in range(n): x1, y1, x2, y2 = map(int, input().split()) if x1 == x2: for y in range(y1, y2): G[x1 - 1][y].remove((1, 0)) for y in range(y1, y2): G[x1][y].remove((-1, 0)) else: for x in range(x1, x2): G[x][y1 - 1].remove((0, 1)) for x in range(x1, x2): G[x][y1].remove((0, -1)) visit = [[0] * h for _ in range(w)] ans = [] for x in range(w): for y in range(h): if not visit[x][y]: c = bfs(x, y) ans.append(c) ans.sort() sys.stdout.write(" ".join(map(str, ans)))
Codeforces Beta Round 31 (Div. 2, Codeforces format)
CF
2,010
2
256
Chocolate
Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.
The first line contains 3 integers W, H and n (1 ≤ W, H, n ≤ 100) — width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 — coordinates of the endpoints of the i-th break (0 ≤ xi, 1 ≤ xi, 2 ≤ W, 0 ≤ yi, 1 ≤ yi, 2 ≤ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order. It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.
Output n + 1 numbers — areas of the resulting parts in the increasing order.
null
null
[{"input": "2 2 2\n1 0 1 2\n0 1 1 1", "output": "1 1 2"}, {"input": "2 2 3\n1 0 1 2\n0 1 1 1\n1 1 2 1", "output": "1 1 1 1"}, {"input": "2 4 2\n0 1 2 1\n0 3 2 3", "output": "2 2 4"}]
2,000
["dfs and similar", "implementation"]
33
[{"input": "2 2 2\r\n1 0 1 2\r\n0 1 1 1\r\n", "output": "1 1 2 "}, {"input": "2 2 3\r\n1 0 1 2\r\n0 1 1 1\r\n1 1 2 1\r\n", "output": "1 1 1 1 "}, {"input": "2 4 2\r\n0 1 2 1\r\n0 3 2 3\r\n", "output": "2 2 4 "}, {"input": "5 5 3\r\n2 1 2 5\r\n0 1 5 1\r\n4 0 4 1\r\n", "output": "1 4 8 12 "}, {"input": "10 10 4\r\n9 0 9 10\r\n4 0 4 10\r\n1 0 1 10\r\n1 4 4 4\r\n", "output": "10 10 12 18 50 "}, {"input": "9 8 5\r\n4 3 4 4\r\n0 4 9 4\r\n5 4 5 8\r\n0 3 9 3\r\n1 4 1 8\r\n", "output": "4 4 5 16 16 27 "}, {"input": "100 100 1\r\n0 14 100 14\r\n", "output": "1400 8600 "}]
false
stdio
null
true
31/D
31
D
Python 3
TESTS
3
62
0
188997254
w,h,n=map(int,input().split()) c=[[0,0,w,h]] s=[min((a,b),(c,d)) for a,b,c,d in [[*map(int,input().split())] for i in range(n)]] for x,y in s: for i,j in enumerate(c): if x>j[0]and x<j[2]+j[0]and y==j[1]: c.append([x,y,j[2]-x+j[0],j[3]]) c[i][2]=x-j[0] break if y>j[1]and y<j[3]+j[1]and x==j[0]: c.append([x,y,j[2],j[3]-y+j[1]]) c[i][3]=y-j[1] break c=[i[2]*i[3] for i in c] c.sort() print(*c)
33
374
2,252,800
73472707
w, h, n = map(int, input().split(' ')) hblock = [[False for i in range(w)] for i in range(h)] vblock = [[False for i in range(w)] for i in range(h)] for i in range(n): x1, y1, x2, y2 = map(int, input().split(' ')) if x1 == x2: for j in range(y1, y2): hblock[j][x1-1] = True else: for j in range(x1, x2): vblock[y1-1][j] = True areas = [] vis = [[False for i in range(w)] for i in range(h)] for i in range(h): for j in range(w): if vis[i][j]: continue width = j while width < w and not hblock[i][width]: width += 1 height = i while height < h and not vblock[height][j]: height += 1 width = min(w - 1, width) - j + 1 height = min(h - 1, height) - i + 1 areas.append(width * height) for p in range(height): for q in range(width): vis[i + p][j + q] = True areas.sort() print(' '.join(map(str, areas)))
Codeforces Beta Round 31 (Div. 2, Codeforces format)
CF
2,010
2
256
Chocolate
Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.
The first line contains 3 integers W, H and n (1 ≤ W, H, n ≤ 100) — width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 — coordinates of the endpoints of the i-th break (0 ≤ xi, 1 ≤ xi, 2 ≤ W, 0 ≤ yi, 1 ≤ yi, 2 ≤ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order. It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.
Output n + 1 numbers — areas of the resulting parts in the increasing order.
null
null
[{"input": "2 2 2\n1 0 1 2\n0 1 1 1", "output": "1 1 2"}, {"input": "2 2 3\n1 0 1 2\n0 1 1 1\n1 1 2 1", "output": "1 1 1 1"}, {"input": "2 4 2\n0 1 2 1\n0 3 2 3", "output": "2 2 4"}]
2,000
["dfs and similar", "implementation"]
33
[{"input": "2 2 2\r\n1 0 1 2\r\n0 1 1 1\r\n", "output": "1 1 2 "}, {"input": "2 2 3\r\n1 0 1 2\r\n0 1 1 1\r\n1 1 2 1\r\n", "output": "1 1 1 1 "}, {"input": "2 4 2\r\n0 1 2 1\r\n0 3 2 3\r\n", "output": "2 2 4 "}, {"input": "5 5 3\r\n2 1 2 5\r\n0 1 5 1\r\n4 0 4 1\r\n", "output": "1 4 8 12 "}, {"input": "10 10 4\r\n9 0 9 10\r\n4 0 4 10\r\n1 0 1 10\r\n1 4 4 4\r\n", "output": "10 10 12 18 50 "}, {"input": "9 8 5\r\n4 3 4 4\r\n0 4 9 4\r\n5 4 5 8\r\n0 3 9 3\r\n1 4 1 8\r\n", "output": "4 4 5 16 16 27 "}, {"input": "100 100 1\r\n0 14 100 14\r\n", "output": "1400 8600 "}]
false
stdio
null
true
31/D
31
D
PyPy 3-64
TESTS
3
92
0
214286950
import sys readline = sys.stdin.readline w, h, n = [int(w) for w in readline().split()] rects = [[0, 0, w, h ]] for _ in range(n): x1, y1, x2, y2 = [int(w) for w in readline().split()] if x2 < x1: x1, x2 = x2, x1 if y2 < y1: y1, y2 = y2, y1 for i, (xi1, yi1, xi2, yi2) in enumerate(rects): if xi1 <= x1 <= x2 <= xi2 and yi1 <= y1 <= y2 <= yi2: if x1 == x2: # split vertically rects[i] = [xi1, yi1, x1, y2] rects.append([x1, y1, xi2, yi2]) break if y1 == y2: rects[i] = [xi1, yi1, xi2, y1] rects.append([xi1, y1, xi2, yi2]) break result = [(x2 - x1) * (y2 - y1) for x1,y1,x2,y2 in rects] result.sort() print(*result)
33
374
3,481,600
95345054
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') w, h, n = map(int, input().split()) mat = [[0] * (2 * w) for _ in range(2 * h)] for x1, y1, x2, y2 in (map(int, input().split()) for _ in range(n)): if x1 == x2: for y in range(2 * y1, 2 * y2): mat[y][2 * x1 - 1] = 1 else: for x in range(2 * x1, 2 * x2): mat[2 * y1 - 1][x] = 1 ans = [] for i in range(0, 2 * h, 2): for j in range(0, 2 * w, 2): if mat[i][j]: continue mat[i][j] = 1 size = 1 stack = [(i, j)] while stack: y, x = stack.pop() for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)): if 0 <= y + dy * 2 < 2 * h and 0 <= x + dx * 2 < 2 * w and mat[y + dy][x + dx] == 0 and mat[y + dy * 2][x + dx * 2] == 0: mat[y + dy * 2][x + dx * 2] = 1 size += 1 stack.append((y + dy * 2, x + dx * 2)) ans.append(size) print(*sorted(ans))
Codeforces Beta Round 31 (Div. 2, Codeforces format)
CF
2,010
2
256
Chocolate
Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.
The first line contains 3 integers W, H and n (1 ≤ W, H, n ≤ 100) — width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 — coordinates of the endpoints of the i-th break (0 ≤ xi, 1 ≤ xi, 2 ≤ W, 0 ≤ yi, 1 ≤ yi, 2 ≤ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order. It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.
Output n + 1 numbers — areas of the resulting parts in the increasing order.
null
null
[{"input": "2 2 2\n1 0 1 2\n0 1 1 1", "output": "1 1 2"}, {"input": "2 2 3\n1 0 1 2\n0 1 1 1\n1 1 2 1", "output": "1 1 1 1"}, {"input": "2 4 2\n0 1 2 1\n0 3 2 3", "output": "2 2 4"}]
2,000
["dfs and similar", "implementation"]
33
[{"input": "2 2 2\r\n1 0 1 2\r\n0 1 1 1\r\n", "output": "1 1 2 "}, {"input": "2 2 3\r\n1 0 1 2\r\n0 1 1 1\r\n1 1 2 1\r\n", "output": "1 1 1 1 "}, {"input": "2 4 2\r\n0 1 2 1\r\n0 3 2 3\r\n", "output": "2 2 4 "}, {"input": "5 5 3\r\n2 1 2 5\r\n0 1 5 1\r\n4 0 4 1\r\n", "output": "1 4 8 12 "}, {"input": "10 10 4\r\n9 0 9 10\r\n4 0 4 10\r\n1 0 1 10\r\n1 4 4 4\r\n", "output": "10 10 12 18 50 "}, {"input": "9 8 5\r\n4 3 4 4\r\n0 4 9 4\r\n5 4 5 8\r\n0 3 9 3\r\n1 4 1 8\r\n", "output": "4 4 5 16 16 27 "}, {"input": "100 100 1\r\n0 14 100 14\r\n", "output": "1400 8600 "}]
false
stdio
null
true
729/D
729
D
Python 3
PRETESTS
2
61
307,200
22355751
n, a, b, k = map(int, input().split()) pole = input() pole3 = [[pole[0]]] result = 0 for i in range(1, n): if pole[i] == pole[i-1]: pole3[-1].append(pole[i]) else: pole3.append([pole[i]]) for i in range(len(pole3)): if pole3[i][0] == '0': if len(pole3[i]) >= b: k = 1 while b * k - 1 < len(pole3[i]): pole3[i][b * k - 1] = 'X' k += 1 result += 1 itog = result + 1 - a print(itog) for i in range(len(pole3)): if pole3[i][0] == '0': for j in range(len(pole3[i])): if pole3[i][j] == 'X': if itog == 0: break itog -= 1 pole3[i][j] = 'Y' pole4 = [] listres = [] for i in range(len(pole3)): pole4 += pole3[i] for i in range(n): if pole4[i] == 'Y': listres.append(i+1) print(*listres)
21
93
17,100,800
172144469
def _n(): return int(input()) def _nA(): return list(map(int, input().split())) def _sA(): return input().split() n, a, b, k = _nA() s = input() i = 0 ret = [] while i < n: if s[i] == '1': i += 1 continue j = i while i < n and s[i] == '0': i += 1 for k in range(j+b-1, i, b): ret.append(k+1) ret=ret[a-1:] print(len(ret)) print(*ret)
Technocup 2017 - Elimination Round 2
CF
2,016
1
256
Sea Battle
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss"). Galya has already made k shots, all of them were misses. Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. It is guaranteed that there is at least one valid ships placement.
The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.
In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.
null
There is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
[{"input": "5 1 2 1\n00100", "output": "2\n4 2"}, {"input": "13 3 2 3\n1000000010001", "output": "2\n7 11"}]
1,700
["constructive algorithms", "greedy", "math"]
21
[{"input": "5 1 2 1\r\n00100\r\n", "output": "2\r\n2 5 \r\n"}, {"input": "13 3 2 3\r\n1000000010001\r\n", "output": "2\r\n3 5 \r\n"}, {"input": "1 1 1 0\r\n0\r\n", "output": "1\r\n1 \r\n"}, {"input": "2 2 1 0\r\n00\r\n", "output": "1\r\n1 \r\n"}, {"input": "5 4 1 0\r\n00000\r\n", "output": "2\r\n1 2 \r\n"}, {"input": "10 2 2 0\r\n0000000000\r\n", "output": "4\r\n2 4 6 8 \r\n"}, {"input": "20 1 3 5\r\n01001010000000010010\r\n", "output": "2\r\n10 13 \r\n"}, {"input": "100 17 4 11\r\n0100000100000000000000001000000000010001100000000000101000000000000000000000001000001000010000000000\r\n", "output": "2\r\n6 12 \r\n"}]
false
stdio
null
true
48/C
48
C
PyPy 3
TESTS
5
312
0
74679887
from math import inf,ceil n = int(input()) a = list(map(int,input().split())) lower_bound = 0 upper_bound = inf station = 1 total_stops = 1 for i in range(n): stop = a[i] if stop!=station: while stop!=station: station+=1 lower_bound = max(lower_bound,station*10/total_stops) upper_bound = min(upper_bound,(10+stop*10)/total_stops) station = stop total_stops+=1 station_set = set() for i in range(int(lower_bound),int(ceil(upper_bound)+1)): if i>lower_bound and i<upper_bound: fuel_last_station = total_stops*i - a[-1]*10 station_set.add(a[-1]+fuel_last_station//10) if len(station_set) > 1: print('not unique') break else: print('unique') print(max(station_set))
45
248
307,200
69074867
# ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def main(): n = int(input()) a = list(map(int ,input().split())) lb = 10 ub = 1e9 for i in range(n): lb = max(lb , 10 * a[i] / (i + 1)) ub = min(ub , 10 * (a[i] + 1)/(i + 1)) # print(lb , ub) minimumstageitcanreach = a[-1] + ((n + 1)*lb - a[-1]*10)//10 ns = minimumstageitcanreach + 1 # print(ns) minalpha = ns * 10 / (n + 1) # print(minalpha) if abs(minalpha - ub) >= 1e-6: if minalpha < ub: print("not unique") else: print("unique") print(int(minimumstageitcanreach)) else: print("unique") print(int(minimumstageitcanreach)) return if __name__ == "__main__": main()
School Personal Contest #3 (Winter Computer School 2010/11) - Codeforces Beta Round 45 (ACM-ICPC Rules)
ICPC
2,010
2
256
The Race
Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer. So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage. One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.
The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.
Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".
null
In the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.
[{"input": "3\n1 2 4", "output": "unique\n5"}, {"input": "2\n1 2", "output": "not unique"}]
1,800
["math"]
45
[{"input": "3\r\n1 2 4\r\n", "output": "unique\r\n5\r\n"}, {"input": "2\r\n1 2\r\n", "output": "not unique\r\n"}, {"input": "1\r\n5\r\n", "output": "not unique\r\n"}, {"input": "3\r\n1 3 4\r\n", "output": "unique\r\n6\r\n"}, {"input": "5\r\n1 2 3 5 6\r\n", "output": "unique\r\n7\r\n"}, {"input": "6\r\n1 2 3 5 6 7\r\n", "output": "not unique\r\n"}, {"input": "10\r\n1 2 4 5 7 8 9 11 12 14\r\n", "output": "unique\r\n15\r\n"}, {"input": "10\r\n1 3 5 6 8 10 12 13 15 17\r\n", "output": "not unique\r\n"}, {"input": "9\r\n2 5 7 10 12 15 17 20 22\r\n", "output": "unique\r\n25\r\n"}, {"input": "10\r\n7 14 21 28 35 42 49 56 63 70\r\n", "output": "not unique\r\n"}, {"input": "15\r\n5 11 16 22 28 33 39 45 50 56 62 67 73 79 84\r\n", "output": "unique\r\n90\r\n"}, {"input": "17\r\n5 11 16 22 28 33 39 45 50 56 62 67 73 79 84 90 96\r\n", "output": "unique\r\n101\r\n"}, {"input": "15\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24\r\n", "output": "unique\r\n25\r\n"}, {"input": "16\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25\r\n", "output": "unique\r\n27\r\n"}, {"input": "17\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27\r\n", "output": "unique\r\n29\r\n"}, {"input": "18\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27 29\r\n", "output": "unique\r\n30\r\n"}, {"input": "19\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27 29 30\r\n", "output": "unique\r\n32\r\n"}, {"input": "20\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27 29 30 32\r\n", "output": "not unique\r\n"}, {"input": "18\r\n49999 99998 149998 199997 249996 299996 349995 399994 449994 499993 549992 599992 649991 699990 749990 799989 849988 899988\r\n", "output": "unique\r\n949987\r\n"}, {"input": "20\r\n49999 99998 149998 199997 249996 299996 349995 399994 449994 499993 549992 599992 649991 699990 749990 799989 849988 899988 949987 999986\r\n", "output": "unique\r\n1049986\r\n"}, {"input": "33\r\n9 19 29 39 49 59 69 79 89 99 109 119 129 139 149 159 168 178 188 198 208 218 228 238 248 258 268 278 288 298 308 318 327\r\n", "output": "unique\r\n337\r\n"}, {"input": "46\r\n40 81 122 162 203 244 284 325 366 406 447 488 528 569 610 650 691 732 772 813 854 894 935 976 1016 1057 1098 1138 1179 1220 1260 1301 1342 1382 1423 1464 1504 1545 1586 1626 1667 1708 1748 1789 1830 1870\r\n", "output": "unique\r\n1911\r\n"}]
false
stdio
null
true
48/C
48
C
PyPy 3
TESTS
2
310
0
74338732
from collections import defaultdict import math n=int(input()) a=list(map(int,input().split())) node=[a[0],1,0]# 10a+bx-10c toadd=a[0] xrange=[0,10]# a<=x<b # print(node,xrange) a=[0]+a for i in range(1,n+1): #after fuling at station i+1 if(node[0]>=a[i]-a[i-1]): node[0]-=a[i]-a[i-1] else: node[2]=a[i]-a[i-1]-node[0] node[0]=0 if(node[2]==0): node[0]+=toadd xrange[1]=10/node[1] else: xrange[0]=(node[2]*10)/node[1] node[0]=toadd-node[2] node[2]=0 node[1]+=1 # temp=node[1]-1 # xrange[1]=10/temp # xrange[0]=10/node[1] # node contains fuel after filling at last station if((xrange[0]*node[1])//10==(xrange[1]*node[1])//10): print("unique") print(a[n]+(xrange[0]*node[1])//10) else: if((xrange[1]*node[1])%10==0): print("unique") print(int(a[n]+(xrange[0]*node[1])//10)) else: print("not unique")
45
280
0
63625034
eps=10**(-9) mn=10 mx=100000000 n=int(input()) arr=list(map(int,input().split())) for i in range(n): mn = max(mn,(arr[i]*10)/(i+1)) mx = min(mx,((arr[i]+1)*10)/(i+1)) ans1=((n+1)*mn)//10 ans2=((n+1)*(mx-eps))//10 if ans2>ans1: print('not unique') else: print('unique') print(int(ans1))
School Personal Contest #3 (Winter Computer School 2010/11) - Codeforces Beta Round 45 (ACM-ICPC Rules)
ICPC
2,010
2
256
The Race
Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer. So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage. One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.
The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.
Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".
null
In the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.
[{"input": "3\n1 2 4", "output": "unique\n5"}, {"input": "2\n1 2", "output": "not unique"}]
1,800
["math"]
45
[{"input": "3\r\n1 2 4\r\n", "output": "unique\r\n5\r\n"}, {"input": "2\r\n1 2\r\n", "output": "not unique\r\n"}, {"input": "1\r\n5\r\n", "output": "not unique\r\n"}, {"input": "3\r\n1 3 4\r\n", "output": "unique\r\n6\r\n"}, {"input": "5\r\n1 2 3 5 6\r\n", "output": "unique\r\n7\r\n"}, {"input": "6\r\n1 2 3 5 6 7\r\n", "output": "not unique\r\n"}, {"input": "10\r\n1 2 4 5 7 8 9 11 12 14\r\n", "output": "unique\r\n15\r\n"}, {"input": "10\r\n1 3 5 6 8 10 12 13 15 17\r\n", "output": "not unique\r\n"}, {"input": "9\r\n2 5 7 10 12 15 17 20 22\r\n", "output": "unique\r\n25\r\n"}, {"input": "10\r\n7 14 21 28 35 42 49 56 63 70\r\n", "output": "not unique\r\n"}, {"input": "15\r\n5 11 16 22 28 33 39 45 50 56 62 67 73 79 84\r\n", "output": "unique\r\n90\r\n"}, {"input": "17\r\n5 11 16 22 28 33 39 45 50 56 62 67 73 79 84 90 96\r\n", "output": "unique\r\n101\r\n"}, {"input": "15\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24\r\n", "output": "unique\r\n25\r\n"}, {"input": "16\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25\r\n", "output": "unique\r\n27\r\n"}, {"input": "17\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27\r\n", "output": "unique\r\n29\r\n"}, {"input": "18\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27 29\r\n", "output": "unique\r\n30\r\n"}, {"input": "19\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27 29 30\r\n", "output": "unique\r\n32\r\n"}, {"input": "20\r\n1 3 4 6 8 9 11 12 14 16 17 19 21 22 24 25 27 29 30 32\r\n", "output": "not unique\r\n"}, {"input": "18\r\n49999 99998 149998 199997 249996 299996 349995 399994 449994 499993 549992 599992 649991 699990 749990 799989 849988 899988\r\n", "output": "unique\r\n949987\r\n"}, {"input": "20\r\n49999 99998 149998 199997 249996 299996 349995 399994 449994 499993 549992 599992 649991 699990 749990 799989 849988 899988 949987 999986\r\n", "output": "unique\r\n1049986\r\n"}, {"input": "33\r\n9 19 29 39 49 59 69 79 89 99 109 119 129 139 149 159 168 178 188 198 208 218 228 238 248 258 268 278 288 298 308 318 327\r\n", "output": "unique\r\n337\r\n"}, {"input": "46\r\n40 81 122 162 203 244 284 325 366 406 447 488 528 569 610 650 691 732 772 813 854 894 935 976 1016 1057 1098 1138 1179 1220 1260 1301 1342 1382 1423 1464 1504 1545 1586 1626 1667 1708 1748 1789 1830 1870\r\n", "output": "unique\r\n1911\r\n"}]
false
stdio
null
true
31/D
31
D
Python 3
TESTS
1
92
0
189595565
from bisect import insort as it w,h,n=map(int,input().split()) x=[[0,h]]+[[] for _ in range(99)] y=[[0,w]]+[[] for _ in range(99)] xy=[[0]*100 for _ in range(100)] xy[0][0]=1 xs,ys={0},{0} for a,b,c,d in [[*map(int,input().split())] for i in range(n)]: m=min((a,b),(c,d)) xy[m[0]][m[1]]=1 xs.add(m[0]) ys.add(m[1]) if a==c: it(x[a],b) it(x[a],d) it(y[m[1]],m[0]) if b==d: it(y[b],a) it(y[b],c) it(x[m[0]],m[1]) f=[] for i in xs: for j in range(len(x[i])): if xy[i][x[i][j]]: xy[i][x[i][j]]*=x[i][j+1]-x[i][j] for i in ys: for j in range(len(y[i])): if xy[y[i][j]][i]: it(f,xy[y[i][j]][i]*(y[i][j+1]-y[i][j])) print(*f)
33
92
0
189949532
from bisect import bisect as bt w,h,n=map(int,input().split()) N,M=max(w,h),10 x=[[0,h]]+[[] for _ in range(N-1)] y=[[0,w]]+[[] for _ in range(N-1)] xy=[[0]*(N+1) for _ in range(N+1)] g=[0]*M+[[]] xy[0][0]=1 xs,ys={0},{0} def t(k,p): for i,j in zip(k,p): q=bt(i,j) if q==0 or i[q-1]!=j: i[q:q]=[j] for a,b,c,d in [[*map(int,input().split())] for i in range(n)]: m=min((a,b),(c,d)) xy[m[0]][m[1]]=1 xs.add(m[0]) ys.add(m[1]) if a==c: t([x[a],x[a],y[m[1]]],[b,d,m[0]]) if b==d: t([y[b],y[b],x[m[0]]],[a,c,m[1]]) for i in xs: for j in range(len(x[i])): if xy[i][x[i][j]]: xy[i][x[i][j]]*=x[i][j+1]-x[i][j] for i in ys: for j in range(len(y[i])): if xy[y[i][j]][i]: p=xy[y[i][j]][i]*(y[i][j+1]-y[i][j]) if p<len(g)-1:g[p]+=1 else:g[-1].append(p) s=[] for i,j in enumerate(g[:-1]): s.extend([str(i)]*j) g[-1].sort() s.extend([str(i) for i in g[-1]]) print(' '.join(s))
Codeforces Beta Round 31 (Div. 2, Codeforces format)
CF
2,010
2
256
Chocolate
Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.
The first line contains 3 integers W, H and n (1 ≤ W, H, n ≤ 100) — width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 — coordinates of the endpoints of the i-th break (0 ≤ xi, 1 ≤ xi, 2 ≤ W, 0 ≤ yi, 1 ≤ yi, 2 ≤ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order. It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.
Output n + 1 numbers — areas of the resulting parts in the increasing order.
null
null
[{"input": "2 2 2\n1 0 1 2\n0 1 1 1", "output": "1 1 2"}, {"input": "2 2 3\n1 0 1 2\n0 1 1 1\n1 1 2 1", "output": "1 1 1 1"}, {"input": "2 4 2\n0 1 2 1\n0 3 2 3", "output": "2 2 4"}]
2,000
["dfs and similar", "implementation"]
33
[{"input": "2 2 2\r\n1 0 1 2\r\n0 1 1 1\r\n", "output": "1 1 2 "}, {"input": "2 2 3\r\n1 0 1 2\r\n0 1 1 1\r\n1 1 2 1\r\n", "output": "1 1 1 1 "}, {"input": "2 4 2\r\n0 1 2 1\r\n0 3 2 3\r\n", "output": "2 2 4 "}, {"input": "5 5 3\r\n2 1 2 5\r\n0 1 5 1\r\n4 0 4 1\r\n", "output": "1 4 8 12 "}, {"input": "10 10 4\r\n9 0 9 10\r\n4 0 4 10\r\n1 0 1 10\r\n1 4 4 4\r\n", "output": "10 10 12 18 50 "}, {"input": "9 8 5\r\n4 3 4 4\r\n0 4 9 4\r\n5 4 5 8\r\n0 3 9 3\r\n1 4 1 8\r\n", "output": "4 4 5 16 16 27 "}, {"input": "100 100 1\r\n0 14 100 14\r\n", "output": "1400 8600 "}]
false
stdio
null
true
754/C
754
C
PyPy 3
TESTS
3
109
23,244,800
24466533
from sys import stdin, stdout n = int(stdin.readline()) for i in range(n): text = [] number = int(stdin.readline()) names = list(stdin.readline().strip().split()) label = 1 k = int(stdin.readline()) challengers = [] used = [[] for i in range(k)] for i in range(k): s = stdin.readline().strip().split(':') text.append(s[1]) challengers.append(s[0]) for f in names: if f in s[1]: used[i].append(f) for i in range(k): if i and i < k - 1: used[i].append(challengers[i - 1]) used[i].append(challengers[i + 1]) elif not i: used[i].append(challengers[i + 1]) else: used[i].append(challengers[i - 1]) label = 1 while label: label = 0 for i in range(k): tr = [] for f in names: if not f in used[i]: tr.append(f) if len(tr) == 1 and challengers[i] == '?': challengers[i] = tr[0] label = 1 if i and i < k - 1: used[i - 1].append(tr[0]) used[i + 1].append(tr[0]) elif not i: used[i + 1].append(tr[0]) else: used[i - 1].append(tr[0]) elif not len(tr) and challengers[i] == '?': challengers[i] = 'Impossible' if challengers.count('Impossible'): stdout.write('Impossible\n') else: for i in range(len(text)): stdout.write(challengers[i] + ':' + text[i] + '\n')
104
327
6,246,400
23603581
from math import * from sys import * from decimal import * def gcd(a,b): if b: return gcd(b,a%b) return a t=int(stdin.readline()) for sssss in range(t): n=int(stdin.readline()) names=stdin.readline().split() dn=dict() for i in range(len(names)): dn[names[i]]=i text=[] ps=[] m=int(stdin.readline()) for i in range(m): nxt=stdin.readline() getname=nxt.split(":")[0] nxt=nxt.split(":")[1] text.append(nxt) if getname=="?": pos=set([z for z in range(n)]) hell="" shit=set([".",",","!","?"]) for y in nxt: if y in shit: hell+=" " else: hell+=y nhere=hell.split() for j in nhere: pos.discard(dn.get(j)) if i and len(ps[-1])==1: for dd in ps[-1]: pos.discard(dd) ps.append(pos) else: if i: ps[-1].discard(dn[getname]) ps.append(set([dn[getname]])) #print(ps) dp=[[False]*n] for i in ps[0]: dp[0][i]=True for i in range(1,m): #print(dp) dp.append([False]*n) for j in ps[i]: for k in range(n): if k!=j and dp[-2][k]==True: dp[-1][j]=True break if True not in dp[-1]: stdout.write("Impossible\n") continue #print(dp) yy=[0]*m ban=-1 for i in range(m-1,-1,-1): for j in range(n): if j!=ban and dp[i][j]: ban=j yy[i]=j break #print(yy,names) for i in range(m): stdout.write(names[yy[i]]+":"+text[i])
Codeforces Round 390 (Div. 2)
CF
2,017
2
256
Vladik and chat
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them. At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages. Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages. He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format. The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat. The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters. The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line: - <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat. - <?>:<text> — the format of a message with unknown sender. The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters. We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha". It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
Print the information about the t chats in the following format: If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format: <username>:<text> If there are multiple answers, print any of them.
null
null
[{"input": "1\n2\nVladik netman\n2\n?: Hello, Vladik!\n?: Hi", "output": "netman: Hello, Vladik!\nVladik: Hi"}, {"input": "1\n2\nnetman vladik\n3\nnetman:how are you?\n?:wrong message\nvladik:im fine", "output": "Impossible"}, {"input": "2\n3\nnetman vladik Fedosik\n2\n?: users are netman, vladik, Fedosik\nvladik: something wrong with this chat\n4\nnetman tigerrrrr banany2001 klinchuh\n4\n?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\n?: yes, netman\nbanany2001: yes of course.", "output": "Impossible\nnetman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\ntigerrrrr: yes, netman\nbanany2001: yes of course."}]
2,200
["brute force", "constructive algorithms", "dp", "implementation", "strings"]
104
[{"input": "1\r\n2\r\nVladik netman\r\n2\r\n?: Hello, Vladik!\r\n?: Hi\r\n", "output": "netman: Hello, Vladik!\r\nVladik: Hi\r\n"}, {"input": "1\r\n2\r\nnetman vladik\r\n3\r\nnetman:how are you?\r\n?:wrong message\r\nvladik:im fine\r\n", "output": "Impossible\r\n"}, {"input": "2\r\n3\r\nnetman vladik Fedosik\r\n2\r\n?: users are netman, vladik, Fedosik\r\nvladik: something wrong with this chat\r\n4\r\nnetman tigerrrrr banany2001 klinchuh\r\n4\r\n?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\r\nklinchuh: yes, coach!\r\n?: yes, netman\r\nbanany2001: yes of course.\r\n", "output": "Impossible\r\nnetman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\r\nklinchuh: yes, coach!\r\ntigerrrrr: yes, netman\r\nbanany2001: yes of course.\r\n"}, {"input": "1\r\n1\r\nb\r\n1\r\nb:lala!\r\n", "output": "b:lala!\r\n"}, {"input": "1\r\n1\r\nb\r\n1\r\n?:lala b!\r\n", "output": "Impossible\r\n"}, {"input": "1\r\n1\r\nb\r\n2\r\n?:lala hhe!\r\nb:wat?\r\n", "output": "Impossible\r\n"}, {"input": "1\r\n3\r\nA B C\r\n3\r\nA: HI\r\n?: HI\r\nB: HI\r\n", "output": "A: HI\r\nC: HI\r\nB: HI\r\n"}]
false
stdio
null
true
285/C
285
C
PyPy 3
TESTS
8
358
21,811,200
63876432
n=int(input()) l=list(map(int,input().split())) l.sort() moves=0 for i in range(n): if l[i]<0: moves+=-(l[i]) l[i]=0 elif l[i]>n: moves+=l[i]-n l[i]=n for i in range(n): moves+=i+1-l[i] print(moves)
33
171
27,545,600
205544002
def Building_Permutation(): n = int(input()) sequence = [int(x) for x in input().split(' ')] sequence_sorted = sorted(sequence) #in ideal case this should be 1,2,3,4,5,....,n #the minimum number of steps required would be when sequence_sorted[i] is made integer i, closest distance actual_seq = [x for x in range(1,n+1)] dist = 0 for index in range(len(sequence_sorted)): dist += abs(sequence_sorted[index] - actual_seq[index]) print(dist) return Building_Permutation()
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
285/C
285
C
Python 3
TESTS
8
436
20,992,000
16645858
n = int(input()) a = list(map(int, input().split())) r = 0 for i in range(n): if a[i] > n: r += a[i]-n a[i] = n print(n*(n+1)//2-sum(a)+r)
33
186
32,358,400
163661338
n=int(input()) lst=[int(x) for x in input().split()] lst.sort() pos,ans=1,0 for i in lst: ans+=abs(pos-i) pos+=1 print(ans)
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
754/C
754
C
PyPy 3
TESTS
11
218
27,238,400
24467144
from sys import stdin, stdout n = int(stdin.readline()) for i in range(n): text = [] number = int(stdin.readline()) names = list(stdin.readline().strip().split()) label = 1 k = int(stdin.readline()) challengers = [] used = [[] for i in range(k)] for i in range(k): s = stdin.readline().strip().split(':') text.append(s[1]) challengers.append(s[0]) l = 0 label = 0 while not label: while l < len(s[1]) and s[1][l] in ' ,?!.': l += 1 label = 1 for j in range(l, len(s[1])): if j == len(s[1]) - 1 or s[1][j + 1] in ' ,?!.': if s[1][l:j + 1] in names: used[i].append(s[1][l:j + 1]) l = j + 1 label = 0 break for i in range(k): if i and i < k - 1: used[i].append(challengers[i - 1]) used[i].append(challengers[i + 1]) elif not i: used[i].append(challengers[i + 1]) else: used[i].append(challengers[i - 1]) label = 1 while label: label = 0 for i in range(k): tr = [] for f in names: if not f in used[i]: tr.append(f) if len(tr) >= 1 and challengers[i] == '?': challengers[i] = tr[0] label = 1 if i and i < k - 1: used[i - 1].append(tr[0]) used[i + 1].append(tr[0]) elif not i: used[i + 1].append(tr[0]) else: used[i - 1].append(tr[0]) if challengers.count('?'): stdout.write('Impossible\n') else: for i in range(len(text)): stdout.write(challengers[i] + ':' + text[i] + '\n')
104
343
5,632,000
23598520
#!/usr/bin/env python3 import re def cont(line, user): return re.search('[^a-zA-Z0-9]' + user + '[^a-zA-Z0-9]', '_' + line + '_') tests = int(input()) for test in range(tests): input() users = input().rstrip('\n').split(' ') linecnt = int(input()) lines = [input().rstrip('\n') for _ in range(linecnt)] lines = [x.split(':', maxsplit=1) for x in lines] poss = [[]] * linecnt for i, (user, line) in enumerate(lines): if user != '?': poss[i] = [user] else: poss[i] = [u for u in users if not cont(line, u)] el = list(enumerate(lines)) rel = list(reversed(el)) changed = False while True: for i, (user, line) in el: if i > 0 and len(poss[i-1]) == 1: if poss[i-1][0] in poss[i]: poss[i].remove(poss[i-1][0]) changed = True for i, (user, line) in rel: if i < linecnt - 1 and len(poss[i+1]) == 1: if poss[i+1][0] in poss[i]: poss[i].remove(poss[i+1][0]) changed = True if not changed: break changed = False if all(len(p) > 0 for p in poss): for i, p, (user, line) in zip(range(linecnt), poss, lines): if i > 0: if poss[i-1][0] in p: p.remove(poss[i-1][0]) print(p[0] + ':' + line) else: print('Impossible')
Codeforces Round 390 (Div. 2)
CF
2,017
2
256
Vladik and chat
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them. At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages. Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages. He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format. The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat. The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters. The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line: - <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat. - <?>:<text> — the format of a message with unknown sender. The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question mark) and ' ' (space). The text doesn't contain trailing spaces. The length of the text is positive and doesn't exceed 100 characters. We say that a text mention a user if his username appears in the text as a word. In other words, the username appears in a such a position that the two characters before and after its appearance either do not exist or are not English letters or digits. For example, the text "Vasya, masha13 and Kate!" can mention users "Vasya", "masha13", "and" and "Kate", but not "masha". It is guaranteed that in each chat no known sender mention himself in his messages and there are no two neighboring messages with the same known sender.
Print the information about the t chats in the following format: If it is not possible to recover senders, print single line "Impossible" for this chat. Otherwise print m messages in the following format: <username>:<text> If there are multiple answers, print any of them.
null
null
[{"input": "1\n2\nVladik netman\n2\n?: Hello, Vladik!\n?: Hi", "output": "netman: Hello, Vladik!\nVladik: Hi"}, {"input": "1\n2\nnetman vladik\n3\nnetman:how are you?\n?:wrong message\nvladik:im fine", "output": "Impossible"}, {"input": "2\n3\nnetman vladik Fedosik\n2\n?: users are netman, vladik, Fedosik\nvladik: something wrong with this chat\n4\nnetman tigerrrrr banany2001 klinchuh\n4\n?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\n?: yes, netman\nbanany2001: yes of course.", "output": "Impossible\nnetman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\nklinchuh: yes, coach!\ntigerrrrr: yes, netman\nbanany2001: yes of course."}]
2,200
["brute force", "constructive algorithms", "dp", "implementation", "strings"]
104
[{"input": "1\r\n2\r\nVladik netman\r\n2\r\n?: Hello, Vladik!\r\n?: Hi\r\n", "output": "netman: Hello, Vladik!\r\nVladik: Hi\r\n"}, {"input": "1\r\n2\r\nnetman vladik\r\n3\r\nnetman:how are you?\r\n?:wrong message\r\nvladik:im fine\r\n", "output": "Impossible\r\n"}, {"input": "2\r\n3\r\nnetman vladik Fedosik\r\n2\r\n?: users are netman, vladik, Fedosik\r\nvladik: something wrong with this chat\r\n4\r\nnetman tigerrrrr banany2001 klinchuh\r\n4\r\n?: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\r\nklinchuh: yes, coach!\r\n?: yes, netman\r\nbanany2001: yes of course.\r\n", "output": "Impossible\r\nnetman: tigerrrrr, banany2001, klinchuh, my favourite team ever, are you ready?\r\nklinchuh: yes, coach!\r\ntigerrrrr: yes, netman\r\nbanany2001: yes of course.\r\n"}, {"input": "1\r\n1\r\nb\r\n1\r\nb:lala!\r\n", "output": "b:lala!\r\n"}, {"input": "1\r\n1\r\nb\r\n1\r\n?:lala b!\r\n", "output": "Impossible\r\n"}, {"input": "1\r\n1\r\nb\r\n2\r\n?:lala hhe!\r\nb:wat?\r\n", "output": "Impossible\r\n"}, {"input": "1\r\n3\r\nA B C\r\n3\r\nA: HI\r\n?: HI\r\nB: HI\r\n", "output": "A: HI\r\nC: HI\r\nB: HI\r\n"}]
false
stdio
null
true
32/D
32
D
Python 3
TESTS
5
218
716,800
44375097
x,y,n = map(int,input().split()) count = 0 space = [[0 for i in range(y + 300)] for j in range(x + 300)] for i in range(x): dd = input() for j in range(y): space[i + 1][j + 1] = dd[j] for i in range(2,x ): for j in range(2,y ): for k in range (1,max(x,y)): if space[i][j] == '*'and space[i - k][j] == '*' and space[i + k][j] == '*' and space[i][j - k] == '*' and space[i][j + k] == '*': count += 1 if count == n and space[i][j] == '*'and space[i - k][j] == '*' and space[i + k][j] == '*' and space[i][j - k] == '*' and space[i][j + k] == '*': print(i,j,"\n",i-k,j,"\n",i+k,j,"\n",i,j-k,"\n",i,j+k) if count < n : print('-1')
57
342
5,529,600
146023211
import sys input = sys.stdin.readline n, m, k = map(int, input().split()) s = [list(input().rstrip()) for _ in range(n)] c = 0 for k0 in range(1, min(n, m)): for i in range(k0, n - k0): l0 = min(i, n - i - 1) si = s[i] for j in range(k0, m - k0): if si[j] == ".": continue if si[j - k0] == si[j + k0] == "*": if s[i - k0][j] == s[i + k0][j] == "*": c += 1 if c == k: ans = [(i + 1, j + 1)] ans.append((i + 1 - k0, j + 1)) ans.append((i + 1 + k0, j + 1)) ans.append((i + 1, j + 1 - k0)) ans.append((i + 1, j + 1 + k0)) for i in range(5): ans[i] = " ".join(map(str, ans[i])) sys.stdout.write("\n".join(ans)) exit() print(-1)
Codeforces Beta Round 32 (Div. 2, Codeforces format)
CF
2,010
2
256
Constellation
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: - the 2nd is on the same vertical line as the 1st, but x squares up - the 3rd is on the same vertical line as the 1st, but x squares down - the 4th is on the same horizontal line as the 1st, but x squares left - the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map.
The first line contains three integers n, m and k (1 ≤ n, m ≤ 300, 1 ≤ k ≤ 3·107) — height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right — (n, m). Then there follow n lines, m characters each — description of the map. j-th character in i-th line is «*», if there is a star in the corresponding square, and «.» if this square is empty.
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each — coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
null
null
[{"input": "5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "output": "2 5\n1 5\n3 5\n2 4\n2 6"}, {"input": "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "output": "-1"}, {"input": "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*...", "output": "4 4\n1 4\n7 4\n4 1\n4 7"}]
1,600
["implementation"]
57
[{"input": "5 6 1\r\n....*.\r\n...***\r\n....*.\r\n..*...\r\n.***..\r\n", "output": "2 5\r\n1 5\r\n3 5\r\n2 4\r\n2 6\r\n"}, {"input": "5 6 2\r\n....*.\r\n...***\r\n....*.\r\n..*...\r\n.***..\r\n", "output": "-1\r\n"}, {"input": "7 7 2\r\n...*...\r\n.......\r\n...*...\r\n*.***.*\r\n...*...\r\n.......\r\n...*...\r\n", "output": "4 4\r\n1 4\r\n7 4\r\n4 1\r\n4 7\r\n"}, {"input": "5 5 1\r\n.....\r\n.....\r\n.*..*\r\n*.*..\r\n....*\r\n", "output": "-1\r\n"}, {"input": "5 5 3\r\n*.***\r\n.****\r\n..***\r\n*.***\r\n.**.*\r\n", "output": "3 4\r\n2 4\r\n4 4\r\n3 3\r\n3 5\r\n"}, {"input": "10 10 6\r\n.*..**.**.\r\n**********\r\n****.*****\r\n**.***....\r\n***.******\r\n****.**..*\r\n**.**.****\r\n****.**..*\r\n..**.**.*.\r\n.*.*..***.\r\n", "output": "5 2\r\n4 2\r\n6 2\r\n5 1\r\n5 3\r\n"}, {"input": "10 10 59\r\n**.*******\r\n********.*\r\n***.******\r\n**.*******\r\n*******.**\r\n**********\r\n**.**.****\r\n.*********\r\n*****.****\r\n*********.\r\n", "output": "6 5\r\n3 5\r\n9 5\r\n6 2\r\n6 8\r\n"}, {"input": "10 10 40\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n", "output": "6 9\r\n5 9\r\n7 9\r\n6 8\r\n6 10\r\n"}]
false
stdio
null
true
32/D
32
D
PyPy 3
TESTS
5
280
0
77909924
import sys n,m,k=map(int,input().split(' ')) star=[] for i in range(n): star.append(list(input())) c=0 for i in range(n): for j in range(m): for z in range(min(i,j,(m-1-j),(n-1-i))): if(star[i][j]=='*' and star[i-(z+1)][j]=='*' and star[i+(z+1)][j]=='*' and star[i][j-(z+1)]=='*' and star[i][j+(z+1)]=='*'): c+=1 if(c==k): print(str(i+1)+' '+str(j+1)) print(str(i-z)+' '+str(j+1)) print(str(i+z+2)+' '+str(j+1)) print(str(i+1)+' '+str(j-z)) print(str(i+1)+' '+str(j+z+2)) sys.exit() print(-1)
57
1,058
8,396,800
138784470
n, m, k = map(int, input().split()) f = [str(input()) for i in range(n)] res = [] for r in range(1, min(n, m)): for i in range(r, n - r): for j in range(r, m - r): if f[i][j] == "*": if f[i - r][j] == "*": if f[i + r][j] == "*": if f[i][j - r] == "*": if f[i][j + r] == "*": k -= 1 if k == 0: res = [[i, j], [i - r, j], [i + r, j], [i, j - r], [i, j + r]] for i in res: print(i[0] + 1, i[1] + 1) quit() print(-1)
Codeforces Beta Round 32 (Div. 2, Codeforces format)
CF
2,010
2
256
Constellation
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: - the 2nd is on the same vertical line as the 1st, but x squares up - the 3rd is on the same vertical line as the 1st, but x squares down - the 4th is on the same horizontal line as the 1st, but x squares left - the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map.
The first line contains three integers n, m and k (1 ≤ n, m ≤ 300, 1 ≤ k ≤ 3·107) — height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right — (n, m). Then there follow n lines, m characters each — description of the map. j-th character in i-th line is «*», if there is a star in the corresponding square, and «.» if this square is empty.
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each — coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
null
null
[{"input": "5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "output": "2 5\n1 5\n3 5\n2 4\n2 6"}, {"input": "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "output": "-1"}, {"input": "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*...", "output": "4 4\n1 4\n7 4\n4 1\n4 7"}]
1,600
["implementation"]
57
[{"input": "5 6 1\r\n....*.\r\n...***\r\n....*.\r\n..*...\r\n.***..\r\n", "output": "2 5\r\n1 5\r\n3 5\r\n2 4\r\n2 6\r\n"}, {"input": "5 6 2\r\n....*.\r\n...***\r\n....*.\r\n..*...\r\n.***..\r\n", "output": "-1\r\n"}, {"input": "7 7 2\r\n...*...\r\n.......\r\n...*...\r\n*.***.*\r\n...*...\r\n.......\r\n...*...\r\n", "output": "4 4\r\n1 4\r\n7 4\r\n4 1\r\n4 7\r\n"}, {"input": "5 5 1\r\n.....\r\n.....\r\n.*..*\r\n*.*..\r\n....*\r\n", "output": "-1\r\n"}, {"input": "5 5 3\r\n*.***\r\n.****\r\n..***\r\n*.***\r\n.**.*\r\n", "output": "3 4\r\n2 4\r\n4 4\r\n3 3\r\n3 5\r\n"}, {"input": "10 10 6\r\n.*..**.**.\r\n**********\r\n****.*****\r\n**.***....\r\n***.******\r\n****.**..*\r\n**.**.****\r\n****.**..*\r\n..**.**.*.\r\n.*.*..***.\r\n", "output": "5 2\r\n4 2\r\n6 2\r\n5 1\r\n5 3\r\n"}, {"input": "10 10 59\r\n**.*******\r\n********.*\r\n***.******\r\n**.*******\r\n*******.**\r\n**********\r\n**.**.****\r\n.*********\r\n*****.****\r\n*********.\r\n", "output": "6 5\r\n3 5\r\n9 5\r\n6 2\r\n6 8\r\n"}, {"input": "10 10 40\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n", "output": "6 9\r\n5 9\r\n7 9\r\n6 8\r\n6 10\r\n"}]
false
stdio
null
true
320/B
320
B
PyPy 3-64
TESTS
4
404
3,276,800
223674516
import io import os def fast_input(): input_length = os.fstat(0).st_size byte_encoded_io = io.BytesIO(os.read(0, input_length)) def decoder_wrapper(): if (byte_encoded_io.tell() >= input_length): raise EOFError return byte_encoded_io.readline().decode() return decoder_wrapper # comment or uncomment for interactive vs fast input modes input = fast_input() def readLineAsIntList(): return [int(x) for x in input().split()] def readMultipleLinesAsIntList(count=None): if count is not None: return [int(input()) for i in range(count)] else: ret = [] try: s = input() while True: ret.append(int(s)) s = input() except EOFError: return ret n = readLineAsIntList()[0] # adj[from][to] adj = [[False] * 100 for i in range(100)] itls = [] idx = 0 def add(a, b): for i, (c, d) in enumerate(itls): if c < a < d or c < b < d: adj[idx][i] = True if a < c < b or a < d < b: adj[i][idx] = True itls.append((a, b)) adj[idx][idx] = True for i in range(100): for j in range(100): for k in range(100): if adj[i][k] and adj[k][j]: adj[i][j] = True for (q, a, b) in [readLineAsIntList() for i in range(n)]: if q == 1: add(a, b) idx+=1 if q == 2: print("YES" if adj[a-1][b-1] else "NO")
24
92
0
147542323
v = [] a = [] mark = [] def DFS(x): global mark, v mark[x] = True for i in v[x]: if mark[i]: continue DFS(i) n = int(input()) for i in range(n): s = input() s = s.split() x = int(s[0]) y = int(s[1]) z = int(s[2]) li = list([]) if x == 1: num = len(a) for j in range(len(a)): if (a[j][0] < y < a[j][1]) or (a[j][0] < z < a[j][1]): li.append(j) if (y < a[j][0] < z) or (y < a[j][1] < z): v[j].append(num) a.append((y,z)) v.append(li) else: mark = [False]*int(len(a)) DFS(y-1) if mark[z-1]: print("YES") else: print("NO")
Codeforces Round 189 (Div. 2)
CF
2,013
2
256
Ping-Pong (Easy Version)
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals.
The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct.
For each query of the second type print "YES" or "NO" on a separate line depending on the answer.
null
null
[{"input": "5\n1 1 5\n1 5 11\n2 1 2\n1 2 9\n2 1 2", "output": "NO\nYES"}]
1,500
["dfs and similar", "graphs"]
24
[{"input": "5\r\n1 1 5\r\n1 5 11\r\n2 1 2\r\n1 2 9\r\n2 1 2\r\n", "output": "NO\r\nYES\r\n"}, {"input": "10\r\n1 -311 -186\r\n1 -1070 -341\r\n1 -1506 -634\r\n1 688 1698\r\n2 2 4\r\n1 70 1908\r\n2 1 2\r\n2 2 4\r\n1 -1053 1327\r\n2 5 4\r\n", "output": "NO\r\nNO\r\nNO\r\nYES\r\n"}, {"input": "10\r\n1 -1365 -865\r\n1 1244 1834\r\n2 1 2\r\n1 -1508 -752\r\n2 3 2\r\n2 2 1\r\n1 -779 595\r\n1 -1316 877\r\n2 2 1\r\n1 -698 1700\r\n", "output": "NO\r\nNO\r\nNO\r\nNO\r\n"}, {"input": "20\r\n1 1208 1583\r\n1 -258 729\r\n1 -409 1201\r\n1 194 1938\r\n1 -958 1575\r\n1 -1466 1752\r\n2 1 2\r\n2 1 2\r\n2 6 5\r\n1 -1870 1881\r\n1 -2002 2749\r\n1 -2002 2984\r\n1 -2002 3293\r\n2 2 4\r\n2 8 10\r\n2 9 6\r\n1 -2002 3572\r\n1 -2002 4175\r\n1 -2002 4452\r\n1 -2002 4605\r\n", "output": "YES\r\nYES\r\nYES\r\nYES\r\nYES\r\nNO\r\n"}, {"input": "9\r\n1 1 4\r\n1 5 20\r\n1 11 30\r\n1 29 60\r\n1 59 100\r\n1 100 200\r\n2 1 5\r\n2 1 6\r\n2 2 5\r\n", "output": "NO\r\nNO\r\nYES\r\n"}]
false
stdio
null
true
285/C
285
C
Python 3
TESTS
8
592
20,992,000
67327020
res=0 x=int(input()) s=list(map(int,input().split())) for n in range(x): if s[n]<=0: res+=1-s[n] s[n]=1 elif s[n]>x: res+=s[n]-x s[n]=x z=sorted(s) s.sort() for n in range(x-1): if s[n]>=s[n+1]: s[n+1]=s[n]+1 res+=abs(s[n]-z[n]) res+=abs(s[-1]-z[-1]) print(res)
33
186
32,358,400
172331940
# a,b,k = map(int,input().split()) # for t in range(int(input())): n = int(input()) # dp = [0](n+1) l = [int(z) for z in input().split()] l.sort() ans = 0 for i in range(n): ans+= abs((i+1)-l[i]) print(ans)
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
285/C
285
C
Python 3
TESTS
8
1,122
20,684,800
32157786
n=int(input()) r=map(int,input().split()) f=list(r) #print(f) f.sort() q=f[::-1] #print(q) l=len(q) i=0 count=0 while i<l: y=f[i] if y>n: g=y-n count=count+g if y<n: h=n-y count=count+h i+=1 #print(count) j=0 k=0 while j<n: k=k+j j+=1 #print(k) print(count-k)
33
186
32,358,400
179333459
n = int(input()) arr = [int(k) for k in input().split()] arr.sort() tot = 0 for i, v in enumerate(arr): tot += abs(v - (i + 1)) print(tot)
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
285/C
285
C
Python 3
TESTS
8
1,310
25,190,400
24462631
n = int(input()) l = list(map(int, input().split())) l.sort() start = 1 end = n res = 0 for i in range(n): if l[i] <= i + 1: res += i + 1 - l[i] l[i] = i + 1 else: break for i in range(n - 1, -1 , -1): if l[i] >= i + 1: res += l[i] - (i + 1) l[i] = i + 1 else: break print(res)
33
186
32,358,400
224249570
n = int(input()) l = [int(x) for x in input().split()] l.sort() c = 0 for i in range(n): c+=abs(i+1-l[i]) print(c)
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
610/D
610
D
PyPy 3
TESTS
6
124
1,740,800
202096627
from collections import defaultdict import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def fenwick_tree(n): tree = [0] * (n + 1) return tree def get_sum0(i): s = 0 while i > 0: s += tree[i] i -= i & -i return s def get_sum(s, t): ans = 0 if s > t else get_sum0(t) - get_sum0(s - 1) return ans def add(i, x): while i < len(tree): tree[i] += x i += i & -i n = int(input()) d1, d2 = defaultdict(lambda : []), defaultdict(lambda : []) for _ in range(n): x1, y1, x2, y2 = map(int, input().split()) if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 if y1 == y2: d1[y1].append((x1, x2)) else: d2[x1].append((y1, y2)) ans = 0 z = [] x0, y0 = set(), set() for y in d1: u = d1[y] u.sort() l, r = u[0] for l0, r0 in u: if r < l0: ans += r - l + 1 z.append((l, y, r, y)) l = l0 r = r0 ans += r - l + 1 z.append((l, y, r, y)) for x in d2: u = d2[x] u.sort() l, r = u[0] for l0, r0 in u: if r < l0: ans += r - l + 1 z.append((x, l, x, r)) l = l0 r = r0 ans += r - l + 1 z.append((x, l, x, r)) for x1, y1, x2, y2 in z: x0.add(x1) x0.add(x2) y0.add(y1) y0.add(y2) x0, y0 = list(x0), list(y0) x0.sort() y0.sort() d1, d2 = dict(), dict() m, l = len(x0), len(y0) for i in range(m): d1[x0[i]] = i + 1 for i in range(l): d2[y0[i]] = i + 1 u = [[] for _ in range(m + 2)] v = [[] for _ in range(m + 2)] for x3, y3, x4, y4 in z: x1, y1, x2, y2 = d1[x3], d2[y3], d1[x4], d2[y4] if y1 == y2: u[x1].append((y1, 1)) u[x2 + 1].append((y1, -1)) else: v[x1].append((y1, y2)) tree = fenwick_tree(l + 5) ng = 0 for i in range(1, m + 1): for j, c in u[i]: add(j, c) for l0, r0 in v[i]: ng += get_sum(l0, r0) ans -= ng print(ans)
47
1,278
54,681,600
216911246
# i'm from jasnah, do not ban me from sys import stdin from itertools import repeat from collections import defaultdict num_rectangles = int(stdin.readline()) horizontal_segments = defaultdict(list) vertical_segments = defaultdict(list) unique_y_values = set() events = defaultdict(list) for _ in repeat(None, num_rectangles): x1, y1, x2, y2 = map(int, input().split()) if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 if x1 == x2: horizontal_segments[x1].append((y1, y2)) else: vertical_segments[y1].append((x1, x2)) total_area = 0 for x, segments in horizontal_segments.items(): segments.sort() segments.append((1001001001, 1001001001)) new_segments = [] start = end = segments[0][0] for y1, y2 in segments: if y1 > end: new_segments.append((start, end)) total_area += end - start + 1 events[start].append((1, x)) events[end + 1].append((-1, x)) start = end = y1 if end < y2: end = y2 segments = new_segments unique_y_values.add(x) for y, segments in vertical_segments.items(): segments.sort() segments.append((1001001001, 1001001001)) new_segments = [] start = end = segments[0][0] for x1, x2 in segments: if x1 > end: new_segments.append((start, end)) unique_y_values.add(start) unique_y_values.add(end) events[y].append((2, start, end)) total_area += end - start + 1 start = end = x1 if end < x2: end = x2 segments = new_segments unique_y_values = [-1001001001] + sorted(unique_y_values) unique_y_values_mapping = {y: i for i, y in enumerate(unique_y_values)} length = len(unique_y_values) binary_indexed_tree = [0] * length for x_value in sorted(events.keys()): for event in sorted(events[x_value]): if event[0] <= 1: operation, y_value = event[0], unique_y_values_mapping[event[1]] while y_value < length: binary_indexed_tree[y_value] += operation y_value += y_value - (y_value & (y_value - 1)) else: operation, start, end = event[0], unique_y_values_mapping[event[1]] - 1, unique_y_values_mapping[event[2]] while end > 0: total_area -= binary_indexed_tree[end] end = end & (end - 1) while start > 0: total_area += binary_indexed_tree[start] start = start & (start - 1) print(total_area)
Codeforces Round 337 (Div. 2)
CF
2,015
2
256
Vika and Segments
Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column. Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of segments drawn by Vika. Each of the next n lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.
Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.
null
In the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3).
[{"input": "3\n0 1 2 1\n1 4 1 2\n0 3 2 3", "output": "8"}, {"input": "4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2", "output": "16"}]
2,300
["constructive algorithms", "data structures", "geometry", "two pointers"]
47
[{"input": "3\r\n0 1 2 1\r\n1 4 1 2\r\n0 3 2 3\r\n", "output": "8\r\n"}, {"input": "4\r\n-2 -1 2 -1\r\n2 1 -2 1\r\n-1 -2 -1 2\r\n1 2 1 -2\r\n", "output": "16\r\n"}, {"input": "1\r\n1 1 1 1\r\n", "output": "1\r\n"}, {"input": "10\r\n-357884841 -999999905 -357884841 999999943\r\n-130177221 999999983 -130177221 -999999974\r\n627454332 999999936 627454332 -999999900\r\n999999986 366591992 -999999919 366591992\r\n488824292 999999952 488824292 -999999979\r\n-261575319 999999910 -261575319 -999999995\r\n837827059 -999999983 837827059 999999984\r\n-999999947 543634048 999999977 543634048\r\n512878899 -999999968 512878899 999999926\r\n239286254 -999999975 239286254 999999937\r\n", "output": "19999999073\r\n"}, {"input": "4\r\n553245544 -999999997 553245544 -918743333\r\n999999988 -668043590 264717840 -668043590\r\n-999999961 121002405 999999920 121002405\r\n999999985 121822043 -796706494 121822043\r\n", "output": "4613245176\r\n"}]
false
stdio
null
true
32/D
32
D
PyPy 3-64
TESTS
5
154
512,000
145340296
n, m, k = map(int, input().split()) starmap = [] for i in range(n): row = [] temp = input() for j in range(m): if temp[j] == '.': row.append(0) else: row.append(1) starmap.append(row) num_crosses = 0 flag = 0 for i in range(n): for j in range(m): for p in range(1, min(i, j)+1): try: if starmap[i][j] == 1 and starmap[i][j-p] == 1 and starmap[i][j+p] == 1 and starmap[i-p][j] == 1 and starmap[i+p][j] == 1: num_crosses += 1 if num_crosses == k: print(i+1, j+1) print(i-p+1, j+1) print(i+p+1, j+1) print(i+1, j-p+1) print(i+1, j+p+1) flag = 1 break except: pass if flag == 1: break if flag == 1: break if flag == 0: print(-1)
57
1,994
5,222,400
95437141
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)] cnt = [0] * 400 for i in range(1, n - 1): for j in range(1, m - 1): if not a[i][j]: continue for rad, ui, di, lj, rj in zip(range(1, 400), range(i - 1, -1, -1), range(i + 1, n), range(j - 1, -1, -1), range(j + 1, m)): if all((a[ui][j], a[di][j], a[i][lj], a[i][rj])): cnt[rad] += 1 rad = -1 for i in range(300): cnt[i + 1] += cnt[i] if cnt[i] >= k: rad = i k -= cnt[i - 1] break else: print(-1) exit() for i in range(rad, n - rad): for j in range(rad, m - rad): if all((a[i][j], a[i - rad][j], a[i + rad][j], a[i][j - rad], a[i][j + rad])): k -= 1 if k == 0: print(f'{i+1} {j+1}\n{i-rad+1} {j+1}\n{i+rad+1} {j+1}\n{i+1} {j-rad+1}\n{i+1} {j+rad+1}') exit()
Codeforces Beta Round 32 (Div. 2, Codeforces format)
CF
2,010
2
256
Constellation
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: - the 2nd is on the same vertical line as the 1st, but x squares up - the 3rd is on the same vertical line as the 1st, but x squares down - the 4th is on the same horizontal line as the 1st, but x squares left - the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map.
The first line contains three integers n, m and k (1 ≤ n, m ≤ 300, 1 ≤ k ≤ 3·107) — height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right — (n, m). Then there follow n lines, m characters each — description of the map. j-th character in i-th line is «*», if there is a star in the corresponding square, and «.» if this square is empty.
If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each — coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.
null
null
[{"input": "5 6 1\n....*.\n...***\n....*.\n..*...\n.***..", "output": "2 5\n1 5\n3 5\n2 4\n2 6"}, {"input": "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..", "output": "-1"}, {"input": "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*...", "output": "4 4\n1 4\n7 4\n4 1\n4 7"}]
1,600
["implementation"]
57
[{"input": "5 6 1\r\n....*.\r\n...***\r\n....*.\r\n..*...\r\n.***..\r\n", "output": "2 5\r\n1 5\r\n3 5\r\n2 4\r\n2 6\r\n"}, {"input": "5 6 2\r\n....*.\r\n...***\r\n....*.\r\n..*...\r\n.***..\r\n", "output": "-1\r\n"}, {"input": "7 7 2\r\n...*...\r\n.......\r\n...*...\r\n*.***.*\r\n...*...\r\n.......\r\n...*...\r\n", "output": "4 4\r\n1 4\r\n7 4\r\n4 1\r\n4 7\r\n"}, {"input": "5 5 1\r\n.....\r\n.....\r\n.*..*\r\n*.*..\r\n....*\r\n", "output": "-1\r\n"}, {"input": "5 5 3\r\n*.***\r\n.****\r\n..***\r\n*.***\r\n.**.*\r\n", "output": "3 4\r\n2 4\r\n4 4\r\n3 3\r\n3 5\r\n"}, {"input": "10 10 6\r\n.*..**.**.\r\n**********\r\n****.*****\r\n**.***....\r\n***.******\r\n****.**..*\r\n**.**.****\r\n****.**..*\r\n..**.**.*.\r\n.*.*..***.\r\n", "output": "5 2\r\n4 2\r\n6 2\r\n5 1\r\n5 3\r\n"}, {"input": "10 10 59\r\n**.*******\r\n********.*\r\n***.******\r\n**.*******\r\n*******.**\r\n**********\r\n**.**.****\r\n.*********\r\n*****.****\r\n*********.\r\n", "output": "6 5\r\n3 5\r\n9 5\r\n6 2\r\n6 8\r\n"}, {"input": "10 10 40\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n**********\r\n", "output": "6 9\r\n5 9\r\n7 9\r\n6 8\r\n6 10\r\n"}]
false
stdio
null
true
285/C
285
C
PyPy 3
TESTS
6
608
29,081,600
120248416
n = int(input()) nums = [(int(x),abs(n-int(x))) for x in input().split()] nums.sort(key = lambda x: (-x[1])) moves = 0 for i in range(1,n+1): val = nums[i-1][0] moves = moves + abs(val - i) print(moves)
33
187
34,406,400
181322660
def solve(): n = int(input()) a = sorted([int(i) for i in input().split()]) ans = 0 for i in range(n): ans += abs(a[i] - i - 1) return ans print(solve())
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
19/A
19
A
Python 3
TESTS
4
92
0
201263699
class Solution: def __init__(self): self.no_of_teams=int(input()) self.order=[] self.mp={} for i in range(self.no_of_teams): self.order.append(input()) for i in range((self.no_of_teams * (self.no_of_teams-1))//2): buffer_input = input() teams,score = buffer_input.split(' ') teams = teams.split('-') score = [int(x) for x in score.split(':')] if teams[0] not in self.mp: self.mp[teams[0]]=[0,0,0] if teams[1] not in self.mp: self.mp[teams[1]]=[0,0,0] self.mp[teams[0]][0]+= 3 if score[0]>score[1] else 1 self.mp[teams[1]][0]+= 3 if score[0]<score[1] else 1 self.mp[teams[0]][1]+= score[0]-score[1] self.mp[teams[1]][1]+= score[1]-score[0] self.mp[teams[0]][2]+=score[0] self.mp[teams[1]][2]+=score[1] def solve(self): self.mp=sorted(self.mp.items(), reverse=True, key = lambda x: (x[1][0],x[1][1],x[1][2])) self.mp1=set() for i in range(self.no_of_teams//2): self.mp1.add(self.mp[i][0]) for i in self.order: if i in self.mp1: print(i) solve=Solution() solve.solve()
29
92
0
141674992
class Info: def __init__(self, _teamName, _points, _goalDiff, _scoredGaols): self.teamName = _teamName self.points = _points self.goalDiff = _goalDiff self.scoredGoals = _scoredGaols def __str__(self): return f'\n*************************\n' \ f'teamName = {self.teamName} \n' \ f'points = {self.points}\n' \ f'goalDiff = {self.goalDiff}\n' \ f'scoredGoals = {self.scoredGoals}\n' \ f'****************************\n' def __eq__(self, other): if other is Info and self.teamName == other.teamName and self.points == other.points \ and self.goalDiff == other.goalDiff and self.scoredGoals == other.scoredGoals: return True return False def output(cont): for item in cont: print(item) def indexOf(cont, searchName): for i in range(len(cont)): if cont[i].teamName == searchName: return i return -1 # obj = Info("barcelona", 5, 8, 15) # print(obj) n = int(input()) cont = [] for i in range(n): # tName = input() # obj = Info(tName,0,0,0) # cont.append(obj) cont.append(Info(input(), 0, 0, 0)) # output(cont) ''' 01234567890123456789 line == "Barcelona-Real 15:10" ''' for i in range(n * (n - 1) // 2): line = input() dashIndex = line.index('-') spaceIndex = line.index(' ') colonIndex = line.index(':') team1Name = line[:dashIndex] team2Name = line[dashIndex + 1:spaceIndex] goal1 = int(line[spaceIndex + 1:colonIndex]) goal2 = int(line[colonIndex + 1:]) team1Ind = indexOf(cont, team1Name) team2Ind = indexOf(cont, team2Name) # update points if goal1 > goal2: cont[team1Ind].points += 3 elif goal1 < goal2: cont[team2Ind].points += 3 else: cont[team1Ind].points += 1 cont[team2Ind].points += 1 # update GoalDiff cont[team1Ind].goalDiff += goal1 - goal2 cont[team2Ind].goalDiff += goal2 - goal1 # update scoredGoals cont[team1Ind].scoredGoals += goal1 cont[team2Ind].scoredGoals += goal2 # sort By points in Descending order then by goaldiff in descending order then by scoredgoals in descending order cont.sort(key=lambda item: (item.points, item.goalDiff, item.scoredGoals), reverse=True) del cont[n // 2:] # sort by teamname in ascending order cont.sort(key=lambda item: item.teamName) for item in cont: print(item.teamName) ''' 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Points GoalDifference ScoredGoals A => 1+1+3=5 A => (1+2+1) - (1+2+0) = 4 - 3 = 1 A => 4 B => 1+3+0=4 B => (1+1+0) - (1+0+3) = 2 - 4 = -2 B => 2 C => 1+0+0=1 C => (2+0+0) - (2+1+3) = 2 - 6 = -4 C => 2 D => 0+3+3=6 D => (0+3+3) - (1+0+0) = 6 - 1 = 5 D => 6 D, A, B, C => D, A => A, D |TeamName: "A" | |Point: 5 | |GoalDiff: 1 | |ScoredGoals: 4| '''
Codeforces Beta Round 19
ICPC
2,010
2
64
World Football Cup
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: - the final tournament features n teams (n is always even) - the first n / 2 teams (according to the standings) come through to the knockout stage - the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals - it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
The first input line contains the only integer n (1 ≤ n ≤ 50) — amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following n·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 — names of the teams; num1, num2 (0 ≤ num1, num2 ≤ 100) — amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
Output n / 2 lines — names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
null
null
[{"input": "4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3", "output": "A\nD"}, {"input": "2\na\nA\na-A 2:1", "output": "a"}]
1,400
["implementation"]
29
[{"input": "4\r\nA\r\nB\r\nC\r\nD\r\nA-B 1:1\r\nA-C 2:2\r\nA-D 1:0\r\nB-C 1:0\r\nB-D 0:3\r\nC-D 0:3\r\n", "output": "A\r\nD\r\n"}, {"input": "2\r\na\r\nA\r\na-A 2:1\r\n", "output": "a\r\n"}, {"input": "2\r\nEULEUbCmfrmqxtzvg\r\nuHGRmKUhDcxcfqyruwzen\r\nuHGRmKUhDcxcfqyruwzen-EULEUbCmfrmqxtzvg 13:92\r\n", "output": "EULEUbCmfrmqxtzvg\r\n"}, {"input": "6\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nA-B 1:0\r\nA-C 0:0\r\nA-D 1:0\r\nA-E 5:5\r\nA-F 0:1\r\nB-C 1:0\r\nB-D 1:0\r\nB-E 1:0\r\nB-F 0:2\r\nC-D 2:2\r\nC-E 1:0\r\nC-F 1:0\r\nD-E 1:0\r\nD-F 1:0\r\nE-F 0:1\r\n", "output": "A\r\nB\r\nF\r\n"}, {"input": "6\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nA-B 1:0\r\nA-C 0:0\r\nA-D 1:0\r\nA-E 5:5\r\nA-F 0:1\r\nB-C 1:0\r\nB-D 1:0\r\nB-E 1:0\r\nB-F 0:2\r\nC-D 7:7\r\nC-E 1:0\r\nC-F 1:0\r\nD-E 1:0\r\nD-F 1:0\r\nE-F 0:1\r\n", "output": "B\r\nC\r\nF\r\n"}]
false
stdio
null
true
19/A
19
A
Python 3
TESTS
4
186
307,200
64257842
#RAVENS #TEAM_2 #ESSI-DAYI_MOHSEN-LORENZO #from tokhmi import Tokhmi_Tarin_Halat_Momken team = [] score = [] goals = [] # gola zade khorde n = int(input()) for i in range(n): team.append(input()) score.append(0) goals.append([0, 0]) for i in range(n * (n - 1) // 2): a, b = input().split() t1, t2 = a.split("-") g1, g2 = b.split(":") in1 = team.index(t1) in2 = team.index(t2) goals[in1][0] += int(g1) goals[in1][1] += int(g2) goals[in2][0] += int(g2) goals[in2][1] += int(g1) if g1 > g2: score[in1] += 3 elif g2 > g1: score[in2] += 3 else: score[in1] += 1 score[in2] += 1 for i in range(n): #print("i : ",i) for j in range(i + 1,n): #print("j : ",j) if (score[i] < score[j]): v = team[j] team[j] = team[i] team[i] = v v = score[j] score[j] = score[i] score[i] = v v = goals[j] goals[j] = goals[i] goals[i] = v elif (score[i] == score[j]): x = goals[i][0] - goals[i][1] y = goals[j][0] - goals[j][1] if (x < y): # tafazol #print("tafazol ",team[i], " < ",team[j]) v = team[j] team[j] = team[i] team[i] = v v = score[j] score[j] = score[i] score[i] = v v = goals[j] goals[j] = goals[i] goals[i] = v elif (x == y): if (goals[i][0] < goals[j][0]): v = team[j] team[j] = team[i] team[i] = v v = score[j] score[j] = score[i] score[i] = v v = goals[j] goals[j] = goals[i] goals[i] = v #print() #print(team) #print(score) #print(goals) #print("----------------------") team = sorted(team[:n // 2]) #print(team) for i in range(n // 2): print(team[i]) ''' 4 TeMnHVvWKpwlpubwyhzqvc AWJwc bhbxErlydiwtoxy EVASMeLpfqwjkke AWJwc-TeMnHVvWKpwlpubwyhzqvc 37:34 bhbxErlydiwtoxy-TeMnHVvWKpwlpubwyhzqvc 38:99 bhbxErlydiwtoxy-AWJwc 33:84 EVASMeLpfqwjkke-TeMnHVvWKpwlpubwyhzqvc 79:34 EVASMeLpfqwjkke-AWJwc 24:37 EVASMeLpfqwjkke-bhbxErlydiwtoxy 3:6 team=dict() score=[] goals=[0,0] # gola zade khorde ls=[] n=int(input()) for i in range(n): team[input()]=[0,0,0] for i in range(n*(n-1)//2): a,b=input().split() t1,t2=a.split("-") g1,g2=b.split(":") team[t1][1]+=int(g1) team[t1][2]+=int(g2) team[t2][1]+=int(g2) team[t2][2]+=int(g1) if g1>g2: team[t1][0]+=3 elif g2>g1: team[t2][0]+=3 else: team[t1][0]+=1 team[t2][0]+=1 sorted_x = sorted(team.items(), key=lambda kv: kv[1]) print(sorted_x) input("enter ? ") for i in team.keys(): ls.append([i,team[i][0],team[i][1],team[i][2]]) print(ls)''' #sag to roohet :D
29
92
0
147237334
class Info: def __init__(self, newTeamName, newPoints, newGoalDiff, newScoredGoals): self.teamName = newTeamName self.points = newPoints self.goalDiff = newGoalDiff self.scoredGoals = newScoredGoals def __str__(self): return f'[teamName: {self.teamName}, Points: {self.points}, ' \ f'GoalDiff: {self.goalDiff}, ScoredGoals: {self.scoredGoals}]' def output(cont): for item in cont: print(item) def findIndexByName(cont, searchName): for i in range(len(cont)): if cont[i].teamName == searchName: return i return -1 N = int(input()) cont = list() for i in range(N): cont.append(Info(input(), 0, 0, 0)) # 01234567890123456789 # Barcelona-Real 15:10 for i in range(N * (N - 1) // 2): line = input() dashIndex = line.index('-') spaceIndex = line.index(' ') colonIndex = line.index(':') team1Name = line[:dashIndex] team2Name = line[dashIndex + 1:spaceIndex] goal1 = int(line[spaceIndex + 1:colonIndex]) goal2 = int(line[colonIndex + 1:]) team1Index = findIndexByName(cont, team1Name) team2Index = findIndexByName(cont, team2Name) # update points: if goal1 > goal2: cont[team1Index].points += 3 elif goal1 < goal2: cont[team2Index].points += 3 else: cont[team1Index].points += 1 cont[team2Index].points += 1 # update goalDiff: cont[team1Index].goalDiff += goal1 - goal2 cont[team2Index].goalDiff += goal2 - goal1 # update scoredGoals: cont[team1Index].scoredGoals += goal1 cont[team2Index].scoredGoals += goal2 cont.sort(key=lambda item: (item.points, item.goalDiff, item.scoredGoals), reverse=True) del cont[N // 2:] cont.sort(key =lambda item: item.teamName) #output(cont) for item in cont: print(item.teamName)
Codeforces Beta Round 19
ICPC
2,010
2
64
World Football Cup
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: - the final tournament features n teams (n is always even) - the first n / 2 teams (according to the standings) come through to the knockout stage - the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals - it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
The first input line contains the only integer n (1 ≤ n ≤ 50) — amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following n·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 — names of the teams; num1, num2 (0 ≤ num1, num2 ≤ 100) — amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
Output n / 2 lines — names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
null
null
[{"input": "4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3", "output": "A\nD"}, {"input": "2\na\nA\na-A 2:1", "output": "a"}]
1,400
["implementation"]
29
[{"input": "4\r\nA\r\nB\r\nC\r\nD\r\nA-B 1:1\r\nA-C 2:2\r\nA-D 1:0\r\nB-C 1:0\r\nB-D 0:3\r\nC-D 0:3\r\n", "output": "A\r\nD\r\n"}, {"input": "2\r\na\r\nA\r\na-A 2:1\r\n", "output": "a\r\n"}, {"input": "2\r\nEULEUbCmfrmqxtzvg\r\nuHGRmKUhDcxcfqyruwzen\r\nuHGRmKUhDcxcfqyruwzen-EULEUbCmfrmqxtzvg 13:92\r\n", "output": "EULEUbCmfrmqxtzvg\r\n"}, {"input": "6\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nA-B 1:0\r\nA-C 0:0\r\nA-D 1:0\r\nA-E 5:5\r\nA-F 0:1\r\nB-C 1:0\r\nB-D 1:0\r\nB-E 1:0\r\nB-F 0:2\r\nC-D 2:2\r\nC-E 1:0\r\nC-F 1:0\r\nD-E 1:0\r\nD-F 1:0\r\nE-F 0:1\r\n", "output": "A\r\nB\r\nF\r\n"}, {"input": "6\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nA-B 1:0\r\nA-C 0:0\r\nA-D 1:0\r\nA-E 5:5\r\nA-F 0:1\r\nB-C 1:0\r\nB-D 1:0\r\nB-E 1:0\r\nB-F 0:2\r\nC-D 7:7\r\nC-E 1:0\r\nC-F 1:0\r\nD-E 1:0\r\nD-F 1:0\r\nE-F 0:1\r\n", "output": "B\r\nC\r\nF\r\n"}]
false
stdio
null
true
505/B
505
B
Python 3
TESTS
5
108
307,200
96940798
def dfs(vertice, cor, adjacencias, visitados): if visitados[vertice] != 1: visitados[vertice] = 1 for aresta in adjacencias[str(vertice)]: if aresta[1] == cor: dfs(int(aresta[0]), cor, adjacencias, visitados) entrada = input().split() n = int(entrada[0]) m = int(entrada[1]) adjacencias = {} i = 1 while i <= n: adjacencias[str(i)] = [] i += 1 i = 0 while i < m: aresta = input().split() adjacencias[aresta[0]].append([aresta[1],aresta[2]]) adjacencias[aresta[1]].append([aresta[0],aresta[2]]) i += 1 q = int(input()) res = [0] * (q + 1) i = 1 while i <= q: questao = input().split() u = questao[0] v = questao[1] for aresta in adjacencias[u]: visitados = [0] * (n + 1) cor = aresta[1] visitados[int(u)] = 1 dfs(int(aresta[0]), cor, adjacencias, visitados) if visitados[int(v)] == 1: res[i] += 1 i += 1 del(res[0]) for e in res: print(e)
29
46
0
147549004
dic = {} mark = [] v = [] def DFS(x): global mark, v mark[x] = True for i in v[x]: if mark[i]: continue DFS(i) s = input() s = s.split() n = int(s[0]) m = int(s[1]) for i in range(m): s = input() s = s.split() x = int(s[0]) y = int(s[1]) z = int(s[2]) x -= 1 y -= 1 if z not in dic: dic[z] = [] for j in range(n): dic[z].append(list([])) dic[z][x].append(y) dic[z][y].append(x) k = int(input()) for i in range(k): ans = 0 s = input() s = s.split() x = int(s[0])-1 y = int(s[1])-1 for j in dic.keys(): mark = [False]*n v = dic[j] DFS(x) if mark[y]: ans += 1 print(ans)
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
505/B
505
B
PyPy 3
TESTS
5
124
2,662,400
108055526
import sys import math from collections import defaultdict import itertools MAXNUM = math.inf MINNUM = -1 * math.inf def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write() pass def dfs(a, b, edgeList): total = 0 for nxt, col in edgeList[a]: explored = dict() explored[a] = True explored[nxt] = True total += dfs_helper(nxt, b, edgeList, col, explored) return total def dfs_helper(cur, goal, edgeList, color, explored): if cur == goal: return 1 for nxt, col in edgeList[cur]: if col == color and nxt not in explored: explored[nxt] = True if dfs_helper(nxt, goal, edgeList, color, explored) == 1: return 1 return 0 def solve(n, m, edgeList, queries): for a, b in queries: print(dfs(a, b, edgeList)) def readinput(): n, m = getInts() edgeList = defaultdict(list) for _ in range(m): a, b, c = getInts() edgeList[a].append((b, c)) edgeList[b].append((a, c)) queries = [] q = getInt() for _ in range(q): queries.append(tuple(getInts())) (solve(n, m, edgeList, queries)) readinput()
29
46
0
152832300
N,M = map(int,input().split()) dat = [[] for _ in range(N)] color = [set() for _ in range(N)] for _ in range(M): a,b,c = map(int,input().split()) dat[a-1].append([b-1,c]) dat[b-1].append([a-1,c]) color[a-1].add(c) color[b-1].add(c) def dfs(i,pre): global ans if i==v-1: ans += 1 visited[i] = 1 for x,y in dat[i]: if visited[x]==1 or y!=pre:continue dfs(x,y) for _ in range(int(input())): u,v = map(int,input().split()) ans = 0 for i in color[u-1]: if i not in color[v-1]:continue visited = [0]*N dfs(u-1,i) print(ans)
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
505/B
505
B
PyPy 3
TESTS
5
124
3,686,400
148240346
n,m = map(int, input().split()) store = [[] for i in range(n+1)] for q in range(m): a,b,c = map(int, input().split()) store[a].append([b,c]) store[b].append([a,c]) vis = [0 for i in range(n+1)] count = 0 def dfs(vertex, dest ,color): global count if vis[vertex]: return vis[vertex] = 1 for child in store[vertex]: if vis[child[0]]: continue if child[0] == dest and child[1] == color: count += 1 return if child[1] != color: continue elif child[1] == color: dfs(child[0], dest, color) else: return q = int(input()) for qu in range(q): a,b = map(int, input().split()) ans = 0 for i in range(1, m+1): dfs(a,b,i) ans += count count = 0 vis = [0 for i in range(n+1)] print(ans)
29
46
0
184157821
def frente(a, c): if f[c][a] != a: f[c][a] = frente(f[c][a], c) return f[c][a] def antes(a, b, c): ra, rb = frente(a, c), frente(b, c) if ra == rb: return f[c][ra] = rb n, m = map(int,input().split()) f = [list(range(n + 1)) for _ in range(m + 2)] for a, b, c in [map(int,input().split()) for _ in range(m)]: antes(a, b, c) q = int(input()) for x, y in [map(int, input().split()) for _ in range(q)]: print(sum(1 for i in range(1, m + 1) if frente(x, i) == frente(y, i)))
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
505/D
505
D
Python 3
PRETESTS
2
61
0
9464509
n, m = map(int, input().split()) l=[] for i in range(m): l.append(list(map(int, input().split()))) l.sort() o=0 for i in range(len(l)-1): o+=1 if(l.count([l[i], l[i+1]])): o-=1 print(o-1)
50
624
12,390,400
20522061
def main(): n, m = map(int, input().split()) n += 1 cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)] def root(x): if x != cluster[x]: cluster[x] = x = root(cluster[x]) return x for _ in range(m): a, b = map(int, input().split()) ab[a].append(b) dest[b] += 1 cluster[root(a)] = root(b) pool = [a for a, f in enumerate(dest) if not f] for a in pool: for b in ab[a]: dest[b] -= 1 if not dest[b]: pool.append(b) ab = [True] * n for a, f in enumerate(dest): if f: ab[root(a)] = False print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, ab))) if __name__ == '__main__': from sys import setrecursionlimit setrecursionlimit(100500) main()
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
null
For the first sample, one of the optimal ways to construct pipes is shown in the image below: For the second sample, one of the optimal ways is shown below:
[{"input": "4 5\n1 2\n1 3\n1 4\n2 3\n2 4", "output": "3"}, {"input": "4 6\n1 2\n1 4\n2 3\n2 4\n3 2\n3 4", "output": "4"}]
2,200
["dfs and similar"]
50
[{"input": "4 5\r\n1 2\r\n1 3\r\n1 4\r\n2 3\r\n2 4\r\n", "output": "3\r\n"}, {"input": "4 6\r\n1 2\r\n1 4\r\n2 3\r\n2 4\r\n3 2\r\n3 4\r\n", "output": "4\r\n"}, {"input": "4 6\r\n1 2\r\n1 3\r\n1 4\r\n2 3\r\n2 4\r\n3 4\r\n", "output": "3\r\n"}, {"input": "3 6\r\n1 2\r\n1 3\r\n2 1\r\n2 3\r\n3 1\r\n3 2\r\n", "output": "3\r\n"}, {"input": "8 12\r\n6 1\r\n7 5\r\n2 5\r\n4 1\r\n6 3\r\n4 3\r\n5 7\r\n1 3\r\n5 2\r\n2 7\r\n4 6\r\n7 2\r\n", "output": "6\r\n"}, {"input": "2 1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "10 4\r\n8 4\r\n9 8\r\n2 8\r\n8 1\r\n", "output": "4\r\n"}, {"input": "8 7\r\n6 3\r\n2 4\r\n3 7\r\n8 2\r\n4 8\r\n7 6\r\n3 2\r\n", "output": "6\r\n"}, {"input": "10 10\r\n10 6\r\n9 4\r\n7 8\r\n1 5\r\n3 10\r\n2 1\r\n4 9\r\n5 2\r\n10 3\r\n6 3\r\n", "output": "9\r\n"}, {"input": "7 8\r\n4 6\r\n2 1\r\n2 5\r\n7 4\r\n7 1\r\n7 2\r\n1 4\r\n2 4\r\n", "output": "5\r\n"}, {"input": "9 10\r\n6 4\r\n7 5\r\n9 3\r\n7 6\r\n4 8\r\n4 2\r\n9 8\r\n1 3\r\n5 1\r\n4 7\r\n", "output": "9\r\n"}, {"input": "10 4\r\n7 4\r\n6 8\r\n2 3\r\n3 8\r\n", "output": "4\r\n"}, {"input": "7 13\r\n6 1\r\n7 2\r\n3 7\r\n6 5\r\n3 6\r\n7 4\r\n3 5\r\n4 1\r\n3 1\r\n1 5\r\n1 6\r\n6 2\r\n2 4\r\n", "output": "7\r\n"}, {"input": "5 7\r\n4 3\r\n2 5\r\n2 1\r\n3 2\r\n1 3\r\n3 4\r\n1 4\r\n", "output": "5\r\n"}, {"input": "6 7\r\n5 4\r\n3 1\r\n4 2\r\n2 1\r\n5 2\r\n2 3\r\n2 6\r\n", "output": "5\r\n"}, {"input": "9 5\r\n5 8\r\n7 4\r\n7 2\r\n9 8\r\n9 5\r\n", "output": "4\r\n"}, {"input": "5 4\r\n2 5\r\n4 3\r\n5 2\r\n5 1\r\n", "output": "4\r\n"}, {"input": "7 7\r\n7 3\r\n5 4\r\n4 7\r\n5 7\r\n6 3\r\n5 6\r\n3 4\r\n", "output": "5\r\n"}, {"input": "8 5\r\n3 1\r\n7 5\r\n2 5\r\n8 6\r\n1 3\r\n", "output": "5\r\n"}, {"input": "5 3\r\n4 2\r\n2 1\r\n5 4\r\n", "output": "3\r\n"}]
false
stdio
null
true
505/B
505
B
PyPy 3
TESTS
5
139
1,126,400
50161725
# !/usr/bin/env python3 # coding: UTF-8 # Modified: <19/Feb/2019 06:22:16 PM> # ✪ H4WK3yE乡 # Mohd. Farhan Tahir # Indian Institute Of Information Technology (IIIT),Gwalior # Question Link # # # ///==========Libraries, Constants and Functions=============/// import sys inf = float("inf") mod = 1000000007 def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline() # ///==========MAIN=============/// N = 105 graph = [[] for _ in range(N)] component = [0] * N visited = [False] * N cnt = 0 v = 0 n, m = 0, 0 ans = 0 def explore(node): visited[node] = True component[node] = cnt for neighbour, color in graph[node]: if visited[neighbour] == False: explore(neighbour) def dfs(n): global cnt for i in range(1, n + 1): if visited[i] == False: cnt += 1 explore(i) def explore_o(node, c): global ans visited[node] = True for neighbour, color in graph[node]: if visited[neighbour] == False and color == c: if neighbour == v: ans += 1 return explore_o(neighbour, c) def dfs_o(u): global visited, ans ans = 0 for neighbour, color in graph[u]: visited = [False] * N visited[u] = True if neighbour == v: ans += 1 continue explore_o(neighbour, color) return ans def main(): global n, m n, m = get_ints() for _ in range(m): u, x, c = get_ints() graph[u].append((x, c)) graph[x].append((u, c)) dfs(n) global v for tc in range(int(input())): u, v = get_ints() if component[u] != component[v]: print(0) continue print(dfs_o(u)) if __name__ == "__main__": main()
29
61
0
142184973
n, m = list(map(int,input().split())) grath = {} for i in range(n): grath[i + 1] = [] for i in range(m): a,b,c = list(map(int,input().split())) grath[a].append([b, c]) grath[b].append([a, c]) q = int(input()) def dfs(v,used,color): used[v] = True for u in grath[v]: if u[1] == color and used[u[0]] == False: dfs(u[0], used, color) itog = [] for _ in range(q): count = 0 u, v = list(map(int,input().split())) s = set() for i in grath[u]: s.add(i[1]) for color in s: used = [False for j in range(n + 1)] dfs(u, used, color) if used[v] == True: count += 1 itog.append(count) for i in itog: print(i)
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
1006/C
1006
C
Python 3
TESTS
20
342
21,401,600
96751934
import sys from collections import Counter as cs #input=sys.stdin.readline n=int(input()) ls=[int(a) for a in input().split()] ls1=[ls[0]] ls2=[ls[-1]] sm=sum(ls) p1,p2=1,1 for i in range(n-1): ls1.append(ls1[-1]+ls[i+1]) if ls1[-1]>sm/2: ls1.pop() break for i in range(n-1,len(ls1),-1): ls2.append(ls2[-1]+ls[i-1]) dt=dict(cs(ls1)) for i in ls2: if i in dt: dt[i]+=1 else: dt[i]=1 an=0 ls1.sort(reverse=True) for i in ls1: if dt[i]>1: an=i break print(an)
27
109
23,654,400
216909712
n = int(input()) lista = list(map(int, input().split(" "))) pont_1 = 0 pont_2 = len(lista) - 1 valor_1 = lista[pont_1] valor_2 = lista[pont_2] value = 0 while (pont_1 < pont_2): if (valor_1 < valor_2): pont_1 += 1 valor_1 += lista[pont_1] elif (valor_1 > valor_2): pont_2 -= 1 valor_2 += lista[pont_2] else: value = valor_1 pont_1 += 1 valor_1 += lista[pont_1] print(value)
Codeforces Round 498 (Div. 3)
ICPC
2,018
1
256
Three Parts of the Array
You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible. More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then: $$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$ The sum of an empty array is $$$0$$$. Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.
Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).
null
In the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$. In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$. In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.
[{"input": "5\n1 3 1 1 4", "output": "5"}, {"input": "5\n1 3 2 1 4", "output": "4"}, {"input": "3\n4 1 2", "output": "0"}]
1,200
["binary search", "data structures", "two pointers"]
27
[{"input": "5\r\n1 3 1 1 4\r\n", "output": "5\r\n"}, {"input": "5\r\n1 3 2 1 4\r\n", "output": "4\r\n"}, {"input": "3\r\n4 1 2\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 3 5 4 5\r\n", "output": "9\r\n"}]
false
stdio
null
true
1006/C
1006
C
PyPy 3
TESTS
20
280
19,148,800
143749589
n=int(input()) a=list(map(int,input().split())) low=0 high=n-1 lowsum=a[low] highsum=a[high] res=0 while high-low>1: if lowsum==highsum: res=max(res,lowsum) low+=1 lowsum+=a[low] elif lowsum<highsum: low+=1 lowsum+=a[low] else: high-=1 highsum+=a[high] if highsum==lowsum: res=max(res,lowsum) print(res)
27
109
23,654,400
216909739
n = int(input()) lista = list(map(int, input().split(" "))) pont_1 = 0 pont_2 = len(lista) - 1 valor_1 = lista[pont_1] valor_2 = lista[pont_2] value = 0 while (pont_1 < pont_2): if (valor_1 < valor_2): pont_1 += 1 valor_1 += lista[pont_1] elif (valor_1 > valor_2): pont_2 -= 1 valor_2 += lista[pont_2] else: value = valor_1 pont_1 += 1 valor_1 += lista[pont_1] print(value)
Codeforces Round 498 (Div. 3)
ICPC
2,018
1
256
Three Parts of the Array
You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible. More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then: $$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$ The sum of an empty array is $$$0$$$. Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.
Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).
null
In the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$. In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$. In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.
[{"input": "5\n1 3 1 1 4", "output": "5"}, {"input": "5\n1 3 2 1 4", "output": "4"}, {"input": "3\n4 1 2", "output": "0"}]
1,200
["binary search", "data structures", "two pointers"]
27
[{"input": "5\r\n1 3 1 1 4\r\n", "output": "5\r\n"}, {"input": "5\r\n1 3 2 1 4\r\n", "output": "4\r\n"}, {"input": "3\r\n4 1 2\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 3 5 4 5\r\n", "output": "9\r\n"}]
false
stdio
null
true
1006/C
1006
C
Python 3
TESTS
20
265
18,432,000
90410495
n=int(input()) a=list(map(int,input().split())) p1=0 p2=n-1 ap1=0 ap2=0 ap1+=a[p1] ap2+=a[p2] l=[] while True: if p1>=p2: break if ap1>ap2: p2-=1 if p1>=p2: break ap2+=a[p2] elif ap2>ap1: p1+=1 if p1>=p2: break ap1+=a[p1] elif ap1==ap2: l.append(ap1) p1+=1 p2-=1 if p1>=p2: break ap1+=a[p1] ap2+=a[p2] if ap1==ap2 : print(ap1) elif len(l)!=0: print(max(l)) else: print(0)
27
109
27,136,000
163954629
from msvcrt import LK_LOCK n = int(input()) lst =list(map(int, input().split())) s1 = s2 = 0 r = n ans = 0 for l in range(len(lst)): s1 += lst[l] while s2 < s1: r -= 1 s2 += lst[r] if s1 == s2 and r > l: ans = max(ans, s1) print(ans)
Codeforces Round 498 (Div. 3)
ICPC
2,018
1
256
Three Parts of the Array
You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible. More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then: $$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$ The sum of an empty array is $$$0$$$. Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.
Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).
null
In the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$. In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$. In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.
[{"input": "5\n1 3 1 1 4", "output": "5"}, {"input": "5\n1 3 2 1 4", "output": "4"}, {"input": "3\n4 1 2", "output": "0"}]
1,200
["binary search", "data structures", "two pointers"]
27
[{"input": "5\r\n1 3 1 1 4\r\n", "output": "5\r\n"}, {"input": "5\r\n1 3 2 1 4\r\n", "output": "4\r\n"}, {"input": "3\r\n4 1 2\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 3 5 4 5\r\n", "output": "9\r\n"}]
false
stdio
null
true
504/D
504
D
Python 3
TESTS
0
31
0
153502837
n = int(input()) arr = [] basis = [] for i in range(n): x = int(input()) arr.append(x) ans = [] for e in basis: if (arr[e]^x) < x: ans.append(e) x ^= arr[e] if x == 0: print(len(ans)) print(*ans) else: print(0) arr[i] = x; basis.append(i)
52
1,044
11,366,400
223656011
m = int(input()) arr = [] bits = [] for i in range(m): x = int(input()) bit = 0 for j in range(len(arr)): p = arr[j] ^ x if p < x: x = p bit ^= bits[j] if x == 0: ans = "" r = 0 for j in range(i): if bit & (1 << j) == 1 << j: r += 1 ans += str(j) + " " print(str(r) + " " + ans) else: print(0) arr.append(x) bits.append(bit ^ (1 << i))
Codeforces Round 285 (Div. 1)
CF
2,015
2
256
Misha and XOR
After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number x to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals x? If the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket. Initially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number 0, the second integer takes number 1 and so on. Misha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him.
The first line contains number m (1 ≤ m ≤ 2000), showing how many numbers are scattered around the room. The next m lines contain the numbers in the order in which the robot puts them in the basket. Each number is a positive integer strictly less than 10600 that doesn't contain leading zeroes.
For each number either print a 0 on the corresponding line, if the number cannot be represented as a XOR sum of numbers that are in the basket, or print integer k showing how many numbers are in the representation and the indexes of these numbers. Separate the numbers by spaces. Each number can occur in the representation at most once.
null
The XOR sum of numbers is the result of bitwise sum of numbers modulo 2.
[{"input": "7\n7\n6\n5\n4\n3\n2\n1", "output": "0\n0\n0\n3 0 1 2\n2 1 2\n2 0 2\n2 0 1"}, {"input": "2\n5\n5", "output": "0\n1 0"}]
2,700
["bitmasks"]
52
[{"input": "7\r\n7\r\n6\r\n5\r\n4\r\n3\r\n2\r\n1\r\n", "output": "0\r\n0\r\n0\r\n3 0 1 2\r\n2 1 2\r\n2 0 2\r\n2 0 1\r\n"}, {"input": "2\r\n5\r\n5\r\n", "output": "0\r\n1 0\r\n"}, {"input": "10\r\n81\r\n97\r\n12\r\n2\r\n16\r\n96\r\n80\r\n99\r\n6\r\n83\r\n", "output": "0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n3 0 1 5\r\n2 1 3\r\n0\r\n2 0 3\r\n"}, {"input": "10\r\n15106\r\n13599\r\n69319\r\n33224\r\n26930\r\n94490\r\n85089\r\n60931\r\n23137\r\n62868\r\n", "output": "0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n"}, {"input": "10\r\n5059464500\r\n8210395556\r\n3004213265\r\n248593357\r\n5644084048\r\n9359824793\r\n8120649160\r\n4288978422\r\n183848555\r\n8135845959\r\n", "output": "0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n0\r\n"}, {"input": "10\r\n4\r\n12\r\n28\r\n29\r\n31\r\n31\r\n31\r\n31\r\n31\r\n31\r\n", "output": "0\r\n0\r\n0\r\n0\r\n0\r\n1 4\r\n1 4\r\n1 4\r\n1 4\r\n1 4\r\n"}, {"input": "10\r\n16\r\n24\r\n28\r\n30\r\n31\r\n31\r\n31\r\n31\r\n31\r\n31\r\n", "output": "0\r\n0\r\n0\r\n0\r\n0\r\n1 4\r\n1 4\r\n1 4\r\n1 4\r\n1 4\r\n"}, {"input": "10\r\n16\r\n8\r\n4\r\n2\r\n1\r\n31\r\n31\r\n31\r\n31\r\n31\r\n", "output": "0\r\n0\r\n0\r\n0\r\n0\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n"}, {"input": "10\r\n1\r\n2\r\n4\r\n8\r\n16\r\n31\r\n31\r\n31\r\n31\r\n31\r\n", "output": "0\r\n0\r\n0\r\n0\r\n0\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n5 0 1 2 3 4\r\n"}]
false
stdio
null
true
505/B
505
B
PyPy 3
TESTS
5
124
4,403,200
104060110
import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 #def input(): return sys.stdin.readline().strip() input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) ilelec = lambda: map(int1,input().split()) alelec = lambda: list(map(int1, input().split())) def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) n,m = ilele() Color = defaultdict(set) G = defaultdict(set) C = set() def addEdge(a,b): G[a].add(b) G[b].add(a) def addColor(a,b,c): Color[(a,b)].add(c) Color[(b,a)].add(c) C.add(c) for i in range(m): a,b,c = ilele() addColor(a,b,c) addEdge(a,b) vis = [False]*(n+1) Ans = [] def fun(node,dest,vis,grp): #print(node,vis,grp) if not grp: return if node == dest: for i in grp: Ans.append(i) return vis[node] = True for i in G.get(node,[]): #print(i) if not vis[i]: newvis = vis.copy() #newvis[c] =True z = grp.intersection(Color[node,i]) #print(z) fun(i,dest,newvis,z) #print(Color,G) for i in range(int(input())): a,b = ilele() vis = [False]*(n+1) grp = C.copy() fun(a,b,vis,grp) #print(Ans) print(len(Ans)) Ans =[]
29
61
0
172115626
def checkcolors(a, b, c, v) : colorset = set() if c == 0 : for edge in edges[a] : if edge[0] == b : v[edge[0]].append(edge[1]) colorset.add(edge[1]) else : if c not in v[edge[0]] : v[edge[0]].append(edge[1]) colorset.update(checkcolors(edge[0],b,edge[1], v)) else : for edge in edges[a] : if edge[0] == b and edge[1] == c : v[edge[0]].append(edge[1]) colorset.add(edge[1]) elif edge[1] == c : if c not in v[edge[0]] : v[edge[0]].append(edge[1]) colorset.update(checkcolors(edge[0],b,c, v)) return colorset n, m = list(map(int, input().split())) edges = [] for i in range(n+1) : edges.append([]) for i in range(m) : a, b, c = list(map(int, input().split())) edges[a].append([b, c]) edges[b].append([a, c]) q = int(input()) for i in range(q) : a, b = list(map(int, input().split())) v = [] for i in range(n+1) : v.append([]) colornum = checkcolors(a, b, 0, v) print(len(colornum))
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
505/B
505
B
Python 3
TESTS
5
46
307,200
221461063
from collections import defaultdict def main(): graph = defaultdict(set) n, m = map(int, input().split()) for _ in range(m): a, b, c = map(int, input().split()) graph[a].add((b, c)) graph[b].add((a, c)) def dfs(node, prev_color, target, used): if node == target: yield 1 return for nn, color in graph[node]: if (prev_color is None or color == prev_color) and nn not in used : used.add(nn) yield from dfs(nn, color, target, used) used.discard(nn) q = int(input()) for _ in range(q): u, v = map(int, input().split()) ans = 0 for i in dfs(u, None, v, {u}): ans += i print(ans) if __name__ == "__main__": main()
29
62
0
9461646
n,m = map(int, input().split()) l = [] for i in range(m): a,b,c = map(int, input().split()) if len(l) <= c-1: for i in range(c-len(l)): l.append([]) p = l[c-1] m = [] for i in range(len(p)): if a in p[i] or b in p[i]: m.append(i) new = [a,b] for i in range(len(m)): new = new + p[m[i]] for i in range(len(m)): p.pop(m[i]-i) p.append(new) l[c-1] = p q = int(input()) for i in range(q): counter = 0 u,v = map(int, input().split()) for j in range(len(l)): yes = 0 for k in range(len(l[j])): if yes == 0 and u in l[j][k] and v in l[j][k]: yes = 1 counter += 1 print(counter)
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
505/B
505
B
PyPy 3-64
TESTS
5
77
3,276,800
222044409
def solve(): n,m = map(int,input().split()) adj = [[]for i in range(n)] for i in range(m): a,b,c = map(int,input().split()) adj[a-1].append((b-1,c-1)) adj[b-1].append((a-1,c-1)) def dfs(s,d,adj,visited,color): if s==d: return True visited[s] = True for i,j in adj[s]: if not visited[i] and j==color: if dfs(i,d,adj,visited,color): return True return False q = int(input()) for i in range(q): a,b = map(int,input().split()) ans = 0 for j,k in adj[a-1]: visited = [False]*n visited[a-1]=True if dfs(j,b-1,adj,visited,k): ans+=1 print(ans) # number of test cases #t = int(input()) t = 1 for i in range(t): solve()
29
62
0
184160064
n, m = map(int, input().split()) graph = [[] for _ in range(105)] for _ in range(m): a, b, c = map(int, input().split()) graph[a].append([b,c]) graph[b].append([a,c]) def dfs(source, destination, colour): if source == destination: return True visited[source] = True for node in graph[source]: if node[1] == colour and visited[node[0]] is False: if dfs(node[0], destination, colour): return True return False for i in range(int(input())): ans = 0 f, y = map(int ,input().split()) for colour in range(1, 101): visited = [False]*(n+1) if dfs(f, y, colour): ans += 1 print(ans)
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
505/B
505
B
PyPy 3-64
TESTS
5
78
6,451,200
144891730
n, m = map(int, input().split()) # vert, edge edges = [tuple(map(int, input().split())) for _ in range(m)] def search(a, b, c): global count if a == b: count += 1 return if c != -1: visited[c].add(a) for e in edges: if e[2] == c or c == -1: if e[0] == a and (e[1] not in visited[c]): search(e[1], b, e[2]) elif e[1] == a and (e[0] not in visited[c]): search(e[0], b, e[2]) for _ in range(int(input())): a, b = map(int, input().split()) global count count = 0 global visited visited = [set([a]) for i in range(115)] search(a, b, -1) print(count)
29
62
102,400
9460278
n,m = input().split(' ') l = [] for x in range(int(m)): l.append(list(range(int(n)))) for x in range(int(m)): p = input().split(' ') newl = l[int(p[2])-1] a,i = max(newl[int(p[0])-1],newl[int(p[1])-1]),min(newl[int(p[0])-1],newl[int(p[1])-1]) for y in range(len(newl)): if newl[y] == a: newl[y] = i l[int(p[2])-1] = newl q = int(input()) put = [] for x in range(q): out = 0 a,b = input().split(' ') for n in l: if n[int(a)-1] == n[int(b)-1]: out += 1 put.append(out) for x in put: print(x)
Codeforces Round 286 (Div. 2)
CF
2,015
1
256
Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers — ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
null
Let's consider the first sample. The figure above shows the first sample. - Vertex 1 and vertex 2 are connected by color 1 and 2. - Vertex 3 and vertex 4 are connected by color 3. - Vertex 1 and vertex 4 are not connected by any single color.
[{"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4", "output": "2\n1\n0"}, {"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4", "output": "1\n1\n1\n1\n2"}]
1,400
["dfs and similar", "dp", "dsu", "graphs"]
29
[{"input": "4 5\r\n1 2 1\r\n1 2 2\r\n2 3 1\r\n2 3 3\r\n2 4 3\r\n3\r\n1 2\r\n3 4\r\n1 4\r\n", "output": "2\r\n1\r\n0\r\n"}, {"input": "5 7\r\n1 5 1\r\n2 5 1\r\n3 5 1\r\n4 5 1\r\n1 2 2\r\n2 3 2\r\n3 4 2\r\n5\r\n1 5\r\n5 1\r\n2 5\r\n1 5\r\n1 4\r\n", "output": "1\r\n1\r\n1\r\n1\r\n2\r\n"}, {"input": "2 1\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "1\r\n"}, {"input": "2 3\r\n1 2 3\r\n1 2 2\r\n1 2 1\r\n1\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 5\r\n1 2 1\r\n1 2 2\r\n1 2 3\r\n1 2 4\r\n1 2 5\r\n1\r\n1 2\r\n", "output": "5\r\n"}]
false
stdio
null
true
1006/C
1006
C
PyPy 3-64
TESTS
11
124
26,521,600
213104137
n = int(input()) l = list(int(num) for num in input().split()) i,j = 0,n-1 actual,rightsum,leftsum=0,0,0 while True: if i>=j: if leftsum==rightsum: actual=leftsum break if leftsum==rightsum : actual=leftsum leftsum+=l[i] rightsum+=l[j] i+=1 j-=1 continue if leftsum<rightsum : leftsum+=l[i] i+=1 continue if rightsum<leftsum : rightsum+=l[j] j-=1 continue print(actual)
27
109
27,545,600
183157150
n = int(input()) d = list(map(int, input().split())) i = 0 j = n-1 s = d[i] f = d[j] c = 0 while i<j: if s<f: i = i + 1 s = s + d[i] elif s>f: j = j - 1 f = f + d[j] else: i = i + 1 j = j - 1 c = c + s s = d[i] f = d[j] print(c)
Codeforces Round 498 (Div. 3)
ICPC
2,018
1
256
Three Parts of the Array
You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible. More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then: $$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$ The sum of an empty array is $$$0$$$. Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.
Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).
null
In the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$. In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$. In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.
[{"input": "5\n1 3 1 1 4", "output": "5"}, {"input": "5\n1 3 2 1 4", "output": "4"}, {"input": "3\n4 1 2", "output": "0"}]
1,200
["binary search", "data structures", "two pointers"]
27
[{"input": "5\r\n1 3 1 1 4\r\n", "output": "5\r\n"}, {"input": "5\r\n1 3 2 1 4\r\n", "output": "4\r\n"}, {"input": "3\r\n4 1 2\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 3 5 4 5\r\n", "output": "9\r\n"}]
false
stdio
null
true
1006/C
1006
C
PyPy 3-64
TESTS
11
109
28,262,400
205240901
import math,sys,collections,bisect,heapq def natural(n): return n*(n+1)//2 def possible(arr,h,k): for i in range(len(arr)-1): if h <= 0: return True h-=min(arr[i+1]-arr[i],k) h-=k if h <=0: return True return False def binarysearch(l,r,arr,h): if l<=r: mid = (l+r)//2 if possible(arr,h,mid): return binarysearch(l,mid-1,arr,h) return binarysearch(mid+1,r,arr,h) return l def binarysearch2(l,r,k,st): if l<=r: mid = (l+r)//2 if mid-st+1==k: return mid elif mid-st+1<k: return binarysearch2(mid+1,r,k,st) return binarysearch2(l,mid-1,k,st) return -1 def ispossible(n): h = 1 num = 2 pre = 2 while num<=n: pre = num h+=1 num+=(h*2)+h-1 return n-pre def cal(n): tmp = 0 while n: tmp+=n%10 n//=10 return tmp def solve(): n = int(input()) arr = list(map(int,input().split())) l = 0 r = n-1 s1 = 0 s2 = 0 m = 0 while l<r: if s1 == s2: m = s1 s1+=arr[l] s2+=arr[r] l+=1 r-=1 elif s1<s2: s1+=arr[l] l+=1 else: s2+=arr[r] r-=1 if s1 == s2: m = s1 print(m) # number of test cases #t = int(input()) t = 1 for i in range(t): solve()
27
109
27,648,000
183810469
n = int(input()) li = list(map(int, input().split())) i = 0 j = n-1 s1 = li[0] s2 = li[n-1] res = 0 while i < j: if s1 > s2: j -= 1 s2 += li[j] elif s1 < s2: i += 1 s1 += li[i] else: res = s1 i += 1 s1 += li[i] print(res)
Codeforces Round 498 (Div. 3)
ICPC
2,018
1
256
Three Parts of the Array
You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible. More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then: $$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$ The sum of an empty array is $$$0$$$. Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.
Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).
null
In the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$. In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$. In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.
[{"input": "5\n1 3 1 1 4", "output": "5"}, {"input": "5\n1 3 2 1 4", "output": "4"}, {"input": "3\n4 1 2", "output": "0"}]
1,200
["binary search", "data structures", "two pointers"]
27
[{"input": "5\r\n1 3 1 1 4\r\n", "output": "5\r\n"}, {"input": "5\r\n1 3 2 1 4\r\n", "output": "4\r\n"}, {"input": "3\r\n4 1 2\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 3 5 4 5\r\n", "output": "9\r\n"}]
false
stdio
null
true
1006/C
1006
C
Python 3
TESTS
12
233
17,715,200
155058386
number = int(input()) numbers = list(map(int,input().split())) e1 = 0 e2 = 1 sum1 = numbers[0] sum3 = numbers[len(numbers) - 1] b = -2 a = 1 count = 1 for c in range(1,len(numbers) - 1): if sum1 < sum3: sum1 += numbers[a] a += 1 elif sum1 > sum3: sum3 += numbers[b] b -= 1 else: sum1 += numbers[a] a += 1 if sum1 == sum3: e1 = sum1 e2 = sum3 count += 1 if count == len(numbers): break if sum1 == sum3: print(sum1) elif e1 == e2: print(e1) else: print(0)
27
109
27,648,000
186685382
n=int(input()) A=list(map(int,input().split())) ANS=0 l=0 r=n-1 S0=0 S1=0 while l<=r: if S0<=S1: S0+=A[l] l+=1 else: S1+=A[r] r-=1 if S0==S1: ANS=max(ANS,S0) print(ANS)
Codeforces Round 498 (Div. 3)
ICPC
2,018
1
256
Three Parts of the Array
You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible. More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then: $$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$ The sum of an empty array is $$$0$$$. Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.
Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).
null
In the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$. In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$. In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.
[{"input": "5\n1 3 1 1 4", "output": "5"}, {"input": "5\n1 3 2 1 4", "output": "4"}, {"input": "3\n4 1 2", "output": "0"}]
1,200
["binary search", "data structures", "two pointers"]
27
[{"input": "5\r\n1 3 1 1 4\r\n", "output": "5\r\n"}, {"input": "5\r\n1 3 2 1 4\r\n", "output": "4\r\n"}, {"input": "3\r\n4 1 2\r\n", "output": "0\r\n"}, {"input": "1\r\n1000000000\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 3 5 4 5\r\n", "output": "9\r\n"}]
false
stdio
null
true
617/C
617
C
Python 3
TESTS
4
30
102,400
224677091
import math def disq(a, b): deltax = abs(a[0] - b[0]) deltay = abs(a[1] - b[1]) result = deltax * deltax + deltay * deltay return result def main(): a, b, c, d, e = input().split() n = int(a) f1 = tuple(map(int, [b, c])) f2 = tuple(map(int, [d, e])) flowers = [] for _ in range(n): tmp = tuple(map(int, input().split())) ddone = disq(tmp, f1) ddtwo = disq(tmp, f2) flowers.append((tmp, (ddone, ddtwo))) flowers.sort(key=lambda x: min(x[1][0], x[1][1]), reverse=True) covered = set() r1sq = 0 r2sq = 0 for flower in flowers: if flower[0] in covered: continue covered.add(flower[0]) newr1sq = max(r1sq, flower[1][0]) newr2sq = max(r2sq, flower[1][1]) if newr1sq + r2sq < newr2sq + r1sq: r1sq = newr1sq else: r2sq = newr2sq for f in flowers: if disq(f[0], f1) < r1sq and disq(f[0], f2) < r2sq: covered.add(f[0]) print(r1sq + r2sq) if __name__ == "__main__": main()
31
77
409,600
15535367
def dist1(x_, y_): return (x1 - x_) ** 2 + (y1 - y_) ** 2 def dist2(x_, y_): return (x2 - x_) ** 2 + (y2 - y_) ** 2 n, x1, y1, x2, y2 = [int(i) for i in input().split()] dist = [[0] * 2 for i in range(n)] for i in range(n): x, y = [int(i) for i in input().split()] dist[i][0] = dist1(x, y) dist[i][1] = dist2(x, y) dist.sort() now1 = 0 now2 = 0 lel = 0 for i in range(n): lel = max(lel, dist[i][1]) ans = lel mx = [0] * n mx[n - 1] = 0 for i in range(n - 2, -1, -1): mx[i] = max(mx[i + 1], dist[i + 1][1]) for i in range(n - 1, -1, -1): now1 = dist[i][0] now2 = mx[i] if now1 + now2 < ans: ans = now1 + now2 print(ans)
Codeforces Round 340 (Div. 2)
CF
2,016
2
256
Watering Flowers
A flowerbed has many flowers and two fountains. You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains. You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.
The first line of the input contains integers n, x1, y1, x2, y2 (1 ≤ n ≤ 2000, - 107 ≤ x1, y1, x2, y2 ≤ 107) — the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≤ xi, yi ≤ 107) — the coordinates of the i-th flower. It is guaranteed that all n + 2 points in the input are distinct.
Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.
null
The first sample is (r12 = 5, r22 = 1): The second sample is (r12 = 1, r22 = 32):
[{"input": "2 -1 0 5 3\n0 2\n5 2", "output": "6"}, {"input": "4 0 0 5 0\n9 4\n8 3\n-1 0\n1 4", "output": "33"}]
1,600
["implementation"]
31
[{"input": "2 -1 0 5 3\r\n0 2\r\n5 2\r\n", "output": "6\r\n"}, {"input": "4 0 0 5 0\r\n9 4\r\n8 3\r\n-1 0\r\n1 4\r\n", "output": "33\r\n"}, {"input": "5 -6 -4 0 10\r\n-7 6\r\n-9 7\r\n-5 -1\r\n-2 1\r\n-8 10\r\n", "output": "100\r\n"}, {"input": "10 -68 10 87 22\r\n30 89\r\n82 -97\r\n-52 25\r\n76 -22\r\n-20 95\r\n21 25\r\n2 -3\r\n45 -7\r\n-98 -56\r\n-15 16\r\n", "output": "22034\r\n"}, {"input": "1 -10000000 -10000000 -10000000 -9999999\r\n10000000 10000000\r\n", "output": "799999960000001\r\n"}]
false
stdio
null
true
62/D
62
D
Python 3
TESTS
4
62
0
139385636
def build_home_path(n: int, m: int, old_path: list) -> list: """ Parameters: :n (int): number of rooms :m (int): number of corridors :old_path (list): old build path :return: new build path """ if old_path[0] != 1: return None for i in reversed(range(len(old_path) - 2)): for j in range(i + 1, len(old_path)): if old_path[i] == old_path[j] and old_path[i + 1] < old_path[j - 1]: return old_path[:i] + old_path[i:j + 1][::-1] + old_path[j + 1:] return None n, m = map(int,input().split()) p = list(map(int,input().split())) res = build_home_path(n,m,p) if res is None: print("No solution") else: print(" ".join(str(x) for x in res))
30
124
819,200
187019306
n,m = map(int,input().split()) m+=1 p = list(map(lambda x:int(x)-1,input().split())) a = [0]*m q = [[False]*n for i in range(n)] d = [[] for i in range(n)] for i in range(1,m): d[p[i]].append(p[i-1]) d[p[i-1]].append(p[i]) for i in range(n): d[i].sort() s = [(p[0],True,p[0])] l = 0 while s: v,f,vv = s[-1] if f is None: s.pop() l-=1 q[vv][v]=q[v][vv]=False continue q[vv][v]=q[v][vv]=True s[-1]=(v,None,vv) a[l]=v l+=1 if l==m: if f: continue else: break for u in reversed(d[v]): if f and u<p[l]: continue if q[u][v]: continue s.append((u,f and u==p[l],v)) if s: print(' '.join(map(lambda x:str(x+1),a))) else: print("No solution")
Codeforces Beta Round 58
CF
2,011
2
256
Wormhouse
Arnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from 1 to n. All the corridors are bidirectional. Arnie wants the new house to look just like the previous one. That is, it should have exactly n rooms and, if a corridor from room i to room j existed in the old house, it should be built in the new one. We know that during the house constructing process Arnie starts to eat an apple starting from some room and only stops when he eats his way through all the corridors and returns to the starting room. It is also known that Arnie eats without stopping. That is, until Arnie finishes constructing the house, he is busy every moment of his time gnawing a new corridor. Arnie doesn't move along the already built corridors. However, gnawing out corridors in one and the same order any time you change a house is a very difficult activity. That's why Arnie, knowing the order in which the corridors were located in the previous house, wants to gnaw corridors in another order. It is represented as a list of rooms in the order in which they should be visited. The new list should be lexicographically smallest, but it also should be strictly lexicographically greater than the previous one. Help the worm.
The first line contains two integers n and m (3 ≤ n ≤ 100, 3 ≤ m ≤ 2000). It is the number of rooms and corridors in Arnie's house correspondingly. The next line contains m + 1 positive integers that do not exceed n. They are the description of Arnie's old path represented as a list of rooms he visited during the gnawing. It is guaranteed that the last number in the list coincides with the first one. The first room described in the list is the main entrance, that's why Arnie should begin gnawing from it. You may assume that there is no room which is connected to itself and there is at most one corridor between any pair of rooms. However, it is possible to find some isolated rooms which are disconnected from others.
Print m + 1 positive integers that do not exceed n. Those numbers are the description of the new path, according to which Arnie should gnaw out his new house. If it is impossible to find new path you should print out No solution. The first number in your answer should be equal to the last one. Also it should be equal to the main entrance.
null
null
[{"input": "3 3\n1 2 3 1", "output": "1 3 2 1"}, {"input": "3 3\n1 3 2 1", "output": "No solution"}]
2,300
["dfs and similar", "graphs"]
30
[{"input": "3 3\r\n1 2 3 1\r\n", "output": "1 3 2 1 "}, {"input": "3 3\r\n1 3 2 1\r\n", "output": "No solution"}, {"input": "4 4\r\n1 2 4 3 1\r\n", "output": "1 3 4 2 1 "}, {"input": "6 7\r\n3 2 4 1 6 5 1 3\r\n", "output": "No solution"}, {"input": "8 12\r\n4 6 5 1 4 3 1 8 3 7 8 5 4\r\n", "output": "4 6 5 1 4 3 1 8 7 3 8 5 4 "}, {"input": "5 6\r\n3 4 1 2 5 1 3\r\n", "output": "3 4 1 5 2 1 3 "}, {"input": "7 9\r\n3 2 7 3 5 1 2 6 1 3\r\n", "output": "3 2 7 3 5 1 6 2 1 3 "}, {"input": "6 7\r\n1 5 6 1 4 3 2 1\r\n", "output": "1 6 5 1 2 3 4 1 "}, {"input": "4 3\r\n1 2 3 1\r\n", "output": "1 3 2 1 "}, {"input": "10 40\r\n10 3 8 4 10 2 8 1 2 6 3 5 7 6 10 8 9 7 8 5 4 9 1 3 7 2 5 10 9 2 4 3 9 6 5 1 4 6 1 7 10\r\n", "output": "10 3 8 4 10 2 8 1 2 6 3 5 7 6 10 8 9 7 8 5 4 9 1 3 7 2 5 10 9 2 4 3 9 6 5 1 6 4 1 7 10 "}]
false
stdio
null
true
508/C
508
C
PyPy 3-64
TESTS
0
46
0
214291416
def num_candles(m, t, r, times): N = 301 x = [0]*N y = [0]*N answer = 0 for i in range(m): x[times[i]] = 1 for i in range(1, N): if x[i] and y[i] < r: for j in range(i-r+y[i]+1, i+1): for k in range(max(j,0), min(j+t,N)): y[k] += 1 answer += 1 if y[i] < r: return -1 return answer m,t,r = map(int,input().split()) print(num_candles(m, t, r, list(map(int,input().split()))))
61
77
0
9587004
m, t, r = map(int, input().split()) w = list(map(int, input().split())) w.sort() cur = set() cur1 = set() cnt = 0 for i in range(m): for j in cur: if j + t >= w[i]: cur1.add(j) cur = set() for j in cur1: cur.add(j) cur1 = set() j = w[i] - 1 while j >= w[i] - t and len(cur) < r: if not j in cur: cur.add(j) cnt += 1 j -= 1 if len(cur) < r: print(-1) exit() print(cnt)
Codeforces Round 288 (Div. 2)
CF
2,015
2
256
Anya and Ghosts
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used. For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second. What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers wi (1 ≤ i ≤ m, 1 ≤ wi ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that. If that is impossible, print - 1.
null
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit. It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively. In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight. In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight. In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
[{"input": "1 8 3\n10", "output": "3"}, {"input": "2 10 1\n5 8", "output": "1"}, {"input": "1 1 3\n10", "output": "-1"}]
1,600
["constructive algorithms", "greedy"]
61
[{"input": "1 8 3\r\n10\r\n", "output": "3\r\n"}, {"input": "2 10 1\r\n5 8\r\n", "output": "1\r\n"}, {"input": "1 1 3\r\n10\r\n", "output": "-1\r\n"}, {"input": "21 79 1\r\n13 42 51 60 69 77 94 103 144 189 196 203 210 215 217 222 224 234 240 260 282\r\n", "output": "4\r\n"}, {"input": "125 92 2\r\n1 2 3 4 5 7 8 9 10 12 17 18 20 21 22 23 24 25 26 28 30 32 33 34 35 36 37 40 41 42 43 44 45 46 50 51 53 54 55 57 60 61 62 63 69 70 74 75 77 79 80 81 82 83 84 85 86 88 89 90 95 96 98 99 101 103 105 106 107 108 109 110 111 112 113 114 118 119 120 121 122 123 124 126 127 128 129 130 133 134 135 137 139 141 143 145 146 147 148 149 150 151 155 157 161 162 163 165 166 167 172 173 174 176 177 179 181 183 184 185 187 188 189 191 194\r\n", "output": "6\r\n"}, {"input": "42 100 2\r\n55 56 57 58 60 61 63 66 71 73 75 76 77 79 82 86 87 91 93 96 97 98 99 100 101 103 108 109 111 113 114 117 119 122 128 129 134 135 137 141 142 149\r\n", "output": "2\r\n"}, {"input": "31 23 2\r\n42 43 44 47 48 49 50 51 52 56 57 59 60 61 64 106 108 109 110 111 114 115 116 117 118 119 120 123 126 127 128\r\n", "output": "6\r\n"}, {"input": "9 12 4\r\n1 2 3 4 5 7 8 9 10\r\n", "output": "5\r\n"}, {"input": "9 16 2\r\n1 2 3 4 6 7 8 9 10\r\n", "output": "2\r\n"}, {"input": "7 17 3\r\n1 3 4 5 7 9 10\r\n", "output": "3\r\n"}, {"input": "1 1 1\r\n4\r\n", "output": "1\r\n"}, {"input": "9 1 3\r\n1 2 4 5 6 7 8 9 10\r\n", "output": "-1\r\n"}, {"input": "9 10 4\r\n1 2 3 4 5 6 8 9 10\r\n", "output": "7\r\n"}, {"input": "7 2 2\r\n1 2 3 4 6 7 9\r\n", "output": "10\r\n"}, {"input": "5 3 3\r\n1 4 5 6 10\r\n", "output": "11\r\n"}, {"input": "9 7 1\r\n2 3 4 5 6 7 8 9 10\r\n", "output": "2\r\n"}, {"input": "8 18 3\r\n2 3 4 5 6 7 8 9\r\n", "output": "3\r\n"}, {"input": "88 82 36\r\n16 17 36 40 49 52 57 59 64 66 79 80 81 82 87 91 94 99 103 104 105 112 115 117 119 122 123 128 129 134 135 140 146 148 150 159 162 163 164 165 166 168 171 175 177 179 181 190 192 194 196 197 198 202 203 209 211 215 216 223 224 226 227 228 230 231 232 234 235 242 245 257 260 262 263 266 271 274 277 278 280 281 282 284 287 290 296 297\r\n", "output": "144\r\n"}, {"input": "131 205 23\r\n1 3 8 9 10 11 12 13 14 17 18 19 23 25 26 27 31 32 33 36 37 39 40 41 43 44 51 58 61 65 68 69 71 72 73 75 79 80 82 87 88 89 90 91 92 93 96 99 100 103 107 109 113 114 119 121 122 123 124 127 135 136 137 139 141 142 143 144 148 149 151 152 153 154 155 157 160 162 168 169 170 171 172 174 176 177 179 182 183 185 186 187 190 193 194 196 197 200 206 209 215 220 224 226 230 232 233 235 237 240 242 243 244 247 251 252 260 264 265 269 272 278 279 280 281 288 290 292 294 296 300\r\n", "output": "46\r\n"}, {"input": "45 131 15\r\n14 17 26 31 32 43 45 56 64 73 75 88 89 93 98 103 116 117 119 123 130 131 135 139 140 153 156 161 163 172 197 212 217 230 232 234 239 240 252 256 265 266 272 275 290\r\n", "output": "45\r\n"}, {"input": "63 205 38\r\n47 50 51 54 56 64 67 69 70 72 73 75 78 81 83 88 91 99 109 114 118 122 136 137 138 143 146 147 149 150 158 159 160 168 171 172 174 176 181 189 192 195 198 201 204 205 226 232 235 238 247 248 253 254 258 260 270 276 278 280 282 284 298\r\n", "output": "76\r\n"}, {"input": "44 258 19\r\n3 9 10 19 23 32 42 45 52 54 65 66 69 72 73 93 108 116 119 122 141 150 160 162 185 187 199 205 206 219 225 229 234 235 240 242 253 261 264 268 275 277 286 295\r\n", "output": "38\r\n"}, {"input": "138 245 30\r\n3 5 6 8 9 13 15 16 19 20 24 25 27 29 30 32 33 34 35 36 37 38 40 42 47 51 52 53 55 56 58 59 63 66 67 68 69 72 73 74 75 77 78 80 81 82 85 86 87 89 91 93 95 96 99 100 102 104 105 108 110 111 112 117 122 124 125 128 129 131 133 136 139 144 145 146 147 148 149 151 153 155 156 159 162 163 164 165 168 174 175 176 183 191 193 194 195 203 204 205 206 211 216 217 218 219 228 229 230 235 237 238 239 242 244 248 249 250 252 253 255 257 258 260 264 265 266 268 270 271 272 277 278 280 285 288 290 291\r\n", "output": "60\r\n"}, {"input": "21 140 28\r\n40 46 58 67 71 86 104 125 129 141 163 184 193 215 219 222 234 237 241 246 263\r\n", "output": "56\r\n"}, {"input": "77 268 24\r\n2 6 15 18 24 32 35 39 41 44 49 54 59 63 70 73 74 85 90 91 95 98 100 104 105 108 114 119 120 125 126 128 131 137 139 142 148 150 151 153 155 158 160 163 168 171 175 183 195 198 202 204 205 207 208 213 220 224 230 239 240 244 256 258 260 262 264 265 266 272 274 277 280 284 291 299 300\r\n", "output": "48\r\n"}, {"input": "115 37 25\r\n1 3 6 8 10 13 14 15 16 17 20 24 28 32 34 36 38 40 41 45 49 58 59 60 62 63 64 77 79 80 85 88 90 91 97 98 100 101 105 109 111 112 114 120 122 123 124 128 132 133 139 144 145 150 151 152 154 155 158 159 160 162 164 171 178 181 182 187 190 191 192 193 194 196 197 198 206 207 213 216 219 223 224 233 235 238 240 243 244 248 249 250 251 252 254 260 261 262 267 268 270 272 273 275 276 278 279 280 283 286 288 289 292 293 300\r\n", "output": "224\r\n"}, {"input": "100 257 21\r\n50 56 57 58 59 60 62 66 71 75 81 84 86 90 91 92 94 95 96 97 100 107 110 111 112 114 115 121 123 125 126 127 129 130 133 134 136 137 147 151 152 156 162 167 168 172 176 177 178 179 181 182 185 186 188 189 190 191 193 199 200 201 202 205 209 213 216 218 220 222 226 231 232 235 240 241 244 248 249 250 252 253 254 256 257 258 260 261 263 264 268 270 274 276 278 279 282 294 297 300\r\n", "output": "35\r\n"}, {"input": "84 55 48\r\n8 9 10 12 14 17 22 28 31 33 36 37 38 40 45 46 48 50 51 58 60 71 73 74 76 77 78 82 83 87 88 90 92 96 98 99 103 104 105 108 109 111 113 117 124 125 147 148 149 152 156 159 161 163 169 170 171 177 179 180 185 186 190 198 199 201 254 256 259 260 261 262 264 267 273 275 280 282 283 286 288 289 292 298\r\n", "output": "296\r\n"}, {"input": "11 1 37\r\n18 48 50 133 141 167 168 173 188 262 267\r\n", "output": "-1\r\n"}, {"input": "48 295 12\r\n203 205 207 208 213 214 218 219 222 223 224 225 228 229 230 234 239 241 243 245 246 247 248 251 252 253 254 255 259 260 261 262 264 266 272 277 278 280 282 285 286 287 289 292 293 296 299 300\r\n", "output": "12\r\n"}, {"input": "2 3 1\r\n2 4\r\n", "output": "1\r\n"}, {"input": "2 3 1\r\n2 5\r\n", "output": "2\r\n"}, {"input": "2 2 2\r\n1 3\r\n", "output": "4\r\n"}, {"input": "2 2 2\r\n1 2\r\n", "output": "3\r\n"}, {"input": "2 1 2\r\n1 2\r\n", "output": "-1\r\n"}, {"input": "1 300 300\r\n1\r\n", "output": "300\r\n"}, {"input": "1 299 300\r\n300\r\n", "output": "-1\r\n"}]
false
stdio
null
true
975/A
975
A
Python 3
PRETESTS
3
77
9,011,200
37816785
n = int(input()) A = list(input().split()) cnt = 1 if n == 1: print(cnt) else: B = [set(i) for i in A] B = sorted(B) for i in range(1, len(B)): if B[i] != B[i - 1]: cnt += 1 print(cnt)
30
46
2,969,600
205469005
from sys import stdin from math import ceil rd = stdin.readline n = int(rd()) s = rd().split() s1 = [] for i in s: s2 = set(i) if s2 not in s1: s1.append(s2) print(len(s1))
Codeforces Round 478 (Div. 2)
CF
2,018
1
256
Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
null
In the first test, there are two objects mentioned. The roots that represent them are "a","ab". In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
[{"input": "5\na aa aaa ab abb", "output": "2"}, {"input": "3\namer arem mrea", "output": "1"}]
900
["implementation", "strings"]
30
[{"input": "5\r\na aa aaa ab abb\r\n", "output": "2"}, {"input": "3\r\namer arem mrea\r\n", "output": "1"}, {"input": "10\r\nbda bbb cda dca dda dcb bcd dcb ada ddd\r\n", "output": "6"}, {"input": "2\r\nfhjlqs aceginpr\r\n", "output": "2"}, {"input": "2\r\nbcdfghimn efghijlmo\r\n", "output": "2"}]
false
stdio
null
true
975/A
975
A
Python 3
TESTS
3
61
1,740,800
184349026
input() lst = [tuple(set(s)) for s in input().split()] print(len(set(lst)))
30
46
3,174,400
219500325
def get_root(word): return ''.join(sorted(set(word))) def count_unique_objects(n, words): unique_roots = set() for word in words: root = get_root(word) unique_roots.add(root) return len(unique_roots) n = int(input()) words = input().split() unique_objects = count_unique_objects(n, words) print(unique_objects)
Codeforces Round 478 (Div. 2)
CF
2,018
1
256
Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
null
In the first test, there are two objects mentioned. The roots that represent them are "a","ab". In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
[{"input": "5\na aa aaa ab abb", "output": "2"}, {"input": "3\namer arem mrea", "output": "1"}]
900
["implementation", "strings"]
30
[{"input": "5\r\na aa aaa ab abb\r\n", "output": "2"}, {"input": "3\r\namer arem mrea\r\n", "output": "1"}, {"input": "10\r\nbda bbb cda dca dda dcb bcd dcb ada ddd\r\n", "output": "6"}, {"input": "2\r\nfhjlqs aceginpr\r\n", "output": "2"}, {"input": "2\r\nbcdfghimn efghijlmo\r\n", "output": "2"}]
false
stdio
null
true
285/C
285
C
Python 3
TESTS
10
405
20,377,600
60349470
n = int(input()) x = list(map(int, input().split())) x.sort() cnt = 0 for i in range(n): if x[i] <= 0: cnt += 1 - x[i] x[i] = 1 elif x[i] >= n: cnt += x[i] - n x[i] = n for j in range(n): if x[j] < j + 1: cnt += j + 1 - x[j] x[j] = j + 1 print(cnt + n - len(set(x)))
33
187
36,966,400
178866041
def main(): n = int(input()) elems = list(sorted(map(int, input().split(" ")))) result = 0 i = 1 for x in elems: result += abs(x - i) if x >= 1 else (abs(x) + i) i += 1 print(result) if __name__ == "__main__": main()
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
285/C
285
C
Python 3
TESTS
8
280
15,974,400
40677262
n, fine, sum_ = int(input()), 0, 0 for a in map(int, input().split()): if a < 1: fine, sum_ = fine - a + 1, sum_ + 1 elif a > n: fine, sum_ = fine + a - n, sum_ + n else: sum_ += a print(fine + abs(n * (n + 1) // 2 - sum_))
33
187
44,134,400
169970868
t=int(input()) # n,a,b,c=map(int,input().split()) # s=input() arr=list(map(int,input().split())) # s=list(map(int,input())) # mat=[input() for i in range(4)] val=[i for i in range(1,t+1)] arr.sort() sum=0 for i in range(t): sum+=abs(arr[i]-val[i]) print(sum)
Codeforces Round 175 (Div. 2)
CF
2,013
1
256
Building Permutation
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1). In the second sample you need 6 moves to build permutation (1, 3, 2).
[{"input": "2\n3 0", "output": "2"}, {"input": "3\n-1 -1 2", "output": "6"}]
1,200
["greedy", "implementation", "sortings"]
33
[{"input": "2\r\n3 0\r\n", "output": "2\r\n"}, {"input": "3\r\n-1 -1 2\r\n", "output": "6\r\n"}, {"input": "5\r\n-3 5 -3 3 3\r\n", "output": "10\r\n"}, {"input": "10\r\n9 6 -2 4 1 1 1 9 6 2\r\n", "output": "18\r\n"}, {"input": "9\r\n2 0 0 6 5 4 1 9 3\r\n", "output": "15\r\n"}]
false
stdio
null
true
975/A
975
A
Python 3
PRETESTS
3
78
9,011,200
37807721
n = int(input()) inputs = input() inlst = list(map(str, inputs.split(" "))) uniqe = [] for i in range(n): uniq = set(inlst[i]) uniqe.append(str(uniq)) objects = len(set(uniqe)) print(objects)
30
46
7,577,600
161874996
n=int(input()) listx=input().split(' ') d=[] for x in listx: x=set(x) if x not in d: d.append(x) print(len(d))
Codeforces Round 478 (Div. 2)
CF
2,018
1
256
Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
null
In the first test, there are two objects mentioned. The roots that represent them are "a","ab". In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
[{"input": "5\na aa aaa ab abb", "output": "2"}, {"input": "3\namer arem mrea", "output": "1"}]
900
["implementation", "strings"]
30
[{"input": "5\r\na aa aaa ab abb\r\n", "output": "2"}, {"input": "3\r\namer arem mrea\r\n", "output": "1"}, {"input": "10\r\nbda bbb cda dca dda dcb bcd dcb ada ddd\r\n", "output": "6"}, {"input": "2\r\nfhjlqs aceginpr\r\n", "output": "2"}, {"input": "2\r\nbcdfghimn efghijlmo\r\n", "output": "2"}]
false
stdio
null
true
975/A
975
A
Python 3
TESTS
3
62
8,806,400
129914360
n=int(input()) s=list(map(str,input().split(' '))) k=[] for i in s: p=set(i) c=0 for j in p: if i.count(j)<2: c+=1 if c==len(i): k.append(i) kn=[] kn.append(k[0]) for i in range(1,len(k)): if sorted(k[0])!=sorted(k[i]): kn.append(k[i]) print(len(kn))
30
61
2,867,200
167668018
n = int(input()) s = input().split() print(len(set(frozenset(si) for si in s)))
Codeforces Round 478 (Div. 2)
CF
2,018
1
256
Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
null
In the first test, there are two objects mentioned. The roots that represent them are "a","ab". In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
[{"input": "5\na aa aaa ab abb", "output": "2"}, {"input": "3\namer arem mrea", "output": "1"}]
900
["implementation", "strings"]
30
[{"input": "5\r\na aa aaa ab abb\r\n", "output": "2"}, {"input": "3\r\namer arem mrea\r\n", "output": "1"}, {"input": "10\r\nbda bbb cda dca dda dcb bcd dcb ada ddd\r\n", "output": "6"}, {"input": "2\r\nfhjlqs aceginpr\r\n", "output": "2"}, {"input": "2\r\nbcdfghimn efghijlmo\r\n", "output": "2"}]
false
stdio
null
true
975/A
975
A
Python 3
TESTS
3
78
9,216,000
38112390
n=int(input()) s=list(input().split(' ')) b=[] for word in s: b.append(set(word)) b.sort() count=1 curr=b[0] for i in range(1,len(b)): if(b[i]==curr): pass else: curr=b[i] count+=1 print(count)
30
61
2,969,600
151004273
n = int(input()) lst = input().split() l1 = [] for i in range(n): if set(lst[i]) not in l1: l1.append(set(lst[i])) print(len(l1))
Codeforces Round 478 (Div. 2)
CF
2,018
1
256
Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
null
In the first test, there are two objects mentioned. The roots that represent them are "a","ab". In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
[{"input": "5\na aa aaa ab abb", "output": "2"}, {"input": "3\namer arem mrea", "output": "1"}]
900
["implementation", "strings"]
30
[{"input": "5\r\na aa aaa ab abb\r\n", "output": "2"}, {"input": "3\r\namer arem mrea\r\n", "output": "1"}, {"input": "10\r\nbda bbb cda dca dda dcb bcd dcb ada ddd\r\n", "output": "6"}, {"input": "2\r\nfhjlqs aceginpr\r\n", "output": "2"}, {"input": "2\r\nbcdfghimn efghijlmo\r\n", "output": "2"}]
false
stdio
null
true
518/E
518
E
PyPy 3-64
TESTS
0
31
0
216008024
print("_RANDOM_GUESS_1690488466.1589143")# 1690488466.1589344
75
405
21,401,600
231038367
INF = 10000000001 def fill(s): s.insert(0, -INF) s.append(INF) i = 0 for j in filter(lambda x: s[x] != '?', range(1, len(s))): d = i - j s[j] = int(s[j]) if s[i] > s[j]+d: raise a = max(min(d//2, s[j]+d), s[i]) for t in range(i+1, j): s[t] = a + t - i i = j return s[1:-1] n, k = map(int, input().split()) s = input().split() try: g = [fill([s[i] for i in range(j, n, k)]) for j in range(k)] print(' '.join(str(g[i%k][i//k]) for i in range(n))) except: print('Incorrect sequence')
Codeforces Round 293 (Div. 2)
CF
2,015
2
256
Arthur and Questions
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n. This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1  +  a2 ...  +  ak,  a2  +  a3  +  ...  +  ak + 1,  ...,  an - k + 1  +  an - k + 2  +  ...  +  an), then those numbers will form strictly increasing sequence. For example, for the following sample: n = 5,  k = 3,  a = (1,  2,  4,  5,  6) the sequence of numbers will look as follows: (1  +  2  +  4,  2  +  4  +  5,  4  +  5  +  6) = (7,  11,  15), that means that sequence a meets the described property. Obviously the sequence of sums will have n - k + 1 elements. Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively. The next line contains n space-separated elements ai (1 ≤ i ≤ n). If ai  =  ?, then the i-th element of Arthur's sequence was replaced by a question mark. Otherwise, ai ( - 109 ≤ ai ≤ 109) is the i-th element of Arthur's sequence.
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes). Otherwise, print n integers — Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
null
null
[{"input": "3 2\n? 1 2", "output": "0 1 2"}, {"input": "5 1\n-10 -9 ? -7 -6", "output": "-10 -9 -8 -7 -6"}, {"input": "5 3\n4 6 7 2 9", "output": "Incorrect sequence"}]
2,200
["greedy", "implementation", "math", "ternary search"]
75
[{"input": "3 2\r\n? 1 2\r\n", "output": "0 1 2 \r\n"}, {"input": "5 1\r\n-10 -9 ? -7 -6\r\n", "output": "-10 -9 -8 -7 -6 \r\n"}, {"input": "5 3\r\n4 6 7 2 9\r\n", "output": "Incorrect sequence\r\n"}, {"input": "9 3\r\n? ? ? ? ? ? ? ? ?\r\n", "output": "-1 -1 -1 0 0 0 1 1 1 \r\n"}, {"input": "5 1\r\n1000000000 ? ? ? ?\r\n", "output": "1000000000 1000000001 1000000002 1000000003 1000000004 \r\n"}, {"input": "5 1\r\n-3 -2 -1 0 1\r\n", "output": "-3 -2 -1 0 1 \r\n"}, {"input": "7 3\r\n1 ? -1000000000 ? 100 ? 3\r\n", "output": "1 0 -1000000000 2 100 0 3 \r\n"}, {"input": "7 3\r\n1 ? -1000000000 ? 100 ? 2\r\n", "output": "Incorrect sequence\r\n"}, {"input": "1 1\r\n?\r\n", "output": "0 \r\n"}, {"input": "1 1\r\n0\r\n", "output": "0 \r\n"}, {"input": "2 1\r\n-1000000000 1000000000\r\n", "output": "-1000000000 1000000000 \r\n"}, {"input": "17 1\r\n? -13 ? ? ? -3 ? ? ? ? ? 10 ? ? ? ? 100\r\n", "output": "-14 -13 -6 -5 -4 -3 -2 -1 0 1 2 10 11 12 13 14 100 \r\n"}, {"input": "5 2\r\n? ? -1000000000 ? ?\r\n", "output": "-1000000001 0 -1000000000 1 0 \r\n"}, {"input": "5 4\r\n-1 ? ? ? 2\r\n", "output": "-1 0 0 0 2 \r\n"}, {"input": "10 2\r\n3 ? 5 ? 7 ? 9 ? 11 ?\r\n", "output": "3 -2 5 -1 7 0 9 1 11 2 \r\n"}, {"input": "39 3\r\n-5 1 -13 ? 2 -12 ? 3 -11 -2 4 -10 ? 5 -9 0 6 -8 ? 7 -7 ? 8 -6 5 9 -5 ? 10 -4 ? 11 -3 ? 12 -2 10 13 -1\r\n", "output": "-5 1 -13 -4 2 -12 -3 3 -11 -2 4 -10 -1 5 -9 0 6 -8 1 7 -7 2 8 -6 5 9 -5 6 10 -4 7 11 -3 8 12 -2 10 13 -1 \r\n"}, {"input": "3 1\r\n4 ? 5\r\n", "output": "Incorrect sequence\r\n"}, {"input": "3 1\r\n-1 ? 1\r\n", "output": "-1 0 1 \r\n"}, {"input": "3 1\r\n-3 ? -2\r\n", "output": "Incorrect sequence\r\n"}, {"input": "7 1\r\n-4 ? ? ? ? ? 2\r\n", "output": "-4 -3 -2 -1 0 1 2 \r\n"}, {"input": "3 1\r\n-5 ? 0\r\n", "output": "-5 -1 0 \r\n"}, {"input": "9 3\r\n-5 0 -1 ? ? ? 0 5 1\r\n", "output": "-5 0 -1 -1 1 0 0 5 1 \r\n"}, {"input": "6 1\r\n-1 ? 1 2 3 4\r\n", "output": "-1 0 1 2 3 4 \r\n"}, {"input": "6 1\r\n-3 ? ? ? ? 3\r\n", "output": "-3 -1 0 1 2 3 \r\n"}, {"input": "7 1\r\n-3 ? ? ? ? ? 3\r\n", "output": "-3 -2 -1 0 1 2 3 \r\n"}, {"input": "7 1\r\n-2 ? ? ? ? ? 4\r\n", "output": "-2 -1 0 1 2 3 4 \r\n"}, {"input": "10 1\r\n-2 ? ? ? ? ? ? 5 ? 10\r\n", "output": "-2 -1 0 1 2 3 4 5 6 10 \r\n"}, {"input": "7 2\r\n-10 0 ? 1 ? 2 ?\r\n", "output": "-10 0 -1 1 0 2 1 \r\n"}, {"input": "7 2\r\n10 0 ? 1 ? 2 ?\r\n", "output": "10 0 11 1 12 2 13 \r\n"}, {"input": "9 2\r\n-10 0 ? 1 ? 2 ? 3 ?\r\n", "output": "-10 0 -1 1 0 2 1 3 2 \r\n"}, {"input": "9 2\r\n10 0 ? 1 ? 2 ? 3 ?\r\n", "output": "10 0 11 1 12 2 13 3 14 \r\n"}, {"input": "7 2\r\n-10 0 ? 1 -6 2 ?\r\n", "output": "-10 0 -7 1 -6 2 0 \r\n"}, {"input": "9 2\r\n-10 0 ? 1 -6 2 ? 3 ?\r\n", "output": "-10 0 -7 1 -6 2 0 3 1 \r\n"}, {"input": "7 2\r\n-10 0 ? 1 ? 2 10\r\n", "output": "-10 0 0 1 1 2 10 \r\n"}, {"input": "7 2\r\n-10 0 ? 1 ? 2 0\r\n", "output": "-10 0 -2 1 -1 2 0 \r\n"}, {"input": "9 2\r\n-10 0 ? 1 ? 2 ? 3 10\r\n", "output": "-10 0 -1 1 0 2 1 3 10 \r\n"}, {"input": "9 2\r\n-10 0 ? 1 ? 2 ? 3 0\r\n", "output": "-10 0 -3 1 -2 2 -1 3 0 \r\n"}, {"input": "7 2\r\n-10 0 0 1 ? 2 ?\r\n", "output": "-10 0 0 1 1 2 2 \r\n"}, {"input": "7 2\r\n-10 0 ? 1 6 2 ?\r\n", "output": "-10 0 0 1 6 2 7 \r\n"}, {"input": "7 2\r\n? ? 10 ? ? ? ?\r\n", "output": "0 -1 10 0 11 1 12 \r\n"}, {"input": "7 2\r\n? ? -10 ? ? ? ?\r\n", "output": "-11 -1 -10 0 0 1 1 \r\n"}, {"input": "7 2\r\n? ? 10 ? -10 ? ?\r\n", "output": "Incorrect sequence\r\n"}, {"input": "7 2\r\n? ? -10 ? 10 ? ?\r\n", "output": "-11 -1 -10 0 10 1 11 \r\n"}, {"input": "9 2\r\n? ? -10 ? ? ? 10 ? ?\r\n", "output": "-11 -1 -10 0 0 1 10 2 11 \r\n"}]
false
stdio
import sys def read_sequence(file): line = file.readline().strip() if line == 'Incorrect sequence': return None try: return list(map(int, line.split())) except: return None def main(): input_path = sys.argv[1] output_path = sys.argv[2] submission_path = sys.argv[3] with open(input_path) as f_input, open(output_path) as f_output, open(submission_path) as f_sub: n_line = f_input.readline().strip() if not n_line: print(0) return try: n, k = map(int, n_line.split()) except: print(0) return original = f_input.readline().split() if len(original) != n: print(0) return ref_line = f_output.readline().strip() ref_output = None if ref_line == 'Incorrect sequence': ref_output = None else: try: ref_output = list(map(int, ref_line.split())) if len(ref_output) != n: ref_output = None except: ref_output = None sub_line = f_sub.readline().strip() sub_output = None if sub_line == 'Incorrect sequence': sub_output = None else: try: sub_output = list(map(int, sub_line.split())) if len(sub_output) != n: sub_output = None except: sub_output = None if ref_output is None: if sub_output is None: print(1) else: print(0) return if sub_output is None: print(0) return if len(sub_output) != n: print(0) return valid = True for i in range(n): orig = original[i] if orig != '?': try: orig_val = int(orig) sub_val = sub_output[i] if orig_val != sub_val: valid = False break except: valid = False break if not valid: print(0) return sums = [] try: for i in range(n - k + 1): s = sum(sub_output[i:i+k]) sums.append(s) except: print(0) return for i in range(1, len(sums)): if sums[i] <= sums[i-1]: print(0) return try: ref_sum = sum(abs(x) for x in ref_output) sub_sum = sum(abs(x) for x in sub_output) except: print(0) return if sub_sum != ref_sum: print(0) return print(1) if __name__ == "__main__": main()
true
723/D
723
D
Python 3
TESTS
3
31
102,400
205145608
def fillLake(s, graph): visited = set() visited.add(s) graph[s[0]][s[1]] = '*' # fill the water cell directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] for d in directions: cellRow = s[0] + d[0] cellCol = s[1] + d[1] if cellRow in range(len(graph[0])) and cellCol in range(len(graph)): if graph[cellRow][cellCol] == '.' and (cellRow, cellCol) not in visited: return 1 + fillLake((cellRow, cellCol), graph) return 1 def connectedToOcean(cellRow, cellCol, graph): return cellRow == 0 or cellRow == len(graph) - 1 or cellCol == 0 or cellCol == len(graph[0]) - 1 def getValidLakeSize(s, visited, graph): if connectedToOcean(s[0], s[1], graph): return -1 # connected to Ocean, not a valid lake size = 1 stack = [s] visited.add(s) directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] while len(stack) > 0: currCellPos = stack.pop() #print('currCellPos', currCellPos) for d in directions: #print(f'd {s} {d}') cellRow = currCellPos[0] + d[0] cellCol = currCellPos[1] + d[1] #print(f'adj cell {cellRow, cellCol}') if cellRow in range(len(graph[0])) and cellCol in range(len(graph)): if graph[cellRow][cellCol] == '.' and (cellRow, cellCol) not in visited: if not connectedToOcean(cellRow, cellCol, graph): size += 1 #print(f'{currCellPos} appended', (cellRow, cellCol)) stack.append((cellRow, cellCol)) visited.add((cellRow, cellCol)) else: return -1 return size def main(): n, m, k = map(int, input().split()) berland = [] for i in range(n): line = list(input()) berland.append(line) lakes = dict() visited = set() for i in range(n): for j in range(m): if berland[i][j] == '.' and (i, j) not in visited: size = getValidLakeSize((i, j), visited, berland) if size != -1: # -1 means it's connected to ocean lakes[size] = (i, j) minNumCellFilled = 0 # sort in decending order of lake sizes and get only lakes' positions lakes = list(dict(sorted(lakes.items(), reverse = True)).values()) numLakes = len(lakes) #print(lakes) while numLakes > k: minNumCellFilled += fillLake(lakes.pop(), berland) # start to fill the current smallest lake numLakes -= 1 print(minNumCellFilled) for line in berland: print(''.join(line)) if __name__ == '__main__': main()
26
77
307,200
21178974
def mark(z): while z: z = z[0] return z def mark2(z): while z and type(z) == list: z = z[0] return z __debug = None n, m, kk = map(int, input().split()) data = [list(input()) for i in range(n)] ocean = [] earth = [] work = [[] for i in range(m*n)] for k in range(m): if data[0][k] == '.': work[m*0 + k].append(ocean) if data[n-1][k] == '.': work[m*(n-1) + k].append(ocean) for i in range(n): if data[i][0] == '.': work[m*i + 0].append(ocean) if data[i][m-1] == '.': work[m*i + m-1].append(ocean) for i in range(n): for k in range(m): if data[i][k] == '.': z = mark(work[m*i + k]) if i and data[i-1][k] == '.': zi = mark(work[m*(i-1) + k]) if z is not zi: if z is ocean: zi.append(z) else: z.append(zi) z = zi if k and data[i][k-1] == '.': zk = mark(work[m*i + k-1]) if z is not zk: if z is ocean: zk.append(z) else: z.append(zk) isl = {} no = 1 for i in range(n): for k in range(m): if data[i][k] == '.': if __debug: print(i, end=" ") if __debug: print(k, end=": ") z = mark2(work[m*i + k]) if z: isl[z].append((i,k)) if __debug: print(z, end=", old") elif z is not ocean: z.append(no) if __debug: print(no, end=", new") isl[no] = [(i,k)] no += 1 if __debug: print() if __debug: print(isl) isl_s = list(isl.values()) if __debug: print(isl_s) isl_s.sort(key = len) if __debug: print(isl_s) delta = len(isl_s) - kk if __debug: print(len(isl_s), end=" ") if __debug: print(kk) for t in range(delta): for i, k in isl_s[t]: data[i][k] = '*' print(sum(map(len, isl_s[:delta]))) for i in range(n): print("".join(data[i]))
Codeforces Round 375 (Div. 2)
CF
2,016
2
256
Lakes in Berland
The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell. You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map. The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least k lakes.
In the first line print the minimum number of cells which should be transformed from water to land. In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them. It is guaranteed that the answer exists on the given data.
null
In the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.
[{"input": "5 4 1\n****\n*..*\n****\n**.*\n..**", "output": "1\n****\n*..*\n****\n****\n..**"}, {"input": "3 3 0\n***\n*.*\n***", "output": "1\n***\n***\n***"}]
1,600
["dfs and similar", "dsu", "graphs", "greedy", "implementation"]
26
[{"input": "5 4 1\r\n****\r\n*..*\r\n****\r\n**.*\r\n..**\r\n", "output": "1\r\n****\r\n*..*\r\n****\r\n****\r\n..**\r\n"}, {"input": "3 3 0\r\n***\r\n*.*\r\n***\r\n", "output": "1\r\n***\r\n***\r\n***\r\n"}, {"input": "3 5 1\r\n.**.*\r\n*.*.*\r\n***..\r\n", "output": "0\r\n.**.*\r\n*.*.*\r\n***..\r\n"}, {"input": "3 5 0\r\n.**.*\r\n*.*.*\r\n***..\r\n", "output": "1\r\n.**.*\r\n***.*\r\n***..\r\n"}, {"input": "3 50 7\r\n***.********.*********************.**********.****\r\n*...**..*.**.*.*.*.*.*.*.*..*.*.*.*.*.*.*.*.*.*..*\r\n****************.*.********.**********************\r\n", "output": "8\r\n***.********.*********************.**********.****\r\n*...**..****.***.*.*******..*******.*.*.*.*.*.*..*\r\n****************.*.********.**********************\r\n"}, {"input": "50 3 4\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n***\r\n*.*\r\n***\r\n.**\r\n***\r\n..*\r\n***\r\n***\r\n*.*\r\n***\r\n*.*\r\n***\r\n***\r\n*.*\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n***\r\n***\r\n*.*\r\n***\r\n***\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n***\r\n***\r\n***\r\n", "output": "8\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n.**\r\n***\r\n..*\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n***\r\n*.*\r\n*.*\r\n*.*\r\n***\r\n***\r\n***\r\n***\r\n"}, {"input": "1 1 0\r\n.\r\n", "output": "0\r\n.\r\n"}, {"input": "1 1 0\r\n*\r\n", "output": "0\r\n*\r\n"}]
false
stdio
import sys from sys import argv def main(): input_path = argv[1] output_path = argv[2] submission_path = argv[3] with open(input_path, 'r') as f: input_lines = f.read().splitlines() n, m, k = map(int, input_lines[0].split()) original_map = input_lines[1:n+1] with open(output_path, 'r') as f: ref_lines = f.read().splitlines() if not ref_lines: print(0) return ref_min = int(ref_lines[0]) with open(submission_path, 'r') as f: sub_lines = f.read().splitlines() if not sub_lines: print(0) return # Check first line try: sub_min = int(sub_lines[0]) except: print(0) return if sub_min != ref_min: print(0) return # Check map lines if len(sub_lines) -1 != n: print(0) return sub_map = sub_lines[1:n+1] for line in sub_map: if len(line) != m: print(0) return # Check original land preserved and count transformed transformed = 0 for i in range(n): orig_line = original_map[i] sub_line = sub_map[i] for j in range(m): oc = orig_line[j] sc = sub_line[j] if oc == '*' and sc != '*': print(0) return if oc == '.' and sc == '*': transformed += 1 if transformed != sub_min: print(0) return # Check number of lakes visited = [[False]*m for _ in range(n)] lakes = 0 dirs = [(-1,0), (1,0), (0,-1), (0,1)] def is_border(x, y): return x == 0 or x == n-1 or y ==0 or y == m-1 for i in range(n): for j in range(m): if sub_map[i][j] == '.' and not visited[i][j]: stack = [(i,j)] visited[i][j] = True has_border = False for x, y in stack: if is_border(x, y): has_border = True for dx, dy in dirs: nx, ny = x + dx, y + dy if 0 <= nx < n and 0 <= ny < m and sub_map[nx][ny] == '.' and not visited[nx][ny]: visited[nx][ny] = True stack.append((nx, ny)) if not has_border: lakes += 1 if lakes != k: print(0) return print(1) if __name__ == '__main__': main()
true
376/B
376
B
PyPy 3-64
TESTS
3
46
0
228525847
n, m = map(int,input().split()) os=[] for i in range(m): os.append(list(map(int,input().split()))) for i in range(m): for j in range(m): if os[i][0]==os[j][1]: if os[i][2]<=os[j][2]: os[j][2]-=os[i][2] os[i][0]=os[j][0] else: os[i][2]-=os[j][2] os[j][0]=os[i][0] # if os[i][0]==os[i][1]: # os.remove(i) # if os[j][0]==os[j][1]: # os.remove(j) # print('yes',os[i][0],os[j][1]) # print(*os[i]) sum=0 for i in range(m): sum+=os[i][2] print(sum)
29
46
0
171003922
n, m = map(int, input().split()) debts = [0] * n for _ in range(m): minus, plus, value = map(int, input().split()) debts[minus - 1] -= value debts[plus - 1] += value print(sum([debt for debt in debts if debt > 0]))
Codeforces Round 221 (Div. 2)
CF
2,013
1
256
I.O.U.
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ ci ≤ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).
Print a single integer — the minimum sum of debts in the optimal rearrangement.
null
In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts.
[{"input": "5 3\n1 2 10\n2 3 1\n2 4 1", "output": "10"}, {"input": "3 0", "output": "0"}, {"input": "4 3\n1 2 1\n2 3 1\n3 1 1", "output": "0"}]
1,300
["implementation"]
29
[{"input": "5 3\r\n1 2 10\r\n2 3 1\r\n2 4 1\r\n", "output": "10\r\n"}, {"input": "3 0\r\n", "output": "0\r\n"}, {"input": "4 3\r\n1 2 1\r\n2 3 1\r\n3 1 1\r\n", "output": "0\r\n"}, {"input": "20 28\r\n1 5 6\r\n1 12 7\r\n1 13 4\r\n1 15 7\r\n1 20 3\r\n2 4 1\r\n2 15 6\r\n3 5 3\r\n3 8 10\r\n3 13 8\r\n3 20 6\r\n4 6 10\r\n4 12 8\r\n4 19 5\r\n5 17 8\r\n6 9 9\r\n6 16 2\r\n6 19 9\r\n7 14 6\r\n8 9 3\r\n8 16 10\r\n9 11 7\r\n9 17 8\r\n11 13 8\r\n11 17 17\r\n11 19 1\r\n15 20 2\r\n17 20 1\r\n", "output": "124\r\n"}, {"input": "20 36\r\n1 2 13\r\n1 3 1\r\n1 6 4\r\n1 12 8\r\n1 13 9\r\n1 15 3\r\n1 18 4\r\n2 10 2\r\n2 15 2\r\n2 18 6\r\n3 7 8\r\n3 16 19\r\n4 7 1\r\n4 18 4\r\n5 9 2\r\n5 15 9\r\n5 17 4\r\n5 18 5\r\n6 11 7\r\n6 13 1\r\n6 14 9\r\n7 10 4\r\n7 12 10\r\n7 15 9\r\n7 17 8\r\n8 14 4\r\n10 13 8\r\n10 19 9\r\n11 12 5\r\n12 17 6\r\n13 15 8\r\n13 19 4\r\n14 15 9\r\n14 16 8\r\n17 19 8\r\n17 20 7\r\n", "output": "147\r\n"}, {"input": "20 40\r\n1 13 4\r\n2 3 3\r\n2 4 5\r\n2 7 7\r\n2 17 10\r\n3 5 3\r\n3 6 9\r\n3 10 4\r\n3 12 2\r\n3 13 2\r\n3 14 3\r\n4 5 4\r\n4 8 7\r\n4 13 9\r\n5 6 14\r\n5 14 5\r\n7 11 5\r\n7 12 13\r\n7 15 7\r\n8 14 5\r\n8 16 7\r\n8 18 17\r\n9 11 8\r\n9 19 19\r\n10 12 4\r\n10 16 3\r\n10 18 10\r\n10 20 9\r\n11 13 9\r\n11 20 2\r\n12 13 8\r\n12 18 2\r\n12 20 3\r\n13 17 1\r\n13 20 4\r\n14 16 8\r\n16 19 3\r\n18 19 3\r\n18 20 7\r\n19 20 10\r\n", "output": "165\r\n"}, {"input": "50 10\r\n1 5 1\r\n2 34 2\r\n3 8 10\r\n5 28 4\r\n7 28 6\r\n13 49 9\r\n15 42 7\r\n16 26 7\r\n18 47 5\r\n20 41 10\r\n", "output": "60\r\n"}, {"input": "50 46\r\n1 6 10\r\n1 18 1\r\n1 24 10\r\n1 33 2\r\n1 40 8\r\n3 16 7\r\n4 26 8\r\n4 32 2\r\n4 34 6\r\n5 29 8\r\n6 44 3\r\n8 20 5\r\n8 42 13\r\n10 13 5\r\n10 25 7\r\n10 27 9\r\n10 29 10\r\n11 23 4\r\n12 28 7\r\n12 30 10\r\n12 40 10\r\n13 18 2\r\n13 33 2\r\n14 15 7\r\n14 43 10\r\n14 47 3\r\n16 27 10\r\n17 21 6\r\n17 30 9\r\n19 40 4\r\n22 24 8\r\n22 25 7\r\n22 38 18\r\n25 38 1\r\n27 31 7\r\n27 40 8\r\n30 36 8\r\n31 34 1\r\n32 49 6\r\n33 35 4\r\n33 50 7\r\n38 47 1\r\n42 47 2\r\n42 50 5\r\n43 44 9\r\n47 50 5\r\n", "output": "228\r\n"}, {"input": "100 48\r\n1 56 6\r\n2 42 3\r\n3 52 1\r\n9 50 8\r\n10 96 8\r\n11 39 2\r\n12 51 6\r\n12 68 7\r\n13 40 5\r\n14 18 10\r\n14 70 6\r\n15 37 4\r\n15 38 8\r\n15 82 6\r\n15 85 5\r\n16 48 4\r\n16 50 9\r\n16 71 9\r\n17 18 3\r\n17 100 10\r\n20 73 3\r\n22 32 9\r\n22 89 9\r\n23 53 3\r\n24 53 1\r\n27 78 10\r\n30 50 5\r\n33 94 8\r\n34 87 9\r\n35 73 3\r\n36 51 8\r\n37 88 10\r\n37 97 2\r\n40 47 8\r\n40 90 6\r\n44 53 3\r\n44 65 3\r\n47 48 8\r\n48 72 10\r\n49 98 2\r\n53 68 10\r\n53 71 9\r\n57 62 2\r\n63 76 10\r\n66 90 9\r\n71 76 8\r\n72 80 5\r\n75 77 7\r\n", "output": "253\r\n"}, {"input": "4 3\r\n1 4 1\r\n2 3 1\r\n4 2 2\r\n", "output": "2\r\n"}]
false
stdio
null
true
520/C
520
C
Python 3
TESTS
3
46
307,200
222635163
from collections import Counter def factorial(n): if n<=1:return 1 return n*factorial(n-1) n=int(input()) s=input() d=Counter(s) a=factorial(n) c=0 for i in d: a//=factorial(d[i]) if d[i]==n//2:c+=1 print(a+c)
25
62
204,800
10107470
MOD = 10**9 + 7 n = int(input()) S = input() cnt = [S.count('A'), S.count('C'), S.count('G'), S.count('T')] max_val = max(cnt) op = cnt.count(max_val) print((op**n)%MOD )
Codeforces Round 295 (Div. 2)
CF
2,015
2
256
DNA Alignment
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): $$\rho(s,t) = \sum_{i=0}^{n-1} \sum_{j=0}^{n-1} h(\text{shift}(s,i), \text{shift}(t,j)).$$ ρ("AGC", "CGT") = h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") + h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") + h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") = 1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6 Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: $$\rho(s,t) = \max_{u:|u|=|s|} \rho(s,u)$$. Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.
The first line of the input contains a single integer n (1 ≤ n ≤ 105). The second line of the input contains a single string of length n, consisting of characters "ACGT".
Print a single number — the answer modulo 109 + 7.
null
Please note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one. In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0. In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4. In the third sample, ρ("TTT", "TTT") = 27
[{"input": "1\nC", "output": "1"}, {"input": "2\nAG", "output": "4"}, {"input": "3\nTTT", "output": "1"}]
1,500
["math", "strings"]
25
[{"input": "1\r\nC\r\n", "output": "1\r\n"}, {"input": "2\r\nAG\r\n", "output": "4\r\n"}, {"input": "3\r\nTTT\r\n", "output": "1\r\n"}, {"input": "4\r\nGACT\r\n", "output": "256\r\n"}, {"input": "1\r\nT\r\n", "output": "1\r\n"}, {"input": "2\r\nAG\r\n", "output": "4\r\n"}, {"input": "3\r\nGCA\r\n", "output": "27\r\n"}, {"input": "5\r\nACGTC\r\n", "output": "1\r\n"}, {"input": "15\r\nAGCGAATCCCATTGT\r\n", "output": "14348907\r\n"}, {"input": "20\r\nTAAGCGACCAGGTGCTTTAC\r\n", "output": "511620083\r\n"}, {"input": "30\r\nCCTTTCGGGGCGCGTTGGCCTTTGTCCTGC\r\n", "output": "130653412\r\n"}, {"input": "318\r\nTATCAATCGGTACGTGCGCATCATTGTCAATCGGGCTTCATGGCTTGCGGGCGCTACCCGAGGGGAAGCTGCGGACAGGTAGGTAAGATACACACGAACCAAACGGAGTTATGTTGGATAAATTGGCTGGAAGGGCGTAGGTATATCGAGTCGCGGACCTGGCATAGACTATCAGGGGCAGCGGTACAAGGCAACCGTGAGCGGGGTCTGCCCACCATTAGACCGATGCGCCGGCTCGTATATGTGATTCTGGTGAAAAGTATCATGCCGGGACGCGTAATGACCCGGCTGGCTAATCCACCGTGGCAGCAAAATAAC\r\n", "output": "1\r\n"}]
false
stdio
null
true
208/E
208
E
PyPy 3-64
TESTS
0
92
0
194426326
n = int(input()) parent = list(map(int, input().split())) m = int(input()) # Функция нахождения p-прародителя common_ancestor def get_p_ancestor(common_ancestor, p): while p > 0 and common_ancestor > 0: common_ancestor = parent[common_ancestor - 1] p -= 1 return common_ancestor # Обработка каждой пары vi, pi for i in range(m): v, p = map(int, input().split()) common_ancestor = get_p_ancestor(v, p) # находим pi-прародителя для vi cnt = 0 for j in range(1, n+1): # находим всех p-прародителей common_ancestor на расстоянии p от него if get_p_ancestor(j, p) == common_ancestor and j != common_ancestor: # подсчитываем количество p-прародителей common_ancestor, которые являются п-прародителями других людей if get_p_ancestor(j, p-1) == common_ancestor: cnt += 1 print(cnt)
64
1,310
69,939,200
200092003
import bisect import heapq import sys from types import GeneratorType from functools import cmp_to_key from collections import defaultdict, Counter, deque import math from functools import lru_cache from heapq import nlargest from functools import reduce import random from itertools import combinations from itertools import accumulate from operator import xor, add from operator import mul from typing import List inf = float("inf") PLATFORM = "CF" if PLATFORM == "LUOGU": import numpy as np sys.setrecursionlimit(1000000) class FastIO: def __init__(self): return @staticmethod def _read(): return sys.stdin.readline().strip() def read_int(self): return int(self._read()) def read_float(self): return float(self._read()) def read_ints(self): return map(int, self._read().split()) def read_floats(self): return map(float, self._read().split()) def read_ints_minus_one(self): return map(lambda x: int(x) - 1, self._read().split()) def read_list_ints(self): return list(map(int, self._read().split())) def read_list_floats(self): return list(map(float, self._read().split())) def read_list_ints_minus_one(self): return list(map(lambda x: int(x) - 1, self._read().split())) def read_str(self): return self._read() def read_list_strs(self): return self._read().split() def read_list_str(self): return list(self._read()) @staticmethod def st(x): return sys.stdout.write(str(x) + '\n') @staticmethod def lst(x): return sys.stdout.write(" ".join(str(w) for w in x) + '\n') @staticmethod def round_5(f): res = int(f) if f - res >= 0.5: res += 1 return res @staticmethod def max(a, b): return a if a > b else b @staticmethod def min(a, b): return a if a < b else b @staticmethod def bootstrap(f, queue=[]): def wrappedfunc(*args, **kwargs): if queue: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if isinstance(to, GeneratorType): queue.append(to) to = next(to) else: queue.pop() if not queue: break to = queue[-1].send(to) return to return wrappedfunc class DFS: def __init__(self): return @staticmethod def gen_dfs_order_recursion(dct): # 模板:生成深搜序即 dfs 序以及对应子树编号区间 def dfs(x): nonlocal order start[x] = order order += 1 for y in dct[x]: if start[y] == -1: dfs(y) end[x] = order - 1 return n = len(dct) order = 0 start = [-1] * n end = [-1]*n dfs(0) return start, end @staticmethod def gen_dfs_order_iteration(dct): # 模板:生成深搜序即 dfs 序以及对应子树编号区间 n = len(dct) order = 0 start = [-1] * n end = [-1]*n parent = [-1]*n stack = [[0, 1, -1, 0]] depth = [0]*n while stack: i, state, fa, d = stack.pop() if state: start[i] = order end[i] = order depth[i] = d order += 1 stack.append([i, 0, fa, d]) for j in dct[i]: if j != fa: parent[j] = i stack.append([j, 1, i, d+1]) else: if parent[i] != -1: end[parent[i]] = end[i] return start, end, depth class TreeAncestor: def __init__(self, edges: List[List[int]]): # 默认以 0 为根节点 n = len(edges) self.parent = [-1] * n self.depth = [-1] * n stack = deque([0]) self.depth[0] = 0 while stack: i = stack.popleft() for j in edges[i]: if self.depth[j] == -1: self.depth[j] = self.depth[i] + 1 self.parent[j] = i stack.append(j) # 根据节点规模设置层数 self.cols = max(2, math.ceil(math.log2(n))) self.dp = [[-1] * self.cols for _ in range(n)] for i in range(n): self.dp[i][0] = self.parent[i] # 动态规划设置祖先初始化, dp[node][j] 表示 node 往前推第 2^j 个祖先 for j in range(1, self.cols): for i in range(n): father = self.dp[i][j-1] if father != -1: self.dp[i][j] = self.dp[father][j-1] return def get_kth_ancestor(self, node: int, k: int) -> int: # 查询节点的第 k 个祖先 for i in range(self.cols - 1, -1, -1): if k & (1 << i): node = self.dp[node][i] if node == -1: break return node def get_lca(self, x: int, y: int) -> int: # 计算任意两点的最近公共祖先 LCA if self.depth[x] < self.depth[y]: x, y = y, x while self.depth[x] > self.depth[y]: d = self.depth[x]-self.depth[y] x = self.dp[x][int(math.log2(d))] if x == y: return x for k in range(int(math.log2(self.depth[x])), -1, -1): if self.dp[x][k] != self.dp[y][k]: x = self.dp[x][k] y = self.dp[y][k] return self.dp[x][0] def get_dist(self, u: int, v: int) -> int: # 计算任意点的最短路距离 lca = self.get_lca(u, v) depth_u = self.depth[u] depth_v = self.depth[v] depth_lca = self.depth[lca] return depth_u + depth_v - 2 * depth_lca class Solution: def __init__(self): return @staticmethod def main(ac=FastIO()): n = ac.read_int() parent = ac.read_list_ints() edge = [[] for _ in range(n+1)] for i in range(n): edge[parent[i]].append(i+1) edge[i+1].append(parent[i]) del parent tree = TreeAncestor(edge) start, end, _ = DFS().gen_dfs_order_iteration(edge) dct = [[] for _ in range(n+1)] for i in range(n+1): dct[tree.depth[i]].append(start[i]) for i in range(n+1): dct[i].sort() ans = [] for _ in range(ac.read_int()): v, p = ac.read_ints() if tree.depth[v] - 1 < p: ans.append(0) continue u = tree.get_kth_ancestor(v, p) low, high = start[u], end[u] cur = bisect.bisect_right(dct[tree.depth[v]], high)-bisect.bisect_left(dct[tree.depth[v]], low) ans.append(ac.max(cur-1, 0)) ac.lst(ans) return Solution().main()
Codeforces Round 130 (Div. 2)
CF
2,012
2
256
Blood Cousins
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent. Let's call person a a 1-ancestor of person b, if a is the parent of b. Let's call person a a k-ancestor (k > 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x > 0). Let's call two people x and y (x ≠ y) p-th cousins (p > 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y. Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
null
null
[{"input": "6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1", "output": "0 0 1 0 0 1 1"}]
2,100
["binary search", "data structures", "dfs and similar", "trees"]
64
[{"input": "6\r\n0 1 1 0 4 4\r\n7\r\n1 1\r\n1 2\r\n2 1\r\n2 2\r\n4 1\r\n5 1\r\n6 1\r\n", "output": "0 0 1 0 0 1 1 \r\n"}, {"input": "1\r\n0\r\n20\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "2\r\n0 1\r\n20\r\n2 1\r\n2 1\r\n2 1\r\n2 1\r\n2 1\r\n2 1\r\n1 1\r\n1 1\r\n1 1\r\n2 1\r\n1 1\r\n2 1\r\n2 1\r\n2 1\r\n1 1\r\n2 1\r\n2 1\r\n1 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "3\r\n0 0 2\r\n20\r\n2 1\r\n1 1\r\n1 1\r\n2 1\r\n2 1\r\n1 1\r\n3 1\r\n1 1\r\n2 1\r\n1 1\r\n3 1\r\n2 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n2 1\r\n3 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "3\r\n0 0 1\r\n20\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n2 1\r\n3 1\r\n2 1\r\n3 1\r\n1 1\r\n1 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "4\r\n0 1 1 0\r\n20\r\n3 1\r\n1 1\r\n1 1\r\n3 1\r\n4 1\r\n3 1\r\n3 1\r\n4 1\r\n2 1\r\n1 1\r\n4 1\r\n4 1\r\n2 1\r\n2 1\r\n3 1\r\n4 1\r\n4 1\r\n1 1\r\n2 1\r\n4 1\r\n", "output": "1 0 0 1 0 1 1 0 1 0 0 0 1 1 1 0 0 0 1 0 \r\n"}, {"input": "4\r\n0 0 0 1\r\n20\r\n2 1\r\n2 1\r\n3 1\r\n2 1\r\n4 1\r\n3 1\r\n1 1\r\n3 1\r\n2 1\r\n2 1\r\n3 1\r\n1 1\r\n1 1\r\n1 1\r\n2 1\r\n4 1\r\n4 1\r\n3 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}]
false
stdio
null
true
316/E1
316
E1
PyPy 3-64
TESTS1
7
216
6,041,600
201607888
n,m=map(int,input().split()) l=list(map(int,input().split())) h=10**9+7 for i in range(m): t,a,b=map(int,input().split()) if t==1: l[a-1]=b else: f=0 s=1 out=0 for i in range(a-1,b): out=(out%h+(s%h*l[i]%h)%h)%h f,s=s,f+s print(out)
19
748
6,963,200
78808001
mod = 10**9 FibArray = [1,1] def fibonacci(n): if n<=len(FibArray): return FibArray[n-1] else: temp_fib = fibonacci(n-1)+fibonacci(n-2) FibArray.append(temp_fib) return temp_fib n, m = map(int, input().split()) a = list(map(int, input().split())) for _ in range(m): query = list(map(int, input().split())) if query[0]==1: a[query[1]-1] = query[2] elif query[0]==3: d = query[3] for i in range(query[1]-1, query[2]): a[i]+=d else: l, r = query[1], query[2] s = 0 for x in range(r-l+1): # print(fibonacci(x+1), a[l+x-1]) s+=((fibonacci(x+1)*a[l+x-1])) print(s%mod)
ABBYY Cup 3.0
ICPC
2,013
3
256
Summer Homework
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum $$\sum_{x=0}^{r_i-l_i} (f_x \cdot a_{l_i+x})$$, where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type: - if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105); - if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n); - if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105). The input limits for scoring 30 points are (subproblem E1): - It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): - It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): - No extra limitations.
For each query print the calculated sum modulo 1000000000 (109).
null
null
[{"input": "5 5\n1 3 1 2 4\n2 1 4\n2 1 5\n2 2 4\n1 3 10\n2 1 5", "output": "12\n32\n8\n50"}, {"input": "5 4\n1 3 1 2 4\n3 1 4 1\n2 2 4\n1 2 10\n2 1 5", "output": "12\n45"}]
1,500
["brute force", "data structures"]
19
[{"input": "5 5\r\n1 3 1 2 4\r\n2 1 4\r\n2 1 5\r\n2 2 4\r\n1 3 10\r\n2 1 5\r\n", "output": "12\r\n32\r\n8\r\n50\r\n"}, {"input": "1 3\r\n2\r\n2 1 1\r\n1 1 3\r\n2 1 1\r\n", "output": "2\r\n3\r\n"}, {"input": "11 11\r\n6 1 9 0 2 9 1 6 2 8 0\r\n2 9 9\r\n1 9 0\r\n1 1 8\r\n2 2 5\r\n2 7 11\r\n2 2 8\r\n1 3 2\r\n1 10 0\r\n2 1 8\r\n2 9 11\r\n1 9 7\r\n", "output": "2\r\n16\r\n31\r\n147\r\n234\r\n0\r\n"}, {"input": "11 18\r\n14 13 18 17 14 17 13 3 0 3 21\r\n2 6 9\r\n2 1 6\r\n2 5 7\r\n2 1 3\r\n2 1 9\r\n2 3 9\r\n2 2 5\r\n2 7 10\r\n2 1 5\r\n2 4 6\r\n2 10 11\r\n2 4 5\r\n2 2 8\r\n2 3 9\r\n2 1 5\r\n2 2 3\r\n2 2 6\r\n1 4 19\r\n", "output": "36\r\n320\r\n57\r\n63\r\n552\r\n203\r\n107\r\n25\r\n184\r\n65\r\n24\r\n31\r\n335\r\n203\r\n184\r\n31\r\n192\r\n"}, {"input": "12 26\r\n18 5 13 38 33 11 30 24 6 34 11 30\r\n2 1 12\r\n2 1 12\r\n2 1 11\r\n1 3 15\r\n1 11 5\r\n2 1 11\r\n2 2 10\r\n2 3 12\r\n2 2 11\r\n2 3 11\r\n2 3 10\r\n2 3 11\r\n1 9 37\r\n1 2 37\r\n2 1 11\r\n1 3 30\r\n2 2 12\r\n1 4 42\r\n2 3 10\r\n2 1 11\r\n1 11 26\r\n1 7 37\r\n2 3 11\r\n1 7 30\r\n1 6 40\r\n1 7 13\r\n", "output": "8683\r\n8683\r\n4363\r\n3833\r\n2084\r\n3106\r\n2359\r\n1456\r\n1286\r\n1456\r\n4919\r\n5727\r\n1708\r\n4961\r\n2627\r\n"}]
false
stdio
null
true
316/E1
316
E1
PyPy 3
TESTS1
7
372
4,505,600
11002630
n,m = map(int,input().split()) a = list(map(int,input().split())) f = [1,1] for i in range(2,n+1): f.append(f[i-1] + f[i-2]) for q in range(m): z,l,r = map(int,input().split()) if z == 1: a[l-1] = r else: s = 0 for j in range(l-1,r): s += (a[j] * f[j-l+1]) print(s)
19
780
25,292,800
35903391
n,m = map(int, input().split()) a = list(map(int, input().split())) f = [1]*n for i in range(2,n): f[i] = f[i-1]+f[i-2] for i in range(m): t,l,r = map(int, input().split()) if t==1: a[l-1] = r else: sum_lr = 0 for x in range(r-l+1): sum_lr += f[x] * a[l+x-1] print(sum_lr%1000000000)
ABBYY Cup 3.0
ICPC
2,013
3
256
Summer Homework
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum $$\sum_{x=0}^{r_i-l_i} (f_x \cdot a_{l_i+x})$$, where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type: - if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105); - if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n); - if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105). The input limits for scoring 30 points are (subproblem E1): - It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): - It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): - No extra limitations.
For each query print the calculated sum modulo 1000000000 (109).
null
null
[{"input": "5 5\n1 3 1 2 4\n2 1 4\n2 1 5\n2 2 4\n1 3 10\n2 1 5", "output": "12\n32\n8\n50"}, {"input": "5 4\n1 3 1 2 4\n3 1 4 1\n2 2 4\n1 2 10\n2 1 5", "output": "12\n45"}]
1,500
["brute force", "data structures"]
19
[{"input": "5 5\r\n1 3 1 2 4\r\n2 1 4\r\n2 1 5\r\n2 2 4\r\n1 3 10\r\n2 1 5\r\n", "output": "12\r\n32\r\n8\r\n50\r\n"}, {"input": "1 3\r\n2\r\n2 1 1\r\n1 1 3\r\n2 1 1\r\n", "output": "2\r\n3\r\n"}, {"input": "11 11\r\n6 1 9 0 2 9 1 6 2 8 0\r\n2 9 9\r\n1 9 0\r\n1 1 8\r\n2 2 5\r\n2 7 11\r\n2 2 8\r\n1 3 2\r\n1 10 0\r\n2 1 8\r\n2 9 11\r\n1 9 7\r\n", "output": "2\r\n16\r\n31\r\n147\r\n234\r\n0\r\n"}, {"input": "11 18\r\n14 13 18 17 14 17 13 3 0 3 21\r\n2 6 9\r\n2 1 6\r\n2 5 7\r\n2 1 3\r\n2 1 9\r\n2 3 9\r\n2 2 5\r\n2 7 10\r\n2 1 5\r\n2 4 6\r\n2 10 11\r\n2 4 5\r\n2 2 8\r\n2 3 9\r\n2 1 5\r\n2 2 3\r\n2 2 6\r\n1 4 19\r\n", "output": "36\r\n320\r\n57\r\n63\r\n552\r\n203\r\n107\r\n25\r\n184\r\n65\r\n24\r\n31\r\n335\r\n203\r\n184\r\n31\r\n192\r\n"}, {"input": "12 26\r\n18 5 13 38 33 11 30 24 6 34 11 30\r\n2 1 12\r\n2 1 12\r\n2 1 11\r\n1 3 15\r\n1 11 5\r\n2 1 11\r\n2 2 10\r\n2 3 12\r\n2 2 11\r\n2 3 11\r\n2 3 10\r\n2 3 11\r\n1 9 37\r\n1 2 37\r\n2 1 11\r\n1 3 30\r\n2 2 12\r\n1 4 42\r\n2 3 10\r\n2 1 11\r\n1 11 26\r\n1 7 37\r\n2 3 11\r\n1 7 30\r\n1 6 40\r\n1 7 13\r\n", "output": "8683\r\n8683\r\n4363\r\n3833\r\n2084\r\n3106\r\n2359\r\n1456\r\n1286\r\n1456\r\n4919\r\n5727\r\n1708\r\n4961\r\n2627\r\n"}]
false
stdio
null
true
318/B
318
B
Python 3
TESTS
3
62
0
226507697
# بسم الله الرحمن الرحيم # صلو على نبينا محمد صلى الله عليه و سلم ##############--->>>>> Mohamed Mostafa Mohamed Abdelhamed <<<<<---############## """ ____ _ _____ / ___|___ __| | ___| ___|__ _ __ ___ ___ ___ | | / _ \ / _` |/ _ \ |_ / _ \| '__/ __/ _ \/ __| | |__| (_) | (_| | __/ _| (_) | | | (_| __/\__ \ \____\___/ \__,_|\___|_| \___/|_| \___\___||___/ """ ss = input() # tt = list() # for i in range(len(ss)): # if ss[i] == "h" and ss[i + 1] == "e" and ss[i + 2] == "a": # tt.append(ss[i : i + 5]) # if ss[i] == "m" and ss[i + 1] == "e" and ss[i + 2] == "t": # tt.append(ss[i : i + 5]) print((ss.count("heavy") // 2) + ss.count("metal"))
30
154
6,963,200
221840419
w = input().replace("heavy","H").replace("metal","M") res, hCount = 0, 0 for c in w: if c == "H": hCount += 1 elif c == "M": res += hCount print(res)
Codeforces Round 188 (Div. 2)
CF
2,013
2
256
Strings of Power
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style. Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text. For simplicity, let us assume that Volodya's text can be represented as a single string.
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Print exactly one number — the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful. In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".
[{"input": "heavymetalisheavymetal", "output": "3"}, {"input": "heavymetalismetal", "output": "2"}, {"input": "trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou", "output": "3"}]
1,300
["implementation", "strings", "two pointers"]
30
[{"input": "heavymetalisheavymetal\r\n", "output": "3"}, {"input": "heavymetalismetal\r\n", "output": "2"}, {"input": "trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou\r\n", "output": "3"}, {"input": "fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua\r\n", "output": "5"}, {"input": "metametaheavyetalalmetalavylkeoheavyhemetaleavycdk\r\n", "output": "3"}, {"input": "hg\r\n", "output": "0"}]
false
stdio
null
true
711/D
711
D
PyPy 3-64
TESTS
3
46
0
207101037
# 环内只需要顺时针逆时针两种情况,环外无所谓。 n = int(input()) a = list(map(int, input().split())) Mod = 10**9 + 7 from collections import defaultdict from collections import deque g = defaultdict(list) cnt = [1]*n for i in range(n): g[i].append(a[i]-1) g[a[i]-1].append(i) cnt[a[i]-1] += 1 q = deque([i for i in range(n) if cnt[i] == 1]) ans = n while q: T = q.popleft() cnt[T] = 0 ans -= 1 for x in g[T]: cnt[x] -= 1 if cnt[x] == 1: q.append(x) print(pow(2,n - ans,Mod)*(pow(2,ans,Mod) - 2)%Mod)
131
155
27,545,600
207098619
# Problem: D. Directed Roads # Contest: Codeforces - Codeforces Round 369 (Div. 2) # URL: https://codeforces.com/problemset/problem/711/D # Memory Limit: 256 MB # Time Limit: 2000 ms import sys import bisect import random import io, os from bisect import * from collections import * from contextlib import redirect_stdout from itertools import * from array import * from functools import lru_cache, reduce from types import GeneratorType from heapq import * from math import sqrt, gcd, inf if sys.version >= '3.8': # ACW没有comb from math import comb RI = lambda: map(int, sys.stdin.buffer.readline().split()) RS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split()) RILST = lambda: list(RI()) DEBUG = lambda *x: sys.stderr.write(f'{str(x)}\n') # print = lambda d: sys.stdout.write(str(d) + "\n") # 打开可以快写,但是无法使用print(*ans,sep=' ')这种语法,需要print(' '.join(map(str, p))),确实会快。 DIRS = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 右下左上 DIRS8 = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)] # →↘↓↙←↖↑↗ MOD = 10 ** 9 + 7 PROBLEM = """https://codeforces.com/problemset/problem/711/D 输入 n(2≤n≤2e5) 和长为 n 的数组 a(1≤a[i]≤n,a[i]≠i),表示一个 n 点 n 边的无向图(节点编号从 1 开始),点 i 和 a[i] 相连。 你需要给每条边定向(无向变有向),这一共有 2^n 种方案。 其中有多少种方案,可以使图中没有环? 模 1e9+7。 输入 3 2 3 1 输出 6 输入 4 2 1 1 1 输出 8 输入 5 2 4 2 5 3 输出 28 """ """https://codeforces.com/contest/711/submission/207047798 前置题目: 2550. 猴子碰撞的方法数 2360. 图中的最长环 遍历每个环,这个环的贡献为 2^环长 - 2。 不在环上的边可以随意取,贡献为 2^边数。 这些贡献相乘即为答案。""" # ms def solve(): n, = RI() a = RILST() for i in range(n): a[i] -= 1 ans = 1 clock = 1 circle = 0 time = [0] * n for u, t in enumerate(time): if t: continue start_time = clock while u >= 0: if time[u]: if time[u] >= start_time: p = clock - time[u] circle += p ans = ans * (pow(2, p, MOD) - 2) % MOD break time[u] = clock clock += 1 u = a[u] print(ans * pow(2, n - circle, MOD) % MOD) if __name__ == '__main__': t = 0 if t: t, = RI() for _ in range(t): solve() else: solve()
Codeforces Round 369 (Div. 2)
CF
2,016
2
256
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.
null
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $$1 \rightarrow 2$$, $$2\rightarrow3$$, $$\overset{3}{\rightarrow}1$$ initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[{"input": "3\n2 3 1", "output": "6"}, {"input": "4\n2 1 1 1", "output": "8"}, {"input": "5\n2 4 2 5 3", "output": "28"}]
1,900
["combinatorics", "dfs and similar", "graphs", "math"]
131
[{"input": "3\r\n2 3 1\r\n", "output": "6\r\n"}, {"input": "4\r\n2 1 1 1\r\n", "output": "8\r\n"}, {"input": "5\r\n2 4 2 5 3\r\n", "output": "28\r\n"}, {"input": "4\r\n2 1 4 3\r\n", "output": "4\r\n"}, {"input": "7\r\n2 3 4 1 6 5 4\r\n", "output": "56\r\n"}, {"input": "20\r\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1\r\n", "output": "1048574\r\n"}, {"input": "2\r\n2 1\r\n", "output": "2\r\n"}, {"input": "84\r\n2 50 67 79 71 45 43 40 57 20 25 8 60 47 52 10 37 23 1 28 22 26 3 42 11 63 61 68 49 32 55 18 5 24 31 70 66 27 38 41 54 12 65 51 15 34 30 35 77 74 21 62 33 16 81 14 19 48 80 73 69 78 39 6 76 46 75 72 84 29 58 59 13 17 82 9 83 4 36 56 53 7 64 44\r\n", "output": "428380105\r\n"}]
false
stdio
null
true
711/D
711
D
PyPy 3-64
TESTS
3
61
0
207137773
import sys from collections import deque RI = lambda: map(int, sys.stdin.buffer.readline().split()) n = list(RI())[0] edges = [0] + list(RI()) deg = [0] * (n + 1) for i, v in enumerate(edges): if i == 0: continue deg[v] += 1 q = deque([i for i in range(1, n + 1) if deg[i] == 0]) while q: x = q.popleft() deg[edges[x]] -= 1 if deg[edges[x]] == 0: q.append(edges[x]) # 剩下的只要deg!=0,就说明是环中的,那就将他和他的出边union fa = list(range(n + 1)) size = [1] * (n + 1) def find(x): if fa[x] != x: fa[x] = find(fa[x]) return fa[x] for i in range(1, n + 1): if deg[i] == 0: continue x = find(i) y = find(edges[i]) if y == x: continue fa[x] = y size[y] += size[x] vis = set() tot = 0 for i in range(1, n + 1): fi = find(i) if fi in vis: continue vis.add(fi) tot += size[fi] mod = 10 ** 9 + 7 has_circle = pow(2, len(vis), mod) * pow(2, n - tot) not_has = (pow(2, n, mod) - has_circle + mod) % mod print(not_has)
131
171
18,534,400
193498801
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) mod = pow(10, 9) + 7 a = [0] + list(map(int, input().split())) pow2 = [1] for _ in range(n + 5): pow2.append(2 * pow2[-1] % mod) visit = [0] * (n + 1) ans = 1 for i in range(1, n + 1): if visit[i]: continue q = [i] visit[i] = 1 while not visit[a[q[-1]]]: j = a[q[-1]] visit[j] = 1 q.append(j) q.reverse() u = a[q[0]] while q and q[-1] ^ u: q.pop() ans = 2 * ans % mod l = len(q) if len(q): ans = ans * (pow2[l] - 2) % mod print(ans)
Codeforces Round 369 (Div. 2)
CF
2,016
2
256
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.
null
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $$1 \rightarrow 2$$, $$2\rightarrow3$$, $$\overset{3}{\rightarrow}1$$ initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[{"input": "3\n2 3 1", "output": "6"}, {"input": "4\n2 1 1 1", "output": "8"}, {"input": "5\n2 4 2 5 3", "output": "28"}]
1,900
["combinatorics", "dfs and similar", "graphs", "math"]
131
[{"input": "3\r\n2 3 1\r\n", "output": "6\r\n"}, {"input": "4\r\n2 1 1 1\r\n", "output": "8\r\n"}, {"input": "5\r\n2 4 2 5 3\r\n", "output": "28\r\n"}, {"input": "4\r\n2 1 4 3\r\n", "output": "4\r\n"}, {"input": "7\r\n2 3 4 1 6 5 4\r\n", "output": "56\r\n"}, {"input": "20\r\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1\r\n", "output": "1048574\r\n"}, {"input": "2\r\n2 1\r\n", "output": "2\r\n"}, {"input": "84\r\n2 50 67 79 71 45 43 40 57 20 25 8 60 47 52 10 37 23 1 28 22 26 3 42 11 63 61 68 49 32 55 18 5 24 31 70 66 27 38 41 54 12 65 51 15 34 30 35 77 74 21 62 33 16 81 14 19 48 80 73 69 78 39 6 76 46 75 72 84 29 58 59 13 17 82 9 83 4 36 56 53 7 64 44\r\n", "output": "428380105\r\n"}]
false
stdio
null
true
711/D
711
D
PyPy 3-64
TESTS
3
92
4,608,000
207147374
from bisect import bisect_left, bisect_right from collections import Counter, deque from functools import lru_cache from math import factorial, comb, sqrt, gcd, lcm, log2 from copy import deepcopy import heapq from sys import stdin, stdout input = stdin.readline def quick_mi(a, b, MOD): res = 1 % MOD while b > 0: if b & 1 == 1: res = res * a % MOD a = a * a % MOD b = b >> 1 return res def main(): MOD = 10**9 + 7 n = int(input()) L = list(map(int, input().split())) nei_L = [[] for _ in range(n)] for i, nei in enumerate(L): nei -= 1 nei_L[i].append(nei) # n 个点 n 条边最多构成一个环 cur_time = 1 time_L = [-1] * n circle_len = -1 def dfs(cur): nonlocal cur_time cur_time += 1 if time_L[cur] != -1: # 说明找到了环 if time_L[cur] > start: nonlocal circle_len circle_len = cur_time - time_L[cur] else: time_L[cur] = cur_time for nei in nei_L[cur]: dfs(nei) for i in range(n): if time_L[i] == -1: start = cur_time dfs(i) cur_time += 1 # print(time_L) # print(circle_len) # if circle_len == -1: # print(quick_mi(2, n, MOD)) # else: print((quick_mi(2, circle_len, MOD) - 2) * quick_mi(2, n - circle_len, MOD) % MOD) if __name__ == "__main__": main()
131
202
28,876,800
207099275
import random import sys from math import gcd, lcm, sqrt, isqrt, perm from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush from copy import deepcopy from bisect import bisect_left, bisect_right from string import ascii_lowercase, ascii_uppercase inf = float('inf') MOD = 10**9+7 input = lambda: sys.stdin.readline().strip() I = lambda: input() II = lambda: int(input()) MII = lambda: map(int, input().split()) LI = lambda: list(input().split()) LII = lambda: list(map(int, input().split())) GMI = lambda: map(lambda x: int(x) - 1, input().split()) LGMI = lambda: list(map(lambda x: int(x) - 1, input().split())) # 时间戳找环 def solve(): n = II() a = LGMI() clock = 0 res = 1 time = [0] * n loop = 0 for i, t in enumerate(time): if t: continue start_t = clock while True: if time[i]: if time[i] >= start_t: sz = clock - time[i] loop += sz res *= pow(2, sz, MOD) - 2 res %= MOD break time[i] = clock clock += 1 i = a[i] res *= pow(2, n-loop, MOD) res %= MOD print(res) return solve()
Codeforces Round 369 (Div. 2)
CF
2,016
2
256
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.
null
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $$1 \rightarrow 2$$, $$2\rightarrow3$$, $$\overset{3}{\rightarrow}1$$ initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[{"input": "3\n2 3 1", "output": "6"}, {"input": "4\n2 1 1 1", "output": "8"}, {"input": "5\n2 4 2 5 3", "output": "28"}]
1,900
["combinatorics", "dfs and similar", "graphs", "math"]
131
[{"input": "3\r\n2 3 1\r\n", "output": "6\r\n"}, {"input": "4\r\n2 1 1 1\r\n", "output": "8\r\n"}, {"input": "5\r\n2 4 2 5 3\r\n", "output": "28\r\n"}, {"input": "4\r\n2 1 4 3\r\n", "output": "4\r\n"}, {"input": "7\r\n2 3 4 1 6 5 4\r\n", "output": "56\r\n"}, {"input": "20\r\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1\r\n", "output": "1048574\r\n"}, {"input": "2\r\n2 1\r\n", "output": "2\r\n"}, {"input": "84\r\n2 50 67 79 71 45 43 40 57 20 25 8 60 47 52 10 37 23 1 28 22 26 3 42 11 63 61 68 49 32 55 18 5 24 31 70 66 27 38 41 54 12 65 51 15 34 30 35 77 74 21 62 33 16 81 14 19 48 80 73 69 78 39 6 76 46 75 72 84 29 58 59 13 17 82 9 83 4 36 56 53 7 64 44\r\n", "output": "428380105\r\n"}]
false
stdio
null
true
711/D
711
D
PyPy 3-64
TESTS
3
93
2,969,600
194664330
from heapq import heappush, heappop from collections import defaultdict, Counter, deque import threading import sys import bisect input = sys.stdin.readline def ri(): return int(input()) def rs(): return input() def rl(): return list(map(int, input().split())) def rls(): return list(input().split()) # threading.stack_size(10**8) # sys.setrecursionlimit(10**6) def main(): n = ri() mod = 10**9+7 a = [0]+rl() vis = [0]*(n+1) res = 1 pos = 1 for i in range(1, n+1): if vis[i]: continue j = i st = pos while not vis[j]: vis[j] = pos pos += 1 j = a[j] if vis[j] >= st: n -= pos-vis[j] res = (res*pow(2, pos-vis[j], mod)-2) % mod print((res*pow(2, n, mod)) % mod) pass main() # threading.Thread(target=main).start()
131
202
33,996,800
207096160
n = int(input()) l = list(map(int, input().split())) l.insert(0,0) mark = {} loop, pos, res , mod= 0, 1, 1, int(1e9+7) for i in range(1, n+1): if not i in mark: start, j = pos, i while not j in mark: mark[j] = pos pos+= 1 j = l[j] if mark[j]>=start: size = pos-mark[j] loop+= size res*= pow(2, size)-2+mod res%= mod res = (res * pow(2, n-loop,mod))%mod print(res)
Codeforces Round 369 (Div. 2)
CF
2,016
2
256
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.
null
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $$1 \rightarrow 2$$, $$2\rightarrow3$$, $$\overset{3}{\rightarrow}1$$ initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[{"input": "3\n2 3 1", "output": "6"}, {"input": "4\n2 1 1 1", "output": "8"}, {"input": "5\n2 4 2 5 3", "output": "28"}]
1,900
["combinatorics", "dfs and similar", "graphs", "math"]
131
[{"input": "3\r\n2 3 1\r\n", "output": "6\r\n"}, {"input": "4\r\n2 1 1 1\r\n", "output": "8\r\n"}, {"input": "5\r\n2 4 2 5 3\r\n", "output": "28\r\n"}, {"input": "4\r\n2 1 4 3\r\n", "output": "4\r\n"}, {"input": "7\r\n2 3 4 1 6 5 4\r\n", "output": "56\r\n"}, {"input": "20\r\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1\r\n", "output": "1048574\r\n"}, {"input": "2\r\n2 1\r\n", "output": "2\r\n"}, {"input": "84\r\n2 50 67 79 71 45 43 40 57 20 25 8 60 47 52 10 37 23 1 28 22 26 3 42 11 63 61 68 49 32 55 18 5 24 31 70 66 27 38 41 54 12 65 51 15 34 30 35 77 74 21 62 33 16 81 14 19 48 80 73 69 78 39 6 76 46 75 72 84 29 58 59 13 17 82 9 83 4 36 56 53 7 64 44\r\n", "output": "428380105\r\n"}]
false
stdio
null
true
711/D
711
D
Python 3
TESTS
3
62
7,168,000
125259672
import math import sys from decimal import Decimal n=int(input()) arr=list(map(int,input().split())) adj={} visited=[False]*(n+1) rev=[] def dfs2(u,comp): comp.add(u) visited[u]=True for v in adj[u]: if not visited[v]: dfs2(v,comp) return comp def dfs1(u): visited[u]=True for v in adj[u]: if not visited[v]: dfs1(v) rev.append(u) return def main(arr,n): mod=10**9+7 global adj global visited dp=[] for i in range(len(arr)): a,b=i+1,arr[i] if a not in adj: adj[a]=[] if b not in adj: adj[b]=[] adj[a].append(b) for i in range(1,n+1): if not visited[i]: dfs1(i) adj={} visited=[False]*(n+1) for i in range(len(arr)): a,b=i+1,arr[i] if a not in adj: adj[a]=[] if b not in adj: adj[b]=[] adj[b].append(a) components=[] while len(rev): i=rev.pop() comp=set() if not visited[i]: dfs2(i,comp) components.append(comp) dp.append(0) tot=0 ans=pow(2,n,mod) a=1 for i in range(len(components)): comp=components[i] l=len(comp) tot+=l if len(comp)>1: val=0 val+=(pow(2,l,mod)-1)*dp[-1]+pow(2,tot-l+a,mod) a=0 val%=mod dp.append(val) return (ans-dp[-1])%mod print(main(arr,n))
131
249
14,745,600
201808730
mod = 1000000007 def solve(A): n = len(A) aa = [0] for x in A: aa.append(x) idx = [0] * (n+1) res = pos = 1 for i in range(1, n + 1): if not idx[i]: j, start = i, pos while not idx[j]: idx[j] = pos pos += 1 j = aa[j] if idx[j] >= start: n -= pos - idx[j] res = res * (pow(2, pos - idx[j], mod) - 2) % mod print(res * pow(2, n, mod) % mod) nn = int(input()) aa = list(map(int, input().strip().split())) solve(aa)
Codeforces Round 369 (Div. 2)
CF
2,016
2
256
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.
null
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $$1 \rightarrow 2$$, $$2\rightarrow3$$, $$\overset{3}{\rightarrow}1$$ initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[{"input": "3\n2 3 1", "output": "6"}, {"input": "4\n2 1 1 1", "output": "8"}, {"input": "5\n2 4 2 5 3", "output": "28"}]
1,900
["combinatorics", "dfs and similar", "graphs", "math"]
131
[{"input": "3\r\n2 3 1\r\n", "output": "6\r\n"}, {"input": "4\r\n2 1 1 1\r\n", "output": "8\r\n"}, {"input": "5\r\n2 4 2 5 3\r\n", "output": "28\r\n"}, {"input": "4\r\n2 1 4 3\r\n", "output": "4\r\n"}, {"input": "7\r\n2 3 4 1 6 5 4\r\n", "output": "56\r\n"}, {"input": "20\r\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1\r\n", "output": "1048574\r\n"}, {"input": "2\r\n2 1\r\n", "output": "2\r\n"}, {"input": "84\r\n2 50 67 79 71 45 43 40 57 20 25 8 60 47 52 10 37 23 1 28 22 26 3 42 11 63 61 68 49 32 55 18 5 24 31 70 66 27 38 41 54 12 65 51 15 34 30 35 77 74 21 62 33 16 81 14 19 48 80 73 69 78 39 6 76 46 75 72 84 29 58 59 13 17 82 9 83 4 36 56 53 7 64 44\r\n", "output": "428380105\r\n"}]
false
stdio
null
true
469/B
469
B
Python 3
TESTS
2
31
0
223779281
p,q,l,r=map(int,input().split());ap=[];aq=[];count=0 for i in range(p): ap.append(list(map(int,input().split()))) for i in range(q): aq.append(list(map(int,input().split()))) for i in range(l,r+1): bol=False for j in aq: for j2 in ap: if j2[0]<=j[0]+i<j2[1] or j2[0]<=j[1]+i<=j2[1]: count+=1 bol=True break if bol: break print(count+1)
31
93
0
7874206
p,q,x,y = map(int, input().split()) a = [0 for i in range(p)] b = [0 for i in range(p)] c = [0 for i in range(q)] d = [0 for i in range(q)] for i in range(p): a[i], b[i] = map(int, input().split()) for i in range(q): c[i], d[i] = map(int, input().split()) ans = 0 def comp(k,l,m,n): if m <= l and k <= n: return 0 #eq elif m >= l: return 1 #ab<cd else: return -1 #ab>cd for t in range(x, y+1): i = 0 j = 0 while i < p and j < q: ## print('i = ',i,'; j = ',j) z = comp(a[i], b[i], c[j] + t, d[j] + t) ## print('comp(', a[i],',',b[i],',',c[j]+t,',',d[j]+t,') = ',z) if z == 0: ans += 1 break elif z == 1: i += 1 else: j += 1 print(ans)
Codeforces Round 268 (Div. 2)
CF
2,014
1
256
Chat Online
Little X and Little Z are good friends. They always chat online. But both of them have schedules. Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between c1 and d1, between c2 and d2, ..., between cq and dq (all borders inclusive). But if he gets up at time t, these segments will be shifted by t. They become [ci + t, di + t] (for all i). If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between l and r (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [l, r] suit for that?
The first line contains four space-separated integers p, q, l, r (1 ≤ p, q ≤ 50; 0 ≤ l ≤ r ≤ 1000). Each of the next p lines contains two space-separated integers ai, bi (0 ≤ ai < bi ≤ 1000). Each of the next q lines contains two space-separated integers cj, dj (0 ≤ cj < dj ≤ 1000). It's guaranteed that bi < ai + 1 and dj < cj + 1 for all valid i and j.
Output a single integer — the number of moments of time from the segment [l, r] which suit for online conversation.
null
null
[{"input": "1 1 0 4\n2 3\n0 1", "output": "3"}, {"input": "2 3 0 20\n15 17\n23 26\n1 4\n7 11\n15 17", "output": "20"}]
1,300
["implementation"]
31
[{"input": "1 1 0 4\r\n2 3\r\n0 1\r\n", "output": "3\r\n"}, {"input": "2 3 0 20\r\n15 17\r\n23 26\r\n1 4\r\n7 11\r\n15 17\r\n", "output": "20\r\n"}, {"input": "5 2 27 452\r\n148 154\r\n421 427\r\n462 470\r\n777 786\r\n969 978\r\n245 247\r\n313 322\r\n", "output": "54\r\n"}, {"input": "3 6 25 785\r\n273 275\r\n391 397\r\n775 783\r\n84 89\r\n348 354\r\n480 483\r\n552 556\r\n711 716\r\n838 844\r\n", "output": "99\r\n"}, {"input": "1 6 364 421\r\n649 688\r\n31 39\r\n438 441\r\n516 524\r\n609 615\r\n708 710\r\n850 851\r\n", "output": "0\r\n"}, {"input": "7 10 87 239\r\n8 23\r\n325 374\r\n516 540\r\n633 658\r\n728 742\r\n833 839\r\n960 995\r\n99 114\r\n213 232\r\n264 269\r\n321 327\r\n492 540\r\n551 559\r\n587 590\r\n625 637\r\n704 723\r\n750 764\r\n", "output": "151\r\n"}, {"input": "33 17 295 791\r\n41 49\r\n66 73\r\n95 102\r\n118 126\r\n157 158\r\n189 198\r\n228 237\r\n247 251\r\n301 307\r\n318 326\r\n328 333\r\n356 363\r\n373 381\r\n454 460\r\n463 466\r\n471 477\r\n500 501\r\n505 510\r\n559 566\r\n585 588\r\n597 604\r\n675 684\r\n688 695\r\n699 705\r\n749 755\r\n780 788\r\n869 873\r\n879 888\r\n890 892\r\n909 918\r\n953 954\r\n973 978\r\n993 996\r\n53 60\r\n68 74\r\n102 105\r\n149 153\r\n191 206\r\n230 242\r\n249 252\r\n320 325\r\n483 488\r\n509 513\r\n523 524\r\n544 560\r\n651 655\r\n670 672\r\n691 708\r\n742 748\r\n920 939\r\n", "output": "497\r\n"}, {"input": "5 4 520 527\r\n257 263\r\n309 315\r\n434 439\r\n540 541\r\n759 763\r\n168 176\r\n313 316\r\n546 548\r\n880 881\r\n", "output": "0\r\n"}, {"input": "11 40 58 976\r\n14 22\r\n85 92\r\n110 112\r\n173 181\r\n188 190\r\n212 218\r\n494 498\r\n530 531\r\n647 656\r\n943 948\r\n960 968\r\n2 16\r\n20 31\r\n40 86\r\n90 91\r\n93 96\r\n103 118\r\n128 155\r\n170 173\r\n176 192\r\n205 207\r\n210 217\r\n237 245\r\n250 280\r\n302 304\r\n311 328\r\n332 376\r\n387 419\r\n422 442\r\n449 454\r\n462 491\r\n496 498\r\n501 516\r\n525 552\r\n556 565\r\n567 573\r\n577 578\r\n586 635\r\n651 677\r\n688 699\r\n704 714\r\n718 719\r\n733 766\r\n768 769\r\n773 811\r\n822 826\r\n830 870\r\n885 917\r\n937 961\r\n971 981\r\n991 1000\r\n", "output": "909\r\n"}, {"input": "10 28 435 847\r\n48 57\r\n86 95\r\n186 188\r\n297 304\r\n500 506\r\n594 600\r\n602 609\r\n802 811\r\n906 911\r\n916 921\r\n20 22\r\n115 118\r\n139 141\r\n170 171\r\n184 188\r\n193 197\r\n227 230\r\n232 235\r\n250 252\r\n256 260\r\n271 275\r\n322 324\r\n326 328\r\n379 381\r\n433 434\r\n528 529\r\n563 565\r\n583 584\r\n614 615\r\n617 619\r\n631 632\r\n726 729\r\n750 754\r\n814 817\r\n853 855\r\n881 882\r\n946 947\r\n981 984\r\n", "output": "284\r\n"}, {"input": "13 42 292 733\r\n304 308\r\n362 365\r\n396 397\r\n686 688\r\n719 722\r\n815 816\r\n901 902\r\n904 905\r\n921 924\r\n929 933\r\n953 954\r\n977 980\r\n982 985\r\n28 30\r\n36 37\r\n108 112\r\n123 127\r\n134 135\r\n151 153\r\n160 162\r\n203 205\r\n208 212\r\n240 243\r\n261 264\r\n271 274\r\n294 297\r\n356 358\r\n383 385\r\n408 412\r\n415 418\r\n435 439\r\n444 447\r\n500 502\r\n507 511\r\n515 519\r\n525 529\r\n541 543\r\n566 569\r\n577 579\r\n606 609\r\n618 622\r\n655 656\r\n715 718\r\n744 745\r\n767 771\r\n798 802\r\n828 830\r\n839 840\r\n842 845\r\n893 894\r\n897 898\r\n902 906\r\n958 960\r\n981 983\r\n988 992\r\n", "output": "412\r\n"}, {"input": "5 46 211 943\r\n367 371\r\n405 408\r\n639 642\r\n821 825\r\n974 978\r\n13 14\r\n31 34\r\n36 39\r\n48 51\r\n82 86\r\n173 174\r\n193 196\r\n227 230\r\n249 250\r\n259 261\r\n292 294\r\n325 327\r\n329 330\r\n352 353\r\n380 383\r\n390 391\r\n398 399\r\n411 414\r\n418 420\r\n424 427\r\n478 479\r\n488 489\r\n500 502\r\n511 514\r\n534 535\r\n548 552\r\n581 584\r\n596 600\r\n609 611\r\n618 622\r\n641 642\r\n656 657\r\n674 678\r\n707 709\r\n718 720\r\n746 748\r\n752 755\r\n771 773\r\n775 777\r\n865 869\r\n892 896\r\n910 911\r\n946 948\r\n963 964\r\n977 978\r\n986 990\r\n", "output": "428\r\n"}, {"input": "1 8 169 472\r\n63 553\r\n32 65\r\n75 204\r\n263 277\r\n289 326\r\n342 441\r\n452 911\r\n945 956\r\n971 986\r\n", "output": "304\r\n"}, {"input": "2 1 17 179\r\n159 202\r\n579 602\r\n115 126\r\n", "output": "55\r\n"}, {"input": "1 1 0 1000\r\n0 1000\r\n0 1000\r\n", "output": "1001\r\n"}, {"input": "10 11 201 515\r\n2 3\r\n102 103\r\n202 203\r\n302 304\r\n401 402\r\n502 503\r\n600 603\r\n701 702\r\n800 803\r\n900 902\r\n1 2\r\n103 104\r\n201 202\r\n302 304\r\n400 404\r\n501 504\r\n600 601\r\n603 604\r\n701 704\r\n800 801\r\n900 902\r\n", "output": "26\r\n"}, {"input": "1 7 140 478\r\n400 404\r\n3 4\r\n100 105\r\n301 304\r\n403 405\r\n504 506\r\n600 605\r\n904 906\r\n", "output": "16\r\n"}, {"input": "9 8 453 552\r\n5 18\r\n23 28\r\n125 132\r\n208 209\r\n215 230\r\n516 527\r\n808 819\r\n906 913\r\n926 929\r\n4 18\r\n221 229\r\n316 330\r\n403 424\r\n506 516\r\n805 828\r\n904 914\r\n916 917\r\n", "output": "49\r\n"}, {"input": "9 1 24 52\r\n63 94\r\n150 164\r\n244 275\r\n379 385\r\n413 420\r\n441 490\r\n506 545\r\n614 661\r\n752 776\r\n531 534\r\n", "output": "0\r\n"}, {"input": "1 1 0 0\r\n1 3\r\n2 5\r\n", "output": "1\r\n"}]
false
stdio
null
true
316/E1
316
E1
PyPy 3-64
TESTS1
7
154
2,969,600
179947019
import sys input = sys.stdin.readline n, m = map(int, input().split()) w = list(map(int, input().split())) M = 10**9 d = [1, 1] for i in range(n-2): d.append(d[-1]+d[-2]) for _ in range(m): a, b, c = map(int, input().split()) if a == 2: q, e = 0, 0 for i in range(b-1, c): q += d[e]*w[i] e += 1 print(q) else: w[b-1] = c
19
828
102,400
3862075
from sys import * from math import * mod = 1000000000 f = [0 for i in range(200)] f[0] = f[1] = 1 for i in range(2, 200): f[i] = f[i - 1] + f[i - 2] n, m = stdin.readline().split() n = int(n) m = int(m) a = list(map(int, stdin.readline().split())) for i in range(m): tp, x, y = stdin.readline().split() tp = int(tp) x = int(x) y = int(y) if tp == 1: x -= 1 a[x] = y else: s = 0 x -= 1 y -= 1 for p in range(y - x + 1): s += f[p] * a[x + p] print(s % mod)
ABBYY Cup 3.0
ICPC
2,013
3
256
Summer Homework
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum $$\sum_{x=0}^{r_i-l_i} (f_x \cdot a_{l_i+x})$$, where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type: - if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105); - if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n); - if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105). The input limits for scoring 30 points are (subproblem E1): - It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): - It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): - No extra limitations.
For each query print the calculated sum modulo 1000000000 (109).
null
null
[{"input": "5 5\n1 3 1 2 4\n2 1 4\n2 1 5\n2 2 4\n1 3 10\n2 1 5", "output": "12\n32\n8\n50"}, {"input": "5 4\n1 3 1 2 4\n3 1 4 1\n2 2 4\n1 2 10\n2 1 5", "output": "12\n45"}]
1,500
["brute force", "data structures"]
19
[{"input": "5 5\r\n1 3 1 2 4\r\n2 1 4\r\n2 1 5\r\n2 2 4\r\n1 3 10\r\n2 1 5\r\n", "output": "12\r\n32\r\n8\r\n50\r\n"}, {"input": "1 3\r\n2\r\n2 1 1\r\n1 1 3\r\n2 1 1\r\n", "output": "2\r\n3\r\n"}, {"input": "11 11\r\n6 1 9 0 2 9 1 6 2 8 0\r\n2 9 9\r\n1 9 0\r\n1 1 8\r\n2 2 5\r\n2 7 11\r\n2 2 8\r\n1 3 2\r\n1 10 0\r\n2 1 8\r\n2 9 11\r\n1 9 7\r\n", "output": "2\r\n16\r\n31\r\n147\r\n234\r\n0\r\n"}, {"input": "11 18\r\n14 13 18 17 14 17 13 3 0 3 21\r\n2 6 9\r\n2 1 6\r\n2 5 7\r\n2 1 3\r\n2 1 9\r\n2 3 9\r\n2 2 5\r\n2 7 10\r\n2 1 5\r\n2 4 6\r\n2 10 11\r\n2 4 5\r\n2 2 8\r\n2 3 9\r\n2 1 5\r\n2 2 3\r\n2 2 6\r\n1 4 19\r\n", "output": "36\r\n320\r\n57\r\n63\r\n552\r\n203\r\n107\r\n25\r\n184\r\n65\r\n24\r\n31\r\n335\r\n203\r\n184\r\n31\r\n192\r\n"}, {"input": "12 26\r\n18 5 13 38 33 11 30 24 6 34 11 30\r\n2 1 12\r\n2 1 12\r\n2 1 11\r\n1 3 15\r\n1 11 5\r\n2 1 11\r\n2 2 10\r\n2 3 12\r\n2 2 11\r\n2 3 11\r\n2 3 10\r\n2 3 11\r\n1 9 37\r\n1 2 37\r\n2 1 11\r\n1 3 30\r\n2 2 12\r\n1 4 42\r\n2 3 10\r\n2 1 11\r\n1 11 26\r\n1 7 37\r\n2 3 11\r\n1 7 30\r\n1 6 40\r\n1 7 13\r\n", "output": "8683\r\n8683\r\n4363\r\n3833\r\n2084\r\n3106\r\n2359\r\n1456\r\n1286\r\n1456\r\n4919\r\n5727\r\n1708\r\n4961\r\n2627\r\n"}]
false
stdio
null
true
774/A
774
A
Python 3
TESTS
5
93
6,963,200
86267037
import math n,c1,c2=map(int,input().split()) s=input() cnt=s.count('1') if(cnt==1): print(int(c1+c2*math.pow((n-1),2))) else: if(n%2): l=int(c1+c2*math.pow((n-1),2)) r=int(2*c1+c2*math.pow(int((n+1)/2)-1,2)+c2*math.pow(int((n-1)/2)-1,2)) print(min(l,r)) else: l=int(c1+c2*math.pow((n-1),2)) r=2*int(c1+c2*math.pow(int(n/2)-1,2)) print(min(l,r))
31
62
7,987,200
216484354
num_people, cost1, cost2 = map(int, input().split()) adults_count = input().count('1') cost_list = [] for i in range(1, adults_count + 1): cost = cost1 * i cost += i * cost2 * (((num_people // i) - 1) ** 2) cost += cost2 * (num_people % i) * (2 * (num_people // i) - 1) cost_list.append(cost) print(min(cost_list))
VK Cup 2017 - Wild Card Round 1
ICPC
2,017
2
256
Amusement Park
Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once. Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1 + c2·(x - 1)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group.
The first line contains three integers n, c1 and c2 (1 ≤ n ≤ 200 000, 1 ≤ c1, c2 ≤ 107) — the number of visitors and parameters for determining the ticket prices for a group. The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.
Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.
null
In the first test one group of three people should go to the attraction. Then they have to pay 4 + 1 * (3 - 1)2 = 8. In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7 + 2 * (2 - 1)2 = 9. Thus, the total price for two groups is 18.
[{"input": "3 4 1\n011", "output": "8"}, {"input": "4 7 2\n1101", "output": "18"}]
2,100
["*special", "ternary search"]
31
[{"input": "3 4 1\r\n011\r\n", "output": "8\r\n"}, {"input": "4 7 2\r\n1101\r\n", "output": "18\r\n"}, {"input": "1 2 2\r\n1\r\n", "output": "2\r\n"}, {"input": "2 3 10\r\n01\r\n", "output": "13\r\n"}, {"input": "5 10 3\r\n11100\r\n", "output": "35\r\n"}, {"input": "10 2 2\r\n1111101111\r\n", "output": "20\r\n"}, {"input": "20 3 13\r\n01111110011111010101\r\n", "output": "120\r\n"}, {"input": "50 13 44\r\n11101110100110111100010110001111001001110010111011\r\n", "output": "1270\r\n"}, {"input": "100 1000 1000\r\n0000010100101100110100101111001111111111100101111100111011110001011110110111111010000000101000111000\r\n", "output": "100000\r\n"}]
false
stdio
null
true
711/D
711
D
PyPy 3-64
TESTS
3
108
4,505,600
207137933
import random, sys, os, math, gc from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations, product from heapq import nsmallest, nlargest, heapify, heappop, heappush from io import BytesIO, IOBase from copy import deepcopy from bisect import bisect_left, bisect_right from math import factorial, gcd from operator import mul, xor, __or__ from types import GeneratorType input = lambda: sys.stdin.readline().rstrip("\r\n") def main(): M = 10 ** 9 + 7 n = int(input()) edge = list(map(int, input().split())) # 形成环 g = [[] for _ in range(n + 1)] st = [False] * (n + 1) dis = [0] * (n + 1) mx = 0 for i, x in enumerate(edge, 1): g[x].append(i) g[i].append(x) def dfs(u : int, dep : int) -> None: st[u] = True dis[u] = dep for x in g[u]: if not st[x]: dfs(x, dep + 1) elif dis[x]: nonlocal mx mx = max(mx, dep + 1 - dis[x]) dis[u] = 0 for i in range(1, n + 1): if not st[i]: dfs(i, 1) ans = (pow(2, n, M) - pow(2, n - mx, M) * 2 + M) % M print(ans) main()
131
265
34,816,000
207132155
n = int(input()) l = list(map(int, input().split())) l.insert(0, 0) mark = {} loop, pos, res, mod = 0, 1, 1, int(1e9 + 7) for i in range(1, n+1): if not i in mark: start, j = pos, i while not j in mark: mark[j] = pos pos += 1 j = l[j] if mark[j] >= start: size = pos - mark[j] loop += size res *= pow(2, size, mod) - 2 + mod res %= mod res = (res * pow(2, n - loop, mod)) % mod print(res)
Codeforces Round 369 (Div. 2)
CF
2,016
2
256
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.
null
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $$1 \rightarrow 2$$, $$2\rightarrow3$$, $$\overset{3}{\rightarrow}1$$ initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[{"input": "3\n2 3 1", "output": "6"}, {"input": "4\n2 1 1 1", "output": "8"}, {"input": "5\n2 4 2 5 3", "output": "28"}]
1,900
["combinatorics", "dfs and similar", "graphs", "math"]
131
[{"input": "3\r\n2 3 1\r\n", "output": "6\r\n"}, {"input": "4\r\n2 1 1 1\r\n", "output": "8\r\n"}, {"input": "5\r\n2 4 2 5 3\r\n", "output": "28\r\n"}, {"input": "4\r\n2 1 4 3\r\n", "output": "4\r\n"}, {"input": "7\r\n2 3 4 1 6 5 4\r\n", "output": "56\r\n"}, {"input": "20\r\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1\r\n", "output": "1048574\r\n"}, {"input": "2\r\n2 1\r\n", "output": "2\r\n"}, {"input": "84\r\n2 50 67 79 71 45 43 40 57 20 25 8 60 47 52 10 37 23 1 28 22 26 3 42 11 63 61 68 49 32 55 18 5 24 31 70 66 27 38 41 54 12 65 51 15 34 30 35 77 74 21 62 33 16 81 14 19 48 80 73 69 78 39 6 76 46 75 72 84 29 58 59 13 17 82 9 83 4 36 56 53 7 64 44\r\n", "output": "428380105\r\n"}]
false
stdio
null
true
774/I
774
I
PyPy 3-64
TESTS
5
77
2,252,800
198743280
n = int(input()) s = [] for i in range(n): s.append(input()) t = input() l = len(t) dp = [float('inf')] * (l+1) dp[0] = 0 for i in range(1, min(55, l) + 1): for j in range(n): if len(s[j]) < i: continue if t[:i] == s[j][-i:]: dp[i] = 1 for i in range(1, l+1): for j in range(max(0, i-55), i): for k in range(n): if len(s[k]) != i-j: continue if s[k] == t[j:i]: dp[i] = min(dp[i], dp[j]+1) for i in range(max(0, l-55), l): for j in range(n): if len(s[j]) < l-i: continue if t[i:] == s[j][:l-i]: dp[l] = min(dp[l], dp[i]+1) if dp[l] >= float('inf')/2: dp[l] = -1 print(dp[l])
46
124
2,764,800
198880859
import sys import math MAXN = 55 INF = 1e9 MOD = 1e9+7 L_INF = 4e18 EPS = 1e-10 n = int(input()) s = [] for i in range(n): s.append(input()) t = input() l = len(t) dp = [INF] * (l + 1) dp[0] = 0 for i in range(l): for j in range(n): _l, _r = i, 0 while _r < len(s[j]) and _l < l: if s[j][_r] == t[_l]: _l += 1 _r += 1 dp[_l] = min(dp[_l], dp[i] + 1) if dp[l] >= INF / 2: dp[l] = -1 print(dp[l])
VK Cup 2017 - Wild Card Round 1
ICPC
2,017
2
256
Composing Of String
Stepan has a set of n strings. Also, he has a favorite string s. Stepan wants to do the following. He will take some strings of his set and write them down one after another. It is possible that he will take some strings more than once, and will not take some of them at all. Your task is to determine the minimum number of strings in the set which Stepan needs to take and write so that the string s appears as a subsequence in the resulting written down string. For example, in the string "abcd" strings "ad", "acd", "abcd" appear as subsequences, and strings "ba", "abdc" don't appear as subsequences.
The first line contains the integer n (1 ≤ n ≤ 50) — the number of strings in Stepan's set. The next n lines contain n non-empty strings consisting of lowercase letters of the English alphabet. The length of each of these strings does not exceed 50 symbols. It is possible that some strings from Stepan's set are the same. The next line contains the non-empty string s, consisting of lowercase letters of the English alphabet — Stepan's favorite string. The length of this string doesn't exceed 2500 symbols.
Print the minimum number of strings which Stepan should take from the set and write them down one after another so that the string s appears as a subsequence in the resulting written down string. Each string from the set should be counted as many times as Stepan takes it from the set. If the answer doesn't exsist, print -1.
null
In the first test, Stepan can take, for example, the third and the second strings from the set, write them down, and get exactly his favorite string. In the second example Stepan can take, for example, the second, the third and again the second strings from the set and write them down. Then he will get a string "aabaaaab", in which his favorite string "baaab" is a subsequence. In the third test Stepan can not get his favorite string, because it contains the letter "c", which is not presented in any of the strings in the set.
[{"input": "3\na\naa\na\naaa", "output": "2"}, {"input": "4\nab\naab\naa\nbb\nbaaab", "output": "3"}, {"input": "2\naaa\nbbb\naaacbbb", "output": "-1"}]
2,300
["*special", "dp"]
46
[{"input": "3\r\na\r\naa\r\na\r\naaa\r\n", "output": "2\r\n"}, {"input": "4\r\nab\r\naab\r\naa\r\nbb\r\nbaaab\r\n", "output": "3\r\n"}, {"input": "2\r\naaa\r\nbbb\r\naaacbbb\r\n", "output": "-1\r\n"}, {"input": "4\r\naab\r\naa\r\nbb\r\naba\r\nbaaab\r\n", "output": "2\r\n"}, {"input": "2\r\naaaaaaaa\r\nabbaaaaaaa\r\nbbbbbbbbbabbbbbbbbbbbbbbbbbbbbabbbbbbbbbbbbbbbbbbbbbbbbabbbbbabbabbbbbbbbbbbbbbbbbbbabbabbbbababbbbbbbbabbbbb\r\n", "output": "52\r\n"}, {"input": "1\r\nlol\r\nlol\r\n", "output": "1\r\n"}]
false
stdio
null
true
962/E
962
E
Python 3
TESTS
0
78
204,800
92462928
n = int(input()) s = 0 x = [] c = [] for i in range(n): a,b = input().split() x.append(int(a)) c.append(b) for i in range(n-1): if c[i] != c[0]: continue if (c[i] == c[i+1] or c[i+1] == "P"): s += x[i+1] - x[i] else: for j in range(i+2, n): if(c[i] == c[j] or c[j] == "P"): s += x[j] - x[i] break for i in range(n-1, 1, -1): if c[i] == c[0]: continue if ((c[i] == c[i-1] and c[i-1] != "P") or (c[i] != "P" and c[i-1] == "P")): s += x[i] - x[i-1] else: for j in range(i-2, 0, -1): if(c[i] == c[j] or c[j] == "P"): s += x[i] - x[j] break print(s)
45
1,326
24,678,400
37233335
#!/usr/bin/env python3 M = 4 * 10**9 + 1 n = int(input().strip()) f = lambda t: (int(t[0]), t[1]) # read and add far P points at both ends xcis = [(-M, 'P')] + [f(input().strip().split()) for _ in range(n)] + [(M, 'P')] iPs = [i for i in range(len(xcis)) if (xcis[i][1] == 'P')] iRs = [i for i in range(len(xcis)) if (xcis[i][1] == 'R')] iBs = [i for i in range(len(xcis)) if (xcis[i][1] == 'B')] l = 0 for iiP in range(1, len(iPs)): iP0 = iPs[iiP - 1] iP1 = iPs[iiP] dRmax = 0 dBmax = 0 (xR, _) = xcis[iP0] (xB, _) = xcis[iP0] for i in range(iP0 + 1, iP1 + 1): (x, c) = xcis[i] if c in 'RP': dRmax = max(dRmax, x - xR) xR = x if c in 'BP': dBmax = max(dBmax, x - xB) xB = x d = xcis[iP1][0] - xcis[iP0][0] l += d + min(d, 2*d - dBmax - dRmax) if iiP in [1, len(iPs) - 1]: l -= d # remove connections to extra P points iP0 = iP1 if len(iPs) == 2: # no P in original data l = (0 if (len(iRs) < 2) else (xcis[iRs[-1]][0] - xcis[iRs[0]][0])) l += (0 if (len(iBs) < 2) else (xcis[iBs[-1]][0] - xcis[iBs[0]][0])) print (l)
Educational Codeforces Round 42 (Rated for Div. 2)
ICPC
2,018
2
256
Byteland, Berland and Disputed Cities
The cities of Byteland and Berland are located on the axis $$$Ox$$$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $$$Ox$$$ there are three types of cities: - the cities of Byteland, - the cities of Berland, - disputed cities. Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected. The countries agreed to connect the pairs of cities with BNET cables in such a way that: - If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, - If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables. Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities. The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected. Each city is a point on the line $$$Ox$$$. It is technically possible to connect the cities $$$a$$$ and $$$b$$$ with a cable so that the city $$$c$$$ ($$$a < c < b$$$) is not connected to this cable, where $$$a$$$, $$$b$$$ and $$$c$$$ are simultaneously coordinates of the cities $$$a$$$, $$$b$$$ and $$$c$$$.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^{5}$$$) — the number of cities. The following $$$n$$$ lines contains an integer $$$x_i$$$ and the letter $$$c_i$$$ ($$$-10^{9} \le x_i \le 10^{9}$$$) — the coordinate of the city and its type. If the city belongs to Byteland, $$$c_i$$$ equals to 'B'. If the city belongs to Berland, $$$c_i$$$ equals to «R». If the city is disputed, $$$c_i$$$ equals to 'P'. All cities have distinct coordinates. Guaranteed, that the cities are given in the increasing order of their coordinates.
Print the minimal total length of such set of cables, that if we delete all Berland cities ($$$c_i$$$='R'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables. Similarly, if we delete all Byteland cities ($$$c_i$$$='B'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables.
null
In the first example, you should connect the first city with the second, the second with the third, and the third with the fourth. The total length of the cables will be $$$5 + 3 + 4 = 12$$$. In the second example there are no disputed cities, so you need to connect all the neighboring cities of Byteland and all the neighboring cities of Berland. The cities of Berland have coordinates $$$10, 21, 32$$$, so to connect them you need two cables of length $$$11$$$ and $$$11$$$. The cities of Byteland have coordinates $$$14$$$ and $$$16$$$, so to connect them you need one cable of length $$$2$$$. Thus, the total length of all cables is $$$11 + 11 + 2 = 24$$$.
[{"input": "4\n-5 R\n0 P\n3 P\n7 B", "output": "12"}, {"input": "5\n10 R\n14 B\n16 B\n21 R\n32 R", "output": "24"}]
2,200
["constructive algorithms", "greedy"]
45
[{"input": "4\r\n-5 R\r\n0 P\r\n3 P\r\n7 B\r\n", "output": "12\r\n"}, {"input": "5\r\n10 R\r\n14 B\r\n16 B\r\n21 R\r\n32 R\r\n", "output": "24\r\n"}, {"input": "10\r\n66 R\r\n67 R\r\n72 R\r\n73 R\r\n76 R\r\n78 B\r\n79 B\r\n83 B\r\n84 B\r\n85 P\r\n", "output": "26\r\n"}, {"input": "10\r\n61 R\r\n64 R\r\n68 R\r\n71 R\r\n72 R\r\n73 R\r\n74 P\r\n86 P\r\n87 B\r\n90 B\r\n", "output": "29\r\n"}, {"input": "15\r\n-9518 R\r\n-6858 P\r\n-6726 B\r\n-6486 R\r\n-4496 P\r\n-4191 P\r\n-772 B\r\n-258 R\r\n-194 P\r\n1035 R\r\n2297 P\r\n4816 B\r\n5779 R\r\n9342 B\r\n9713 B\r\n", "output": "25088\r\n"}, {"input": "6\r\n-8401 R\r\n-5558 P\r\n-3457 P\r\n-2361 R\r\n6966 P\r\n8140 B\r\n", "output": "17637\r\n"}, {"input": "2\r\n1 R\r\n2 R\r\n", "output": "1\r\n"}, {"input": "2\r\n-1000000000 B\r\n1000000000 R\r\n", "output": "0\r\n"}, {"input": "2\r\n-1000000000 P\r\n1000000000 P\r\n", "output": "2000000000\r\n"}, {"input": "2\r\n-1000000000 B\r\n1000000000 P\r\n", "output": "2000000000\r\n"}, {"input": "9\r\n-105 R\r\n-81 B\r\n-47 P\r\n-25 R\r\n-23 B\r\n55 P\r\n57 R\r\n67 B\r\n76 P\r\n", "output": "272\r\n"}, {"input": "6\r\n-13 R\r\n-10 P\r\n-6 R\r\n-1 P\r\n4 R\r\n10 P\r\n", "output": "32\r\n"}, {"input": "8\r\n-839 P\r\n-820 P\r\n-488 P\r\n-334 R\r\n-83 B\r\n187 R\r\n380 B\r\n804 P\r\n", "output": "2935\r\n"}, {"input": "8\r\n-12 P\r\n-9 B\r\n-2 R\r\n-1 R\r\n2 B\r\n8 B\r\n9 R\r\n15 P\r\n", "output": "54\r\n"}, {"input": "6\r\n0 B\r\n3 P\r\n7 B\r\n9 B\r\n11 P\r\n13 B\r\n", "output": "17\r\n"}]
false
stdio
null
true
961/E
961
E
PyPy 3-64
TESTS
3
62
0
198868848
import sys from array import array input = lambda: sys.stdin.buffer.readline().decode().rstrip() inp = lambda dtype: [dtype(x) for x in input().split()] debug = lambda *x: print(*x, file=sys.stderr) ceil_ = lambda a, b: (a + b - 1) // b sum_n = lambda n: (n * (n + 1)) // 2 get_bit = lambda x, i: (x >> i) & 1 Mint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, [] class FenwickTree: def __init__(self, n): self.n = n + 1 self.Bit = [0] * self.n def fill(self, a): for i in range(len(a)): self.update(i, a[i]) def get_sum(self, ix): ret, ix = 0, ix + 1 while ix > 0: ret += self.Bit[ix] ix -= ix & (-ix) return ret def query(self, l, r): '''[l,r]''' return self.get_sum(r) - self.get_sum(l - 1) def update(self, ix, val): ix += 1 while ix < self.n: self.Bit[ix] += val ix += ix & (-ix) for _ in range(1): n, a = int(input()), array('i', inp(int)) tree, ans = FenwickTree(n + 1), 0 for i in range(n): a[i] = min(a[i], n) tree.update(a[i], 1) for i in range(n): tree.update(a[i], -1) ans += tree.query(i + 1, a[i]) out.append(ans) print('\n'.join(map(str, out)))
30
732
24,268,800
58653185
from sys import stdin from sys import setrecursionlimit as SRL; SRL(10**7) rd = stdin.readline rrd = lambda: map(int, rd().strip().split()) n = int(input()) a = list(rrd()) bit = [0]*(n+100) def ins(x): while x<=n: bit[x] += 1 x += x&(-x) def get(l): tot = 0 while l: tot += bit[l] l -= l&(-l) return tot ta = [] pans = 0 for i in range(len(a)): if a[i] > i: pans += 1 ta.append([i+1, a[i]]) ta.sort(key=lambda x: x[1]) ans = 0 now = 0 for x in ta: while now < min(n,x[1]): if a[now] <= n: ins(a[now]) now += 1 ans += now - get(x[0]-1) print((ans-pans)//2)
Educational Codeforces Round 41 (Rated for Div. 2)
ICPC
2,018
2
256
Tufurama
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method. TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
The first line contains one integer n (1 ≤ n ≤ 2·105) — the number of seasons. The second line contains n integers separated by space a1, a2, ..., an (1 ≤ ai ≤ 109) — number of episodes in each season.
Print one integer — the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.
null
Possible pairs in the second example: 1. x = 1, y = 2 (season 1 episode 2 $$\text{The formula used to produce the text is not provided in the image.}$$ season 2 episode 1); 2. x = 2, y = 3 (season 2 episode 3 $$\text{The formula used to produce the text is not provided in the image.}$$ season 3 episode 2); 3. x = 1, y = 3 (season 1 episode 3 $$\text{The formula used to produce the text is not provided in the image.}$$ season 3 episode 1). In the third example: 1. x = 1, y = 2 (season 1 episode 2 $$\text{The formula used to produce the text is not provided in the image.}$$ season 2 episode 1); 2. x = 1, y = 3 (season 1 episode 3 $$\text{The formula used to produce the text is not provided in the image.}$$ season 3 episode 1).
[{"input": "5\n1 2 3 4 5", "output": "0"}, {"input": "3\n8 12 7", "output": "3"}, {"input": "3\n3 2 1", "output": "2"}]
1,900
["data structures"]
30
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "0\r\n"}, {"input": "3\r\n8 12 7\r\n", "output": "3\r\n"}, {"input": "3\r\n3 2 1\r\n", "output": "2\r\n"}, {"input": "5\r\n2 3 4 5 6\r\n", "output": "4\r\n"}, {"input": "8\r\n7 2 6 6 5 1 4 9\r\n", "output": "9\r\n"}, {"input": "10\r\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000\r\n", "output": "45\r\n"}, {"input": "1\r\n1\r\n", "output": "0\r\n"}]
false
stdio
null
true
962/E
962
E
Python 3
TESTS
18
717
19,660,800
37684244
# B R P def solve2(length, cities): result = 0 for idx, city in enumerate(cities): cityCode = city[1] cityIdx = city[0] it = idx - 1 visitedP = False visitedN = False visitedB = False visitedR = False BValue = 0 RValue = 0 PValue = 0 while(it >= 0): neighbourCode = cities[it][1] neighbourIdx = cities[it][0] if(cityCode == 'P' ): if(neighbourCode == 'B' and visitedB == False): visitedB = True BValue = neighbourIdx elif(neighbourCode == 'R' and visitedR == False): visitedR = True RValue = neighbourIdx elif(neighbourCode == 'P' and visitedP == False): visitedP = True PValue = neighbourIdx it -= 1 if(visitedP and visitedB and visitedR): break continue if(neighbourCode == cityCode and visitedN == False): visitedN = True result += abs(cities[it][0] - cityIdx) break if(neighbourCode == 'P' and visitedP == False): visitedP = True result += abs(cities[it][0] - cityIdx) break it -= 1 if(cityCode == 'P'): if(visitedB != False and visitedR != False and visitedP != False): result += min(abs(RValue - cityIdx) + abs(BValue - cityIdx), abs(PValue - cityIdx)) elif(visitedP != False): result += abs(PValue - cityIdx) elif(visitedB != False and visitedR != False): result += abs(RValue - cityIdx) + abs(BValue - cityIdx) elif(visitedB != False): result += abs(BValue - cityIdx) elif(visitedR != False): result += abs(RValue - cityIdx) return result def solve(length, cities): result = 0 lastP = -1 lastB = -1 lastR = -1 maxB = 0 maxR = 0 for idx, city in enumerate(cities): i, code = city if(code == 'B'): if(lastB != -1): result += abs(i - lastB) maxB = max(maxB, abs(i - lastB)) lastB = i if(code == 'R'): if(lastR != -1): result += abs(i - lastR) maxR = max(maxR, abs(i - lastR)) lastR = i if(code == 'P'): if(lastB != -1 and lastB != lastP): result += abs(i - lastB) maxB = max(maxB, abs(i - lastB)) if(lastR != -1 and lastR != lastP): result += abs(i - lastR) maxR = max(maxR, abs(i - lastR)) if(lastP != -1): if(lastB > lastP or lastR > lastP): candidate = result - maxB - maxR + abs(i - lastP) #print("1): ", candidate, maxR, maxB, result) result += abs(i - lastP) - maxB - maxR #print("2): ", result) result = min(result, candidate) else: result += abs(i - lastP) maxB = 0 maxR = 0 lastB = i lastR = i lastP = i return result if __name__ == '__main__': length = int(input()) cities = [] for i in range(length): data = input().split(" ") cities.append((int(data[0]), data[1])) result = solve(length, cities) print(result)
45
1,887
31,232,000
37344651
n=int(input()) b,r,p=None,None,None res=0 mr=-1 mb=-1 for i in range(n): ix,t=input().split() ix=int(ix) if t!='R': if b is not None: res+=ix-b mb=max(mb,ix-b) b=ix if t!='B': if r is not None: res+=ix-r mr=max(mr,ix-r) r=ix if t=='P': if p is not None: if ix-p<mr+mb:res-=(mr+mb)-(ix-p) p=ix mr=mb=0 print(res)
Educational Codeforces Round 42 (Rated for Div. 2)
ICPC
2,018
2
256
Byteland, Berland and Disputed Cities
The cities of Byteland and Berland are located on the axis $$$Ox$$$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $$$Ox$$$ there are three types of cities: - the cities of Byteland, - the cities of Berland, - disputed cities. Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected. The countries agreed to connect the pairs of cities with BNET cables in such a way that: - If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, - If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables. Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities. The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected. Each city is a point on the line $$$Ox$$$. It is technically possible to connect the cities $$$a$$$ and $$$b$$$ with a cable so that the city $$$c$$$ ($$$a < c < b$$$) is not connected to this cable, where $$$a$$$, $$$b$$$ and $$$c$$$ are simultaneously coordinates of the cities $$$a$$$, $$$b$$$ and $$$c$$$.
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^{5}$$$) — the number of cities. The following $$$n$$$ lines contains an integer $$$x_i$$$ and the letter $$$c_i$$$ ($$$-10^{9} \le x_i \le 10^{9}$$$) — the coordinate of the city and its type. If the city belongs to Byteland, $$$c_i$$$ equals to 'B'. If the city belongs to Berland, $$$c_i$$$ equals to «R». If the city is disputed, $$$c_i$$$ equals to 'P'. All cities have distinct coordinates. Guaranteed, that the cities are given in the increasing order of their coordinates.
Print the minimal total length of such set of cables, that if we delete all Berland cities ($$$c_i$$$='R'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables. Similarly, if we delete all Byteland cities ($$$c_i$$$='B'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables.
null
In the first example, you should connect the first city with the second, the second with the third, and the third with the fourth. The total length of the cables will be $$$5 + 3 + 4 = 12$$$. In the second example there are no disputed cities, so you need to connect all the neighboring cities of Byteland and all the neighboring cities of Berland. The cities of Berland have coordinates $$$10, 21, 32$$$, so to connect them you need two cables of length $$$11$$$ and $$$11$$$. The cities of Byteland have coordinates $$$14$$$ and $$$16$$$, so to connect them you need one cable of length $$$2$$$. Thus, the total length of all cables is $$$11 + 11 + 2 = 24$$$.
[{"input": "4\n-5 R\n0 P\n3 P\n7 B", "output": "12"}, {"input": "5\n10 R\n14 B\n16 B\n21 R\n32 R", "output": "24"}]
2,200
["constructive algorithms", "greedy"]
45
[{"input": "4\r\n-5 R\r\n0 P\r\n3 P\r\n7 B\r\n", "output": "12\r\n"}, {"input": "5\r\n10 R\r\n14 B\r\n16 B\r\n21 R\r\n32 R\r\n", "output": "24\r\n"}, {"input": "10\r\n66 R\r\n67 R\r\n72 R\r\n73 R\r\n76 R\r\n78 B\r\n79 B\r\n83 B\r\n84 B\r\n85 P\r\n", "output": "26\r\n"}, {"input": "10\r\n61 R\r\n64 R\r\n68 R\r\n71 R\r\n72 R\r\n73 R\r\n74 P\r\n86 P\r\n87 B\r\n90 B\r\n", "output": "29\r\n"}, {"input": "15\r\n-9518 R\r\n-6858 P\r\n-6726 B\r\n-6486 R\r\n-4496 P\r\n-4191 P\r\n-772 B\r\n-258 R\r\n-194 P\r\n1035 R\r\n2297 P\r\n4816 B\r\n5779 R\r\n9342 B\r\n9713 B\r\n", "output": "25088\r\n"}, {"input": "6\r\n-8401 R\r\n-5558 P\r\n-3457 P\r\n-2361 R\r\n6966 P\r\n8140 B\r\n", "output": "17637\r\n"}, {"input": "2\r\n1 R\r\n2 R\r\n", "output": "1\r\n"}, {"input": "2\r\n-1000000000 B\r\n1000000000 R\r\n", "output": "0\r\n"}, {"input": "2\r\n-1000000000 P\r\n1000000000 P\r\n", "output": "2000000000\r\n"}, {"input": "2\r\n-1000000000 B\r\n1000000000 P\r\n", "output": "2000000000\r\n"}, {"input": "9\r\n-105 R\r\n-81 B\r\n-47 P\r\n-25 R\r\n-23 B\r\n55 P\r\n57 R\r\n67 B\r\n76 P\r\n", "output": "272\r\n"}, {"input": "6\r\n-13 R\r\n-10 P\r\n-6 R\r\n-1 P\r\n4 R\r\n10 P\r\n", "output": "32\r\n"}, {"input": "8\r\n-839 P\r\n-820 P\r\n-488 P\r\n-334 R\r\n-83 B\r\n187 R\r\n380 B\r\n804 P\r\n", "output": "2935\r\n"}, {"input": "8\r\n-12 P\r\n-9 B\r\n-2 R\r\n-1 R\r\n2 B\r\n8 B\r\n9 R\r\n15 P\r\n", "output": "54\r\n"}, {"input": "6\r\n0 B\r\n3 P\r\n7 B\r\n9 B\r\n11 P\r\n13 B\r\n", "output": "17\r\n"}]
false
stdio
null
true
713/C
713
C
PyPy 3
TESTS
1
124
0
67950940
def mySol(arr, n): mod = 0 if arr[0] > arr[1]: mod = arr[0]-arr[1] + 1 arr[0] = arr[1]-1 for i in range(1, n-1): am = arr[i] a0 = arr[i-1] a1 = arr[i+1] if a0 < am < a1: continue if a1 < am : possDed = am - a0 - 1 if possDed > (am-a1) + 1: mod += am - a1 am = a1 else: mod += possDed am -= possDed mod += am - a1 + 1 a1 = am + 1 arr[i],arr[i-1],arr[i+1] = am, a0, a1 # print(arr) return mod n = int(input()) arr = list(map(int, input().split())) print(mySol(arr,n))
57
155
4,915,200
178123174
# LUOGU_RID: 91828776 import sys # sys.setrecursionlimit(int(1e9)) # import random from collections import Counter, defaultdict, deque from functools import lru_cache, reduce # from itertools import accumulate,product from heapq import nsmallest, nlargest, heapify, heappop, heappush # from bisect import bisect_left,bisect_right # from sortedcontainers import SortedList # input = sys.stdin.buffer.readline # import re input = lambda:sys.stdin.readline().rstrip("\r\n") def mp():return list(map(int,input().split())) def it():return int(input()) # import math MOD = int(1e9 + 7) INF = int(1e18) def solve(): n=it() nums=mp() ans,pq=0,[] for i,num in enumerate(nums): if pq and -pq[0]>num-i: ans+=-heappop(pq)-num+i heappush(pq,-num+i) # 使小于当前横坐标值的线段保持其之前的斜率 rank 值 heappush(pq,-num+i) # 所有斜率都减一 print(ans) return if __name__ == '__main__': # t=it() # for _ in range(t): # solve() # n=it() # n,m,i=mp() # n,m=mp() solve()
Codeforces Round 371 (Div. 1)
CF
2,016
5
256
Sonya and Problem Wihtout a Legend
Sonya was unable to think of a story for this problem, so here comes the formal description. You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.
The first line of the input contains a single integer n (1 ≤ n ≤ 3000) — the length of the array. Next line contains n integer ai (1 ≤ ai ≤ 109).
Print the minimum number of operation required to make the array strictly increasing.
null
In the first sample, the array is going to look as follows: 2 3 5 6 7 9 11 |2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9 And for the second sample: 1 2 3 4 5 |5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12
[{"input": "7\n2 1 5 11 5 9 11", "output": "9"}, {"input": "5\n5 4 3 2 1", "output": "12"}]
2,300
["dp", "sortings"]
57
[{"input": "7\r\n2 1 5 11 5 9 11\r\n", "output": "9\r\n"}, {"input": "5\r\n5 4 3 2 1\r\n", "output": "12\r\n"}, {"input": "2\r\n1 1000\r\n", "output": "0\r\n"}, {"input": "2\r\n1000 1\r\n", "output": "1000\r\n"}, {"input": "5\r\n100 80 60 70 90\r\n", "output": "54\r\n"}, {"input": "10\r\n10 16 17 11 1213 1216 1216 1209 3061 3062\r\n", "output": "16\r\n"}, {"input": "20\r\n103 103 110 105 107 119 113 121 116 132 128 124 128 125 138 137 140 136 154 158\r\n", "output": "43\r\n"}, {"input": "1\r\n1\r\n", "output": "0\r\n"}, {"input": "5\r\n1 1 1 2 3\r\n", "output": "3\r\n"}, {"input": "1\r\n1000\r\n", "output": "0\r\n"}, {"input": "50\r\n499 780 837 984 481 526 944 482 862 136 265 605 5 631 974 967 574 293 969 467 573 845 102 224 17 873 648 120 694 996 244 313 404 129 899 583 541 314 525 496 443 857 297 78 575 2 430 137 387 319\r\n", "output": "12423\r\n"}, {"input": "75\r\n392 593 98 533 515 448 220 310 386 79 539 294 208 828 75 534 875 493 94 205 656 105 546 493 60 188 222 108 788 504 809 621 934 455 307 212 630 298 938 62 850 421 839 134 950 256 934 817 209 559 866 67 990 835 534 672 468 768 757 516 959 893 275 315 692 927 321 554 801 805 885 12 67 245 495\r\n", "output": "17691\r\n"}, {"input": "10\r\n26 723 970 13 422 968 875 329 234 983\r\n", "output": "2546\r\n"}, {"input": "20\r\n245 891 363 6 193 704 420 447 237 947 664 894 512 194 513 616 671 623 686 378\r\n", "output": "3208\r\n"}, {"input": "5\r\n850 840 521 42 169\r\n", "output": "1485\r\n"}]
false
stdio
null
true
283/B
283
B
PyPy 3
TESTS
2
310
0
72115387
""" NTC here """ import sys inp = sys.stdin.readline def input(): return inp().strip() flush = sys.stdout.flush # import threading # sys.setrecursionlimit(10**6) # threading.stack_size(2**25) def iin(): return int(input()) def lin(): return list(map(int, input().split())) # range = xrange # input = raw_input def main(): n = iin() a = [0]+lin() for i in range(1, n): if i-a[i]<0 : a[i]=a[i] elif i-a[i]==0: a[i]=-1 else: if a[i-a[i]] != -1: a[i] = a[i]+a[i-a[i]] else: a[i] = -1 print(a[i]+ (i if a[i]!=-1 else 0)) # print(a) main() # threading.Thread(target=main).start()
50
466
29,696,000
171032684
n = int(input()) t = [0, 0] t += list(map(int, input().split())) n += 1 a = [0] * n b = [0] * n n -= 1 a[1] = b[1] = -1 #print(t, a, b) def calc(s, a, b, l): global t l.reverse() j = 0 n = len(l) while True: s += t[l[j]] a[l[j]] = s j += 1 if j == n: return s += t[l[j]] b[l[j]] = s j += 1 if j == n: return def calc2(i, k): global a, b l = [] if k: a[i] = -1 l.append(i) i += t[i] while True: if i > n: return calc(0, a, b, l) if b[i] > 0: return calc(b[i], a, b, l) if b[i] == -1: return b[i] = -1 l.append(i) i -= t[i] if i < 1: return calc(0, b, a, l) if a[i] > 0: return calc(a[i], b, a, l) if a[i] == -1: return a[i] -= 1 l.append(i) i += t[i] for i in range(2, n + 1): if a[i] == 0: calc2(i, True) if b[i] == 0: calc2(i, False) for i in range(1, n): if b[i + 1] > 0: t[i] = i + b[i + 1] else: t[i] = -1 #print(t, a, b) print('\n'.join(map(str, t[1:n])))
Codeforces Round 174 (Div. 1)
CF
2,013
2
256
Cow Program
Farmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a1, a2, ..., an of positive integers: 1. Initially, x = 1 and y = 0. If, after any step, x ≤ 0 or x > n, the program immediately terminates. 2. The program increases both x and y by a value equal to ax simultaneously. 3. The program now increases y by ax while decreasing x by ax. 4. The program executes steps 2 and 3 (first step 2, then step 3) repeatedly until it terminates (it may never terminate). So, the sequence of executed steps may start with: step 2, step 3, step 2, step 3, step 2 and so on. The cows are not very good at arithmetic though, and they want to see how the program works. Please help them! You are given the sequence a2, a3, ..., an. Suppose for each i (1 ≤ i ≤ n - 1) we run the program on the sequence i, a2, a3, ..., an. For each such run output the final value of y if the program terminates or -1 if it does not terminate.
The first line contains a single integer, n (2 ≤ n ≤ 2·105). The next line contains n - 1 space separated integers, a2, a3, ..., an (1 ≤ ai ≤ 109).
Output n - 1 lines. On the i-th line, print the requested value when the program is run on the sequence i, a2, a3, ...an. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
null
In the first sample 1. For i = 1,  x becomes $$1 \rightarrow 2 \rightarrow 0$$ and y becomes 1 + 2 = 3. 2. For i = 2,  x becomes $$1 \rightarrow 3 \rightarrow - 1$$ and y becomes 2 + 4 = 6. 3. For i = 3,  x becomes $$1 \rightarrow 4 \rightarrow 3 \rightarrow 7$$ and y becomes 3 + 1 + 4 = 8.
[{"input": "4\n2 4 1", "output": "3\n6\n8"}, {"input": "3\n1 2", "output": "-1\n-1"}]
1,700
["dfs and similar", "dp", "graphs"]
50
[{"input": "4\r\n2 4 1\r\n", "output": "3\r\n6\r\n8\r\n"}, {"input": "3\r\n1 2\r\n", "output": "-1\r\n-1\r\n"}, {"input": "5\r\n2 2 1 3\r\n", "output": "3\r\n-1\r\n-1\r\n-1\r\n"}, {"input": "2\r\n1\r\n", "output": "-1\r\n"}, {"input": "8\r\n7 6 2 6 2 6 6\r\n", "output": "8\r\n8\r\n12\r\n10\r\n-1\r\n-1\r\n20\r\n"}, {"input": "8\r\n4 5 3 2 3 3 3\r\n", "output": "5\r\n7\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n"}, {"input": "3\r\n1 1\r\n", "output": "-1\r\n-1\r\n"}, {"input": "5\r\n3 2 4 2\r\n", "output": "4\r\n-1\r\n7\r\n-1\r\n"}, {"input": "10\r\n6 7 5 3 1 5 2 4 6\r\n", "output": "7\r\n9\r\n8\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n"}, {"input": "8\r\n6 311942309 3 1 3 2 2\r\n", "output": "7\r\n311942311\r\n-1\r\n311942323\r\n311942317\r\n311942321\r\n12\r\n"}, {"input": "8\r\n2 3 1 2 2 3 3\r\n", "output": "3\r\n5\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n"}, {"input": "6\r\n2 1 2 2 3\r\n", "output": "3\r\n-1\r\n-1\r\n-1\r\n-1\r\n"}, {"input": "23\r\n20 1 3 3 13 11 9 7 5 3 1 7 2 4 6 8 10 12 14 16 12 5\r\n", "output": "21\r\n-1\r\n-1\r\n-1\r\n18\r\n17\r\n16\r\n-1\r\n26\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n48\r\n-1\r\n37\r\n"}, {"input": "71\r\n28 11 39 275858941 64 69 66 18 468038892 49 47 45 43 41 39 37 35 33 31 29 27 25 23 21 19 17 15 13 11 9 7 5 3 1 25 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 701366631 51 25 11 11 49 33 67 43 57\r\n", "output": "29\n13\n42\n275858945\n69\n75\n73\n26\n468038901\n59\n58\n57\n56\n55\n54\n53\n52\n51\n50\n49\n48\n47\n-1\n-1\n113\n468038935\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n-1\n701366692\n-1\n-1\n111\n114\n-1\n-1\n-1\n-1\n-1\n"}, {"input": "23\r\n11 6 21 9 13 11 9 7 5 3 1 8 2 4 6 8 10 12 14 935874687 21 1\r\n", "output": "12\r\n8\r\n24\r\n13\r\n18\r\n17\r\n16\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n-1\r\n935874707\r\n-1\r\n44\r\n"}, {"input": "71\r\n2 50 62 41 50 16 65 6 49 47 45 43 41 39 37 35 33 31 29 27 25 23 21 19 17 15 13 11 9 7 5 3 1 26 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 14 6 67 54 54 620768469 637608010 27 54 18 49\r\n", "output": "3\n52\n65\n45\n55\n22\n72\n801\n58\n57\n56\n55\n54\n53\n52\n51\n50\n49\n48\n47\n46\n45\n831\n1067\n87\n1147\n891\n671\n487\n339\n227\n151\n111\n105\n109\n117\n129\n145\n165\n189\n217\n249\n285\n325\n369\n417\n469\n525\n585\n649\n717\n789\n865\n945\n1029\n1117\n1209\n1305\n1405\n543\n109\n129\n1413\n1317\n620768534\n637608076\n843\n973\n121\n515\n"}]
false
stdio
null
true
379/B
379
B
Python 3
TESTS
5
202
1,843,200
150938472
n=int(input()) s=list(map(int,input().split())) a=[] while sum(s)>0: for i in range(n): if s[i]>0: a.append("P") s[i]-=1 if i<n-1: a.append("R") i+=1 a.append("L") for j in range(n-1): if s[n-2-j]>0: a.append("P") s[n-2-j]-=1 if j<n-2: a.append("L") j+=1 while a[len(a)-1]!="P": a=a[:len(a)-1] print("".join(a))
15
46
204,800
200589946
n = int(input()) arr = list(map(int,input().split())) # print((a*b-1)//(b-1)) ans = 'PRL'*arr[0] for i in range(1,n): ans+='R'+'PLR'*arr[i] print(ans)
Good Bye 2013
CF
2,013
1
256
New Year Present
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put ai coins to the i-th wallet from the left. Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row. Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.
The first line contains integer n (2 ≤ n ≤ 300) — the number of wallets. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 300). It is guaranteed that at least one ai is positive.
Print the sequence that consists of k (1 ≤ k ≤ 106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet n. As a result of the performed operations, the i-th wallet from the left must contain exactly ai coins. If there are multiple answers, you can print any of them.
null
null
[{"input": "2\n1 2", "output": "PRPLRP"}, {"input": "4\n0 2 0 2", "output": "RPRRPLLPLRRRP"}]
1,200
["constructive algorithms", "implementation"]
15
[{"input": "2\r\n1 2\r\n", "output": "PRPLRP"}, {"input": "4\r\n0 2 0 2\r\n", "output": "RPRRPLLPLRRRP"}, {"input": "10\r\n2 3 4 0 0 1 1 3 4 2\r\n", "output": "PRPRPRRRPRPRPRPRPLPLPLLLLLPLPLPRPRPRRRRRPRPRPLPLLLLLLPLL"}, {"input": "10\r\n0 0 0 0 0 0 0 0 1 0\r\n", "output": "RRRRRRRRPR"}, {"input": "5\r\n2 2 2 2 2\r\n", "output": "PRPRPRPRPLPLPLPLPRRRRP"}, {"input": "2\r\n6 0\r\n", "output": "PRLPRLPRLPRLPRLP"}]
false
stdio
import sys def main(input_path, output_path, sub_output_path): with open(input_path) as f: n = int(f.readline()) a = list(map(int, f.readline().split())) with open(sub_output_path) as f: s = f.read().strip() if len(s) < 1 or len(s) > 10**6: print(0) return valid_chars = {'L', 'R', 'P'} for c in s: if c not in valid_chars: print(0) return coins = [0] * n current_pos = 1 # 1-based position prev_was_p = False for c in s: if c == 'P': if prev_was_p: print(0) return coins[current_pos - 1] += 1 prev_was_p = True else: if c == 'L': if current_pos == 1: print(0) return current_pos -= 1 else: # 'R' if current_pos == n: print(0) return current_pos += 1 prev_was_p = False if coins == a: print(1) else: print(0) if __name__ == "__main__": input_path = sys.argv[1] output_path = sys.argv[2] sub_output_path = sys.argv[3] main(input_path, output_path, sub_output_path)
true
961/E
961
E
PyPy 3
TESTS
3
109
0
50576307
N = int(input()) A = list(map(int, input().split())) def getsum(BITTree,i): s = 0 i = i+1 while i > 0: s += BITTree[i] i -= i & (-i) return s def updatebit(BITTree , n , i ,v): i += 1 while i <= n: BITTree[i] += v i += i & (-i) def construct(arr, n): BITTree = [0]*(n+1) for i in range(n): updatebit(BITTree, n, i, arr[i]) return BITTree BIT = construct([0]*(N+1), N+1) ans = 0 for i in range(1, N+1): #s = "" #for j in range(N+1): # s += str(getsum(BIT,j)) + " " #print(s) a = min(A[i-1],N) #print(a) ans += min(a, getsum(BIT, a)) #print("getsum", getsum(BIT, a)-getsum(BIT,a-1)) updatebit(BIT, N+1, 1,1) updatebit(BIT, N+1, a+1,-1) print(ans)
30
1,465
77,004,800
36972134
import sys class RangeBit: def __init__(self, n): sz = 1 while n >= sz: sz *= 2 self.size = sz self.dataAdd = [0 for _ in range(sz)] self.dataMul = [0 for _ in range(sz)] def sum(self, i): assert i > 0 add, mul, start = 0, 0, i while i > 0: add += self.dataAdd[i] mul += self.dataMul[i] i -= i & -i return mul * start + add def add(self, left, right, by): assert 0 < left <= right self._add(left, by, -by * (left - 1)) self._add(right, -by, by * right) def _add(self, i, mul, add): assert i > 0 while i < self.size: self.dataAdd[i] += add self.dataMul[i] += mul i += i & -i n = int(input()) l = list(map(int, sys.stdin.readline().split())) queries = [] for i in range(n): if min(l[i], n) >= i+2: queries.append((i+2, min(l[i], n), i+1)) result = 0 a = sorted(list(zip(range(1, n+1), l)) + queries, key=lambda x:(-x[-1], len(x))) ft = RangeBit(n+1) for el in a: #print(el) if len(el) == 2: #update ind, val = el ft.add(ind, ind, 1) else: #query fr, to, val = el # print(fr, to, val) # print(ft.sum(to) - (ft.sum(fr - 1) if fr > 1 else 0)) result += ft.sum(to) - (ft.sum(fr - 1) if fr > 1 else 0) print(result)
Educational Codeforces Round 41 (Rated for Div. 2)
ICPC
2,018
2
256
Tufurama
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method. TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
The first line contains one integer n (1 ≤ n ≤ 2·105) — the number of seasons. The second line contains n integers separated by space a1, a2, ..., an (1 ≤ ai ≤ 109) — number of episodes in each season.
Print one integer — the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.
null
Possible pairs in the second example: 1. x = 1, y = 2 (season 1 episode 2 $$\text{The formula used to produce the text is not provided in the image.}$$ season 2 episode 1); 2. x = 2, y = 3 (season 2 episode 3 $$\text{The formula used to produce the text is not provided in the image.}$$ season 3 episode 2); 3. x = 1, y = 3 (season 1 episode 3 $$\text{The formula used to produce the text is not provided in the image.}$$ season 3 episode 1). In the third example: 1. x = 1, y = 2 (season 1 episode 2 $$\text{The formula used to produce the text is not provided in the image.}$$ season 2 episode 1); 2. x = 1, y = 3 (season 1 episode 3 $$\text{The formula used to produce the text is not provided in the image.}$$ season 3 episode 1).
[{"input": "5\n1 2 3 4 5", "output": "0"}, {"input": "3\n8 12 7", "output": "3"}, {"input": "3\n3 2 1", "output": "2"}]
1,900
["data structures"]
30
[{"input": "5\r\n1 2 3 4 5\r\n", "output": "0\r\n"}, {"input": "3\r\n8 12 7\r\n", "output": "3\r\n"}, {"input": "3\r\n3 2 1\r\n", "output": "2\r\n"}, {"input": "5\r\n2 3 4 5 6\r\n", "output": "4\r\n"}, {"input": "8\r\n7 2 6 6 5 1 4 9\r\n", "output": "9\r\n"}, {"input": "10\r\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000\r\n", "output": "45\r\n"}, {"input": "1\r\n1\r\n", "output": "0\r\n"}]
false
stdio
null
true
961/F
961
F
PyPy 3-64
TESTS
1
61
1,433,600
168239894
import random import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def is_Prime(n): if n == 1: return False for i in range(2, min(int(n ** (1 / 2)) + 2, n)): if n % i == 0: return False return True def random_mod(): mod = random.randint(5 * pow(10, 8), pow(10, 9)) if not mod % 2: mod += 1 while not is_Prime(mod): mod += 2 while not min(mod % 3, mod % 5): mod += 2 return mod def binary_search(c1, c2, u): c = (c1 + c2 + 1) // 2 while abs(c1 - c2) > 1: c = (c1 + c2 + 1) // 2 if ok(c, u): c1 = c else: c2 = c c += 2 while not ok(c, u): c -= 1 return c def ok(c, u): if not c: return True if c > u: return False l1, r1 = u - c, u + c l2, r2 = n - u - 1 - c, n - u - 1 + c for i in range(2): mod, hi, xi = m[i], h[i], x[i] h1 = (hi[r1 + 1] - hi[l1]) % mod * xi[l1] % mod h2 = (hi[r2 + 1] - hi[l2]) % mod * xi[l2] % mod if h1 ^ h2: return False return True n = int(input()) s = list(input().rstrip()) for i in range(n): s[i] -= 96 m = [random_mod() for _ in range(2)] h, x = [], [] b = 29 for i in range(2): mod = m[i] b0, h0 = 1, [0, s[0]] for j in range(1, n): b0 = 27 * b0 % mod h0.append((b0 * s[j] % mod + h0[-1]) % mod) x0 = [pow(b0, mod - 2, mod)] for _ in range(n - 1): x0.append(27 * x0[-1] % mod) x0.reverse() h.append(h0) x.append(x0) ans = [-1] * (n // 2 + 1) for i in range(n // 2): if s[i] ^ s[-i - 1]: continue c = binary_search(0, i + 1, i) ans[i - c] = max(ans[i - c], 2 * c + 1) for i in range(1, n // 2 + 1): ans[i] = max(ans[i], ans[i - 1] - 2, -1) sys.stdout.write(" ".join(map(str, ans)))
44
592
48,025,600
168241300
import random import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def is_Prime(n): if n == 1: return False for i in range(2, min(int(n ** (1 / 2)) + 2, n)): if n % i == 0: return False return True def random_mod(): mod = random.randint(5 * pow(10, 8), pow(10, 9)) if not mod % 2: mod += 1 while not is_Prime(mod): mod += 2 while not min(mod % 3, mod % 5): mod += 2 return mod def binary_search(c1, c2, u): c = (c1 + c2 + 1) // 2 while abs(c1 - c2) > 1: c = (c1 + c2 + 1) // 2 if ok(c, u): c1 = c else: c2 = c c += 2 while not ok(c, u): c -= 1 return c def ok(c, u): if not c: return True if c > u: return False l1, r1 = u - c, u + c l2, r2 = n - u - 1 - c, n - u - 1 + c h1 = (h[r1 + 1] - h[l1]) % mod * x[l1] % mod h2 = (h[r2 + 1] - h[l2]) % mod * x[l2] % mod return False if h1 ^ h2 else True n = int(input()) s = list(input().rstrip()) for i in range(n): s[i] -= 96 mod = random_mod() b, h = 1, [0, s[0]] for j in range(1, n): b = 29 * b % mod h.append((b * s[j] % mod + h[-1]) % mod) x = [pow(b, mod - 2, mod)] for _ in range(n - 1): x.append(29 * x[-1] % mod) x.reverse() ans = [-1] * (n // 2 + n % 2) for i in range(n // 2): if s[i] ^ s[-i - 1]: continue c = binary_search(0, i + 1, i) ans[i - c] = max(ans[i - c], 2 * c + 1) for i in range(1, n // 2 + n % 2): ans[i] = max(ans[i], ans[i - 1] - 2, -1) sys.stdout.write(" ".join(map(str, ans)))
Educational Codeforces Round 41 (Rated for Div. 2)
ICPC
2,018
4
256
k-substrings
You are given a string s consisting of n lowercase Latin letters. Let's denote k-substring of s as a string subsk = sksk + 1..sn + 1 - k. Obviously, subs1 = s, and there are exactly $$\left\lceil \frac{n}{2} \right\rceil$$ such substrings. Let's call some string t an odd proper suprefix of a string T iff the following conditions are met: - |T| > |t|; - |t| is an odd number; - t is simultaneously a prefix and a suffix of T. For evey k-substring ($$k \in [1,\left\lceil \frac{n}{2} \right\rceil]$$) of s you have to calculate the maximum length of its odd proper suprefix.
The first line contains one integer n (2 ≤ n ≤ 106) — the length s. The second line contains the string s consisting of n lowercase Latin letters.
Print $$\left\lceil \frac{n}{2} \right\rceil$$ integers. i-th of them should be equal to maximum length of an odd proper suprefix of i-substring of s (or - 1, if there is no such string that is an odd proper suprefix of i-substring).
null
The answer for first sample test is folowing: - 1-substring: bcabcabcabcabca - 2-substring: cabcabcabcabc - 3-substring: abcabcabcab - 4-substring: bcabcabca - 5-substring: cabcabc - 6-substring: abcab - 7-substring: bca - 8-substring: c
[{"input": "15\nbcabcabcabcabca", "output": "9 7 5 3 1 -1 -1 -1"}, {"input": "24\nabaaabaaaabaaabaaaabaaab", "output": "15 13 11 9 7 5 3 1 1 -1 -1 1"}, {"input": "19\ncabcabbcabcabbcabca", "output": "5 3 1 -1 -1 1 1 -1 -1 -1"}]
2,700
["binary search", "hashing", "string suffix structures"]
44
[{"input": "15\r\nbcabcabcabcabca\r\n", "output": "9 7 5 3 1 -1 -1 -1\r\n"}, {"input": "24\r\nabaaabaaaabaaabaaaabaaab\r\n", "output": "15 13 11 9 7 5 3 1 1 -1 -1 1\r\n"}, {"input": "19\r\ncabcabbcabcabbcabca\r\n", "output": "5 3 1 -1 -1 1 1 -1 -1 -1\r\n"}, {"input": "2\r\nza\r\n", "output": "-1\r\n"}, {"input": "20\r\nbbbaaabbbbbbbbaaabbb\r\n", "output": "9 7 5 3 1 1 7 5 3 1\r\n"}, {"input": "2\r\nzz\r\n", "output": "1\r\n"}, {"input": "3\r\ndad\r\n", "output": "1 -1\r\n"}, {"input": "4\r\naccd\r\n", "output": "-1 1\r\n"}, {"input": "5\r\naabcd\r\n", "output": "-1 -1 -1\r\n"}, {"input": "6\r\nbcabbd\r\n", "output": "-1 -1 -1\r\n"}, {"input": "7\r\nbaaaadd\r\n", "output": "-1 -1 1 -1\r\n"}]
false
stdio
null
true
28/B
28
B
Python 3
TESTS
1
218
409,600
50622642
n=int(input()) from collections import defaultdict d=defaultdict(list) a=[int(i) for i in input().split()] b=[int(i) for i in input().split()] for i in range(n): x=b[i] if i-x>=0: d[i].append(i-x) d[i-x].append(i) if i+x<n: d[i].append(i+x) d[i+x].append(i) for i in range(n): d[i].append(i) #print(d) f=1 for i in range(0,n): loc=0 q=[i] vis=[0]*n vis[i]=1 while q: t=q.pop() # print(t) if a[t]==b[i]: loc=1 for i in d[t]: if not vis[i]: vis[i]=1 q.append(i) if loc==0: print(i) f=0 if f: print('YES') else: print('NO')
33
124
6,963,200
115960096
n=int(input()) orden= input().split() fav= input().split() arr=[] for i in range(n): orden[i]=int(orden[i]) fav[i]=int(fav[i]) arr.append(i) def union(el): if arr[el] != el: arr[el] = union(arr[el]) return arr[el] cont=0 for i in fav: if cont >= i: arr[union(cont)] = union(cont - i) if cont < n - i: arr[union(cont)] = union(cont + i) cont += 1 flag = True for i in range(n): if union(arr[i])==union(orden[i]-1): continue else: flag = False if flag: print("YES") else: print("NO")
Codeforces Beta Round 28 (Codeforces format)
CF
2,010
2
256
pSort
One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited. The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.
The first line contains positive integer n (1 ≤ n ≤ 100) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.
If the given state is reachable in the described game, output YES, otherwise NO.
null
null
[{"input": "5\n5 4 3 2 1\n1 1 1 1 1", "output": "YES"}, {"input": "7\n4 3 5 1 2 7 6\n4 6 6 1 6 6 1", "output": "NO"}, {"input": "7\n4 2 5 1 3 7 6\n4 6 6 1 6 6 1", "output": "YES"}]
1,600
["dfs and similar", "dsu", "graphs"]
33
[{"input": "5\r\n5 4 3 2 1\r\n1 1 1 1 1\r\n", "output": "YES\r\n"}, {"input": "7\r\n4 3 5 1 2 7 6\r\n4 6 6 1 6 6 1\r\n", "output": "NO\r\n"}, {"input": "7\r\n4 2 5 1 3 7 6\r\n4 6 6 1 6 6 1\r\n", "output": "YES\r\n"}, {"input": "6\r\n3 2 1 4 6 5\r\n3 6 1 6 6 1\r\n", "output": "YES\r\n"}, {"input": "6\r\n3 5 1 4 6 2\r\n3 6 1 6 6 1\r\n", "output": "NO\r\n"}, {"input": "4\r\n1 2 3 4\r\n1 1 1 1\r\n", "output": "YES\r\n"}, {"input": "13\r\n13 1 12 4 6 10 7 8 9 3 11 5 2\r\n6 12 12 7 11 7 10 3 1 5 2 2 1\r\n", "output": "NO\r\n"}, {"input": "5\r\n1 3 2 4 5\r\n1 4 1 2 4\r\n", "output": "YES\r\n"}, {"input": "10\r\n6 2 9 4 8 7 5 10 3 1\r\n2 9 7 9 4 5 1 5 3 2\r\n", "output": "YES\r\n"}, {"input": "8\r\n5 2 3 4 8 6 1 7\r\n6 7 7 7 7 7 2 7\r\n", "output": "YES\r\n"}, {"input": "17\r\n1 11 3 4 5 6 7 8 9 10 2 12 13 14 15 16 17\r\n13 9 16 5 16 12 11 4 4 7 12 16 2 7 14 6 3\r\n", "output": "YES\r\n"}, {"input": "19\r\n7 2 17 18 4 16 1 9 12 10 8 11 6 13 14 19 3 5 15\r\n12 4 9 1 13 18 14 10 18 2 17 16 12 3 16 6 5 7 7\r\n", "output": "NO\r\n"}, {"input": "1\r\n1\r\n1\r\n", "output": "YES\r\n"}, {"input": "2\r\n1 2\r\n2 2\r\n", "output": "YES\r\n"}, {"input": "2\r\n1 2\r\n1 1\r\n", "output": "YES\r\n"}, {"input": "2\r\n2 1\r\n2 2\r\n", "output": "NO\r\n"}, {"input": "2\r\n2 1\r\n1 1\r\n", "output": "YES\r\n"}]
false
stdio
null
true
711/D
711
D
Python 3
TESTS
3
30
0
201802043
MOD = 1000000007 def dfs2(u, cycles, cyclecnt, visited, a): cycles[cyclecnt] += 1 visited[u] = 3 if visited[a[u]] == 3: return dfs2(a[u], cycles, cyclecnt, visited, a) def dfs(u, cycles, cyclecnt, visited, a): visited[u] = 2 if visited[a[u]] == 0: dfs(a[u], cycles, cyclecnt, visited, a) elif visited[a[u]] == 1: visited[u] = 1 return else: cycles.append(0) dfs2(u, cycles, cyclecnt, visited, a) cyclecnt += 1 visited[u] = 1 def solve(A): n = len(A) a = [0]*(n+1) visited = [0]*(n+1) cycles = [] for i in range(n): a[i+1] = A[i] cyclecnt = 0 ans = 0 dp = [1]*(n+1) for i in range(1, n+1): dp[i] = (dp[i-1]*2)%MOD ans = 1 for i in range(1, n+1): if visited[i] == 0: dfs(i, cycles, cyclecnt, visited, a) cnt = n for i in range(len(cycles)): cnt -= cycles[i] ans = (ans*(dp[cycles[i]]-2+MOD))%MOD ans = (ans*dp[cnt])%MOD if ans < 0: ans += MOD print(ans) nn = int(input().strip()) aa = list(map(int, input().strip().split())) solve(aa)
131
342
43,622,400
88162972
from sys import stdin n = int(stdin.readline()) a = [int(x)-1 for x in stdin.readline().split()] nodes = set([x for x in range(n)]) loops = [] while nodes: for x in nodes: nxt = x break visited = set() q = [] early = False while not nxt in visited: if not nxt in nodes: early = True break q.append(nxt) visited.add(nxt) nodes.remove(nxt) nxt = a[nxt] if not early: loops.append(len(q)-q.index(nxt)) base = pow(2,n-sum(loops),10**9+7) for x in loops: base *= pow(2,x,10**9+7)-2 base %= 10**9+7 print(base)
Codeforces Round 369 (Div. 2)
CF
2,016
2
256
Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after. ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns. Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing. Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.
The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.
Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.
null
Consider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are $$1 \rightarrow 2$$, $$2\rightarrow3$$, $$\overset{3}{\rightarrow}1$$ initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip. The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.
[{"input": "3\n2 3 1", "output": "6"}, {"input": "4\n2 1 1 1", "output": "8"}, {"input": "5\n2 4 2 5 3", "output": "28"}]
1,900
["combinatorics", "dfs and similar", "graphs", "math"]
131
[{"input": "3\r\n2 3 1\r\n", "output": "6\r\n"}, {"input": "4\r\n2 1 1 1\r\n", "output": "8\r\n"}, {"input": "5\r\n2 4 2 5 3\r\n", "output": "28\r\n"}, {"input": "4\r\n2 1 4 3\r\n", "output": "4\r\n"}, {"input": "7\r\n2 3 4 1 6 5 4\r\n", "output": "56\r\n"}, {"input": "20\r\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1\r\n", "output": "1048574\r\n"}, {"input": "2\r\n2 1\r\n", "output": "2\r\n"}, {"input": "84\r\n2 50 67 79 71 45 43 40 57 20 25 8 60 47 52 10 37 23 1 28 22 26 3 42 11 63 61 68 49 32 55 18 5 24 31 70 66 27 38 41 54 12 65 51 15 34 30 35 77 74 21 62 33 16 81 14 19 48 80 73 69 78 39 6 76 46 75 72 84 29 58 59 13 17 82 9 83 4 36 56 53 7 64 44\r\n", "output": "428380105\r\n"}]
false
stdio
null
true
777/C
777
C
Python 3
TESTS
98
857
10,444,800
27457208
from sys import stdin n, m = map(int, stdin.readline().rstrip().split()) if n == 1: print("Yes") exit() data = [] for i in range(0, n): data.append(list(map(int, stdin.readline().rstrip().split()))) sorted_data = [0] * n for col in range(0, m): mark_r = 0 cur_r = 1 st = [] while cur_r < n: if data[cur_r][col] < data[cur_r - 1][col]: st.extend([cur_r - 1] * (cur_r - mark_r)) mark_r = cur_r cur_r += 1 st.extend([cur_r - 1] * (cur_r - mark_r)) for index, item in enumerate(st): if sorted_data[index] < st[index]: sorted_data[index] = st[index] q_count = int(stdin.readline().rstrip()) for _ in range(0, q_count): l, r = map(lambda x: int(x) - 1, stdin.readline().rstrip().split()) if sorted_data[l] >= r: print("Yes") else: print("No")
114
187
13,414,400
189119085
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v): return u * m + v n, m = map(int, input().split()) a = [] for _ in range(n): a0 = list(map(int, input().split())) for i in a0: a.append(i) x = [i for i in range(1, n + 1)] for j in range(m): u = n for i in range(n - 2, -1, -1): if not a[f(i, j)] <= a[f(i + 1, j)]: u = i + 1 x[i] = max(x[i], u) x = [0] + x k = int(input()) ans = [] for _ in range(k): l, r = map(int, input().split()) ans0 = "Yes" if x[l] >= r else "No" ans.append(ans0) sys.stdout.write("\n".join(ans))
Codeforces Round 401 (Div. 2)
CF
2,017
1
256
Alyona and Spreadsheet
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables. Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai, j ≤ ai + 1, j for all i from 1 to n - 1. Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai, j ≤ ai + 1, j for all i from l to r - 1 inclusive. Alyona is too small to deal with this task and asks you to help!
The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 100 000) — the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table. Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for ai, j (1 ≤ ai, j ≤ 109). The next line of the input contains an integer k (1 ≤ k ≤ 100 000) — the number of task that teacher gave to Alyona. The i-th of the next k lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n).
Print "Yes" to the i-th line of the output if the table consisting of rows from li to ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No".
null
In the sample, the whole table is not sorted in any column. However, rows 1–3 are sorted in column 1, while rows 4–5 are sorted in column 3.
[{"input": "5 4\n1 2 3 5\n3 1 3 2\n4 5 2 3\n5 5 3 2\n4 4 3 4\n6\n1 1\n2 5\n4 5\n3 5\n1 3\n1 5", "output": "Yes\nNo\nYes\nYes\nYes\nNo"}]
1,600
["binary search", "data structures", "dp", "greedy", "implementation", "two pointers"]
114
[{"input": "5 4\r\n1 2 3 5\r\n3 1 3 2\r\n4 5 2 3\r\n5 5 3 2\r\n4 4 3 4\r\n6\r\n1 1\r\n2 5\r\n4 5\r\n3 5\r\n1 3\r\n1 5\r\n", "output": "Yes\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\n"}, {"input": "1 1\r\n1\r\n1\r\n1 1\r\n", "output": "Yes\r\n"}, {"input": "10 1\r\n523130301\r\n127101624\r\n15573616\r\n703140639\r\n628818570\r\n957494759\r\n161270109\r\n386865653\r\n67832626\r\n53360557\r\n17\r\n4 5\r\n4 7\r\n8 8\r\n9 9\r\n3 9\r\n8 10\r\n8 9\r\n7 9\r\n4 5\r\n2 9\r\n4 6\r\n2 4\r\n2 6\r\n4 6\r\n7 9\r\n2 4\r\n8 10\r\n", "output": "No\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\n"}, {"input": "15 1\r\n556231456\r\n573340933\r\n626155933\r\n397229387\r\n10255952\r\n376567394\r\n906742013\r\n269437009\r\n31298788\r\n712285290\r\n620239975\r\n379221898\r\n229140718\r\n95080095\r\n997123854\r\n18\r\n5 15\r\n1 12\r\n4 10\r\n2 15\r\n12 15\r\n15 15\r\n2 2\r\n15 15\r\n15 15\r\n13 13\r\n10 14\r\n3 6\r\n14 15\r\n3 6\r\n4 4\r\n14 15\r\n12 14\r\n1 9\r\n", "output": "No\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\n"}, {"input": "11 1\r\n501465490\r\n366941771\r\n415080944\r\n385243536\r\n445132523\r\n697044413\r\n894369800\r\n812743722\r\n23684788\r\n466526046\r\n953916313\r\n45\r\n2 4\r\n8 9\r\n7 7\r\n4 9\r\n2 9\r\n2 11\r\n4 4\r\n5 7\r\n1 2\r\n5 10\r\n4 6\r\n1 7\r\n4 4\r\n1 6\r\n4 7\r\n10 11\r\n1 8\r\n6 11\r\n8 8\r\n8 10\r\n1 1\r\n5 10\r\n9 10\r\n6 9\r\n6 11\r\n1 1\r\n9 9\r\n5 11\r\n1 2\r\n9 11\r\n2 6\r\n3 7\r\n11 11\r\n6 7\r\n11 11\r\n7 8\r\n5 8\r\n11 11\r\n5 6\r\n4 5\r\n2 6\r\n5 10\r\n9 9\r\n1 1\r\n1 1\r\n", "output": "No\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\n"}]
false
stdio
null
true
327/C
327
C
PyPy 3-64
TESTS
4
92
1,945,600
174864734
n=input(); ans= 0; n *= int(input()); c = len(n) for x in range(c) : if n[x] == '0' or n[x] == '5' : ans+=2**(x) print(ans)
33
248
19,353,600
194605055
import sys import math import random input = sys.stdin.readline def mod(a, b, m): if b == 0: return 1 else: p = mod(a, b // 2, m) if b % 2: return (p ** 2 * a) % m else: return (p ** 2) % m def g(l, M): return mod(l, M - 2, M) M = 10 ** 9 + 7 step = [1] for i in range(10 ** 6): step.append((step[-1] * 2) % M) s = input()[:-1] n = len(s) k = int(input()) ans = 0 r = ((mod(step[n], k, M) - 1) * g(step[n] - 1, M)) % M for i in range(n): if int(s[i]) % 5 == 0: ans += step[i] * r print(ans % 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
393/B
393
B
Python 3
TESTS
1
93
307,200
49667745
import math n = int(input()) A = [[0.0]*n]*n B = [[0.0]*n]*n W = [] for i in range(n): W.append(list(map(int, input().split()))) for i in range(n): for j in range(n): if i!=j: if A[i][j] == 0: A[i][j] = A[j][i] = min(W[i][j], W[j][i])+abs(W[i][j]-W[j][i])/2 if B[i][j]==0: B[i][j] = W[i][j] - A[i][j] B[j][i] = -B[i][j] for i in range(n): for j in range(n): print(float(W[i][j]) if i==j else A[i][j], end=' ') print() for i in range(n): for j in range(n): print(0.0 if i==j else B[i][j], end=' ') print()
40
155
1,331,200
64654734
n = int(input()) lst = [[int(x) for x in input().split()] for i in range(n)] t = [[0] * n for y in range(n)] for i in range(n): t[i][i], lst[i][i] = lst[i][i], 0 for j in range(i + 1, n): t[j][i] = t[i][j] = d = (lst[i][j] + lst[j][i]) / 2 lst[i][j] -= d lst[j][i] -= d for i in t: print(' '.join(map(str, i))) for i in lst: print(' '.join(map(str, i)))
Codeforces Round 230 (Div. 2)
CF
2,014
1
256
Three matrices
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold: - Aij = Aji, for all i, j (1 ≤ i, j ≤ n); - Bij =  - Bji, for all i, j (1 ≤ i, j ≤ n); - Wij = Aij + Bij, for all i, j (1 ≤ i, j ≤ n). Can you solve the problem?
The first line contains an integer n (1 ≤ n ≤ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0 ≤ |Wij| < 1717).
The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 4.
null
null
[{"input": "2\n1 4\n3 2", "output": "1.00000000 3.50000000\n3.50000000 2.00000000\n0.00000000 0.50000000\n-0.50000000 0.00000000"}, {"input": "3\n1 2 3\n4 5 6\n7 8 9", "output": "1.00000000 3.00000000 5.00000000\n3.00000000 5.00000000 7.00000000\n5.00000000 7.00000000 9.00000000\n0.00000000 -1.00000000 -2.00000000\n1.00000000 0.00000000 -1.00000000\n2.00000000 1.00000000 0.00000000"}]
null
[]
40
[{"input": "2\r\n1 4\r\n3 2\r\n", "output": "1.00000000 3.50000000\r\n3.50000000 2.00000000\r\n0.00000000 0.50000000\r\n-0.50000000 0.00000000\r\n"}, {"input": "3\r\n1 2 3\r\n4 5 6\r\n7 8 9\r\n", "output": "1.00000000 3.00000000 5.00000000\r\n3.00000000 5.00000000 7.00000000\r\n5.00000000 7.00000000 9.00000000\r\n0.00000000 -1.00000000 -2.00000000\r\n1.00000000 0.00000000 -1.00000000\r\n2.00000000 1.00000000 0.00000000\r\n"}, {"input": "8\r\n62 567 1382 1279 728 1267 1262 568\r\n77 827 717 1696 774 248 822 1266\r\n563 612 995 424 1643 1197 338 1141\r\n1579 806 1254 468 184 1571 716 772\r\n1087 182 1312 772 605 1674 720 1349\r\n1393 988 873 157 403 301 1519 1192\r\n1085 625 1395 1087 847 1360 1004 594\r\n1368 1056 916 839 472 840 53 1238\r\n", "output": "62.000000000 322.000000000 972.500000000 1429.000000000 907.500000000 1330.000000000 1173.500000000 968.000000000\n322.000000000 827.000000000 664.500000000 1251.000000000 478.000000000 618.000000000 723.500000000 1161.000000000\n972.500000000 664.500000000 995.000000000 839.000000000 1477.500000000 1035.000000000 866.500000000 1028.500000000\n1429.000000000 1251.000000000 839.000000000 468.000000000 478.000000000 864.000000000 901.500000000 805.500000000\n907.500000000 478.000000000 1477.500000000 478.000000000 605.000000000 1038.500000000 783.500000000 910.500000000\n1330.000000000 618.000000000 1035.000000000 864.000000000 1038.500000000 301.000000000 1439.500000000 1016.000000000\n1173.500000000 723.500000000 866.500000000 901.500000000 783.500000000 1439.500000000 1004.000000000 323.500000000\n968.000000000 1161.000000000 1028.500000000 805.500000000 910.500000000 1016.000000000 323.500000000 1238.000000000\n0.000000000 245.000000000 409.500000000 -150.000000000 -179.500000000 -63.000000000 88.500000000 -400.000000000\n-245.000000000 0.000000000 52.500000000 445.000000000 296.000000000 -370.000000000 98.500000000 105.000000000\n-409.500000000 -52.500000000 0.000000000 -415.000000000 165.500000000 162.000000000 -528.500000000 112.500000000\n150.000000000 -445.000000000 415.000000000 0.000000000 -294.000000000 707.000000000 -185.500000000 -33.500000000\n179.500000000 -296.000000000 -165.500000000 294.000000000 0.000000000 635.500000000 -63.500000000 438.500000000\n63.000000000 370.000000000 -162.000000000 -707.000000000 -635.500000000 0.000000000 79.500000000 176.000000000\n-88.500000000 -98.500000000 528.500000000 185.500000000 63.500000000 -79.500000000 0.000000000 270.500000000\n400.000000000 -105.000000000 -112.500000000 33.500000000 -438.500000000 -176.000000000 -270.500000000 0.000000000\n"}, {"input": "7\r\n926 41 1489 72 749 375 940\r\n464 1148 858 1010 285 1469 1506\r\n1112 1087 225 917 480 511 1090\r\n759 945 627 230 220 1456 529\r\n318 83 203 134 1192 1167 6\r\n440 1158 1614 683 1358 1140 1196\r\n1175 900 126 1562 1220 813 148\r\n", "output": "926.000000000 252.500000000 1300.500000000 415.500000000 533.500000000 407.500000000 1057.500000000\n252.500000000 1148.000000000 972.500000000 977.500000000 184.000000000 1313.500000000 1203.000000000\n1300.500000000 972.500000000 225.000000000 772.000000000 341.500000000 1062.500000000 608.000000000\n415.500000000 977.500000000 772.000000000 230.000000000 177.000000000 1069.500000000 1045.500000000\n533.500000000 184.000000000 341.500000000 177.000000000 1192.000000000 1262.500000000 613.000000000\n407.500000000 1313.500000000 1062.500000000 1069.500000000 1262.500000000 1140.000000000 1004.500000000\n1057.500000000 1203.000000000 608.000000000 1045.500000000 613.000000000 1004.500000000 148.000000000\n0.000000000 -211.500000000 188.500000000 -343.500000000 215.500000000 -32.500000000 -117.500000000\n211.500000000 0.000000000 -114.500000000 32.500000000 101.000000000 155.500000000 303.000000000\n-188.500000000 114.500000000 0.000000000 145.000000000 138.500000000 -551.500000000 482.000000000\n343.500000000 -32.500000000 -145.000000000 0.000000000 43.000000000 386.500000000 -516.500000000\n-215.500000000 -101.000000000 -138.500000000 -43.000000000 0.000000000 -95.500000000 -607.000000000\n32.500000000 -155.500000000 551.500000000 -386.500000000 95.500000000 0.000000000 191.500000000\n117.500000000 -303.000000000 -482.000000000 516.500000000 607.000000000 -191.500000000 0.000000000\n"}, {"input": "1\r\n1\r\n", "output": "1.00000000\r\n0.00000000\r\n"}, {"input": "1\r\n0\r\n", "output": "0.00000000\r\n0.00000000\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0.00000000 0.00000000\r\n0.00000000 0.00000000\r\n0.00000000 0.00000000\r\n0.00000000 0.00000000\r\n"}, {"input": "2\r\n0 1\r\n0 1\r\n", "output": "0.00000000 0.50000000\r\n0.50000000 1.00000000\r\n0.00000000 0.50000000\r\n-0.50000000 0.00000000\r\n"}]
false
stdio
import sys def is_close(a, b): abs_tol = 1e-4 rel_tol = 1e-4 diff = abs(a - b) if diff <= abs_tol: return True max_val = max(abs(a), abs(b)) return diff <= rel_tol * max_val def main(input_path, output_path, submission_path): with open(input_path) as f: lines = f.read().splitlines() n = int(lines[0]) w = [] for line in lines[1:1+n]: row = list(map(int, line.split())) w.append(row) with open(submission_path) as f: submission_lines = f.read().splitlines() if len(submission_lines) != 2 * n: print(0) return A = [] B = [] for i in range(n): if i >= len(submission_lines): print(0) return parts = submission_lines[i].split() if len(parts) != n: print(0) return try: row = list(map(float, parts)) except: print(0) return A.append(row) for i in range(n, 2 * n): if i >= len(submission_lines): print(0) return parts = submission_lines[i].split() if len(parts) != n: print(0) return try: row = list(map(float, parts)) except: print(0) return B.append(row) for i in range(n): for j in range(n): if not is_close(A[i][j], A[j][i]): print(0) return for i in range(n): for j in range(n): if not is_close(B[i][j], -B[j][i]): print(0) return for i in range(n): for j in range(n): sum_ab = A[i][j] + B[i][j] expected = w[i][j] if not is_close(sum_ab, expected): 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
778/A
778
A
PyPy 3
TESTS
29
592
45,465,600
90796107
from collections import defaultdict def isSubsequence(S,T,List,pos,Pos): lenS = len(S) lenT = len(T) Sx = 0 Tx = 0 while(Tx<lenT and Sx<lenS): if(Pos[Sx]<pos): Sx+=1 elif(S[Sx] == T[Tx]): Sx+=1 Tx+=1 else: Sx+=1 if(Tx == lenT): return True return False S = input() T = input() List = [int(x) for x in input().split()] N = len(List) Pos = defaultdict(int) for i in range(N): Pos[List[i]-1] = i N = len(List) l = 0 r = N-1 while(l<r): mid = (l+r)>>1 if(isSubsequence(S,T,List,mid,Pos)): l = mid+1 else: r = mid print(l-1)
43
187
31,744,000
195894676
import sys input = sys.stdin.readline s = input()[:-1] t = input()[:-1] w = list(map(int, input().split())) n = len(w) l, r, x = 0, n-len(t)+1, 0 while l < r: m = (l+r)//2 d = [0]*n for i in range(m): d[w[i]-1] = 1 j = 0 for i in range(n): if s[i] == t[j] and d[i] == 0: j += 1 if j == len(t): x = max(x, m) l = m+1 break else: r = m print(x)
Codeforces Round 402 (Div. 1)
CF
2,017
2
512
String Game
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" $$\rightarrow$$ "nastya" $$\rightarrow$$ "nastya" $$\rightarrow$$ "nastya" $$\rightarrow$$ "nastya" $$\rightarrow$$ "nastya" $$\rightarrow$$ "nastya". Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey. It is guaranteed that the word p can be obtained by removing the letters from word t.
The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).
Print a single integer number, the maximum number of letters that Nastya can remove.
null
In the first sample test sequence of removing made by Nastya looks like this: "ababcba" $$\rightarrow$$ "ababcba" $$\rightarrow$$ "ababcba" $$\rightarrow$$ "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba". So, Nastya will remove only three letters.
[{"input": "ababcba\nabb\n5 3 4 1 7 6 2", "output": "3"}, {"input": "bbbabb\nbb\n1 6 3 4 2 5", "output": "4"}]
1,700
["binary search", "greedy", "strings"]
43
[{"input": "ababcba\r\nabb\r\n5 3 4 1 7 6 2\r\n", "output": "3"}, {"input": "bbbabb\r\nbb\r\n1 6 3 4 2 5\r\n", "output": "4"}, {"input": "cacaccccccacccc\r\ncacc\r\n10 9 14 5 1 7 15 3 6 12 4 8 11 13 2\r\n", "output": "9"}, {"input": "aaaabaaabaabaaaaaaaa\r\naaaa\r\n18 5 4 6 13 9 1 3 7 8 16 10 12 19 17 15 14 11 20 2\r\n", "output": "16"}, {"input": "aaaaaaaadbaaabbbbbddaaabdadbbbbbdbbabbbabaabdbbdababbbddddbdaabbddbbbbabbbbbabadaadabaaaadbbabbbaddb\r\naaaaaaaaaaaaaa\r\n61 52 5 43 53 81 7 96 6 9 34 78 79 12 8 63 22 76 18 46 41 56 3 20 57 21 75 73 100 94 35 69 32 4 70 95 88 44 68 10 71 98 23 89 36 62 28 51 24 30 74 55 27 80 38 48 93 1 19 84 13 11 86 60 87 33 39 29 83 91 67 72 54 2 17 85 82 14 15 90 64 50 99 26 66 65 31 49 40 45 77 37 25 42 97 47 58 92 59 16\r\n", "output": "57"}]
false
stdio
null
true
393/B
393
B
Python 3
TESTS
1
93
0
47525599
n = int(input()) w = [None]*n dsum_len = 2*n-1 dsum = [0]*dsum_len for i in range(n): w[i] = [int(j) for j in input().strip().split(' ')] for j in range(n): dsum[i+j] += w[i][j] for i in range(n): for j in range(n): val = w[i][j] if (i != j): ij = i+j if ij >= n: val = dsum[ij]/(dsum_len-ij+1) else: val = dsum[ij]/(ij+1) print('{:.8f}'.format(val), end=' ') print('') for i in range(n): for j in range(n): val = 0 if (i != j): ij = i+j if ij >= n: val = w[i][j]-(dsum[ij]/(dsum_len-ij+1)) else: val = w[i][j]-(dsum[ij]/(ij+1)) print('{:.8f}'.format(val), end=' ') print('')
40
155
2,867,200
140353732
n = int(input()) mat = [] mat1 = [] mat2 = [] for _ in range(n): t = list(map(int, input().split())) mat.append(t) for i in range(n): m = [] m1 = [] for j in range(n): if(i==j): m.append("{0:.8f}".format(mat[i][j])) m1.append("{0:.8f}".format(0)) elif(i<j): a = (mat[i][j] + mat[j][i])/2 m.append("{0:.8f}".format(a)) m1.append("{0:.8f}".format(mat[i][j] - a)) else: m.append(mat1[j][i]) if(mat2[j][i][0] != "-"): m1.append("-"+(mat2[j][i])) else: m1.append(mat2[j][i][1:]) mat1.append(m) mat2.append(m1) for i in range(n): for j in range(n): print(mat1[i][j],end=" ") print() for i in range(n): for j in range(n): print(mat2[i][j],end=" ") print()
Codeforces Round 230 (Div. 2)
CF
2,014
1
256
Three matrices
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold: - Aij = Aji, for all i, j (1 ≤ i, j ≤ n); - Bij =  - Bji, for all i, j (1 ≤ i, j ≤ n); - Wij = Aij + Bij, for all i, j (1 ≤ i, j ≤ n). Can you solve the problem?
The first line contains an integer n (1 ≤ n ≤ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0 ≤ |Wij| < 1717).
The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 4.
null
null
[{"input": "2\n1 4\n3 2", "output": "1.00000000 3.50000000\n3.50000000 2.00000000\n0.00000000 0.50000000\n-0.50000000 0.00000000"}, {"input": "3\n1 2 3\n4 5 6\n7 8 9", "output": "1.00000000 3.00000000 5.00000000\n3.00000000 5.00000000 7.00000000\n5.00000000 7.00000000 9.00000000\n0.00000000 -1.00000000 -2.00000000\n1.00000000 0.00000000 -1.00000000\n2.00000000 1.00000000 0.00000000"}]
null
[]
40
[{"input": "2\r\n1 4\r\n3 2\r\n", "output": "1.00000000 3.50000000\r\n3.50000000 2.00000000\r\n0.00000000 0.50000000\r\n-0.50000000 0.00000000\r\n"}, {"input": "3\r\n1 2 3\r\n4 5 6\r\n7 8 9\r\n", "output": "1.00000000 3.00000000 5.00000000\r\n3.00000000 5.00000000 7.00000000\r\n5.00000000 7.00000000 9.00000000\r\n0.00000000 -1.00000000 -2.00000000\r\n1.00000000 0.00000000 -1.00000000\r\n2.00000000 1.00000000 0.00000000\r\n"}, {"input": "8\r\n62 567 1382 1279 728 1267 1262 568\r\n77 827 717 1696 774 248 822 1266\r\n563 612 995 424 1643 1197 338 1141\r\n1579 806 1254 468 184 1571 716 772\r\n1087 182 1312 772 605 1674 720 1349\r\n1393 988 873 157 403 301 1519 1192\r\n1085 625 1395 1087 847 1360 1004 594\r\n1368 1056 916 839 472 840 53 1238\r\n", "output": "62.000000000 322.000000000 972.500000000 1429.000000000 907.500000000 1330.000000000 1173.500000000 968.000000000\n322.000000000 827.000000000 664.500000000 1251.000000000 478.000000000 618.000000000 723.500000000 1161.000000000\n972.500000000 664.500000000 995.000000000 839.000000000 1477.500000000 1035.000000000 866.500000000 1028.500000000\n1429.000000000 1251.000000000 839.000000000 468.000000000 478.000000000 864.000000000 901.500000000 805.500000000\n907.500000000 478.000000000 1477.500000000 478.000000000 605.000000000 1038.500000000 783.500000000 910.500000000\n1330.000000000 618.000000000 1035.000000000 864.000000000 1038.500000000 301.000000000 1439.500000000 1016.000000000\n1173.500000000 723.500000000 866.500000000 901.500000000 783.500000000 1439.500000000 1004.000000000 323.500000000\n968.000000000 1161.000000000 1028.500000000 805.500000000 910.500000000 1016.000000000 323.500000000 1238.000000000\n0.000000000 245.000000000 409.500000000 -150.000000000 -179.500000000 -63.000000000 88.500000000 -400.000000000\n-245.000000000 0.000000000 52.500000000 445.000000000 296.000000000 -370.000000000 98.500000000 105.000000000\n-409.500000000 -52.500000000 0.000000000 -415.000000000 165.500000000 162.000000000 -528.500000000 112.500000000\n150.000000000 -445.000000000 415.000000000 0.000000000 -294.000000000 707.000000000 -185.500000000 -33.500000000\n179.500000000 -296.000000000 -165.500000000 294.000000000 0.000000000 635.500000000 -63.500000000 438.500000000\n63.000000000 370.000000000 -162.000000000 -707.000000000 -635.500000000 0.000000000 79.500000000 176.000000000\n-88.500000000 -98.500000000 528.500000000 185.500000000 63.500000000 -79.500000000 0.000000000 270.500000000\n400.000000000 -105.000000000 -112.500000000 33.500000000 -438.500000000 -176.000000000 -270.500000000 0.000000000\n"}, {"input": "7\r\n926 41 1489 72 749 375 940\r\n464 1148 858 1010 285 1469 1506\r\n1112 1087 225 917 480 511 1090\r\n759 945 627 230 220 1456 529\r\n318 83 203 134 1192 1167 6\r\n440 1158 1614 683 1358 1140 1196\r\n1175 900 126 1562 1220 813 148\r\n", "output": "926.000000000 252.500000000 1300.500000000 415.500000000 533.500000000 407.500000000 1057.500000000\n252.500000000 1148.000000000 972.500000000 977.500000000 184.000000000 1313.500000000 1203.000000000\n1300.500000000 972.500000000 225.000000000 772.000000000 341.500000000 1062.500000000 608.000000000\n415.500000000 977.500000000 772.000000000 230.000000000 177.000000000 1069.500000000 1045.500000000\n533.500000000 184.000000000 341.500000000 177.000000000 1192.000000000 1262.500000000 613.000000000\n407.500000000 1313.500000000 1062.500000000 1069.500000000 1262.500000000 1140.000000000 1004.500000000\n1057.500000000 1203.000000000 608.000000000 1045.500000000 613.000000000 1004.500000000 148.000000000\n0.000000000 -211.500000000 188.500000000 -343.500000000 215.500000000 -32.500000000 -117.500000000\n211.500000000 0.000000000 -114.500000000 32.500000000 101.000000000 155.500000000 303.000000000\n-188.500000000 114.500000000 0.000000000 145.000000000 138.500000000 -551.500000000 482.000000000\n343.500000000 -32.500000000 -145.000000000 0.000000000 43.000000000 386.500000000 -516.500000000\n-215.500000000 -101.000000000 -138.500000000 -43.000000000 0.000000000 -95.500000000 -607.000000000\n32.500000000 -155.500000000 551.500000000 -386.500000000 95.500000000 0.000000000 191.500000000\n117.500000000 -303.000000000 -482.000000000 516.500000000 607.000000000 -191.500000000 0.000000000\n"}, {"input": "1\r\n1\r\n", "output": "1.00000000\r\n0.00000000\r\n"}, {"input": "1\r\n0\r\n", "output": "0.00000000\r\n0.00000000\r\n"}, {"input": "2\r\n0 0\r\n0 0\r\n", "output": "0.00000000 0.00000000\r\n0.00000000 0.00000000\r\n0.00000000 0.00000000\r\n0.00000000 0.00000000\r\n"}, {"input": "2\r\n0 1\r\n0 1\r\n", "output": "0.00000000 0.50000000\r\n0.50000000 1.00000000\r\n0.00000000 0.50000000\r\n-0.50000000 0.00000000\r\n"}]
false
stdio
import sys def is_close(a, b): abs_tol = 1e-4 rel_tol = 1e-4 diff = abs(a - b) if diff <= abs_tol: return True max_val = max(abs(a), abs(b)) return diff <= rel_tol * max_val def main(input_path, output_path, submission_path): with open(input_path) as f: lines = f.read().splitlines() n = int(lines[0]) w = [] for line in lines[1:1+n]: row = list(map(int, line.split())) w.append(row) with open(submission_path) as f: submission_lines = f.read().splitlines() if len(submission_lines) != 2 * n: print(0) return A = [] B = [] for i in range(n): if i >= len(submission_lines): print(0) return parts = submission_lines[i].split() if len(parts) != n: print(0) return try: row = list(map(float, parts)) except: print(0) return A.append(row) for i in range(n, 2 * n): if i >= len(submission_lines): print(0) return parts = submission_lines[i].split() if len(parts) != n: print(0) return try: row = list(map(float, parts)) except: print(0) return B.append(row) for i in range(n): for j in range(n): if not is_close(A[i][j], A[j][i]): print(0) return for i in range(n): for j in range(n): if not is_close(B[i][j], -B[j][i]): print(0) return for i in range(n): for j in range(n): sum_ab = A[i][j] + B[i][j] expected = w[i][j] if not is_close(sum_ab, expected): 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
526/B
526
B
PyPy 3
TESTS
1
124
0
102859969
import math a = int(input()) b = list(map(int, input().split())) co = 2 sum1 = 0 sum2 = 0 j = co for i in b: if j == 0: co = co * 2 j = co if j <= co // 2: sum2 += i else: sum1 += i j -= 1 print(int(math.fabs(sum2-sum1)))
38
46
0
195061844
def dfs(node, v): global ans if node >= len(a) + 2: return 0 v = a[node - 2] q = dfs(2 * node, v) r = dfs(2 * node + 1, v) v += max(q, r) ans += abs(q - r) return v ans = 0 n = int(input()) a = list(map(int, input().split())) dfs(1, 0) print(ans)
ZeptoLab Code Rush 2015
CF
2,015
1
256
Om Nom and Dark Park
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square $$\frac{i}{2}$$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and $$\frac{i}{2}$$. All numbers ai are positive integers, not exceeding 100.
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
null
Picture for the sample test. Green color denotes the additional street lights.
[{"input": "2\n1 2 3 4 5 6", "output": "5"}]
1,400
["dfs and similar", "greedy", "implementation"]
38
[{"input": "2\r\n1 2 3 4 5 6\r\n", "output": "5\r\n"}, {"input": "2\r\n1 2 3 3 2 2\r\n", "output": "0\r\n"}, {"input": "1\r\n39 52\r\n", "output": "13\r\n"}, {"input": "2\r\n59 96 34 48 8 72\r\n", "output": "139\r\n"}, {"input": "3\r\n87 37 91 29 58 45 51 74 70 71 47 38 91 89\r\n", "output": "210\r\n"}, {"input": "5\r\n39 21 95 89 73 90 9 55 85 32 30 21 68 59 82 91 20 64 52 70 6 88 53 47 30 47 34 14 11 22 42 15 28 54 37 48 29 3 14 13 18 77 90 58 54 38 94 49 45 66 13 74 11 14 64 72 95 54 73 79 41 35\r\n", "output": "974\r\n"}, {"input": "1\r\n49 36\r\n", "output": "13\r\n"}, {"input": "1\r\n77 88\r\n", "output": "11\r\n"}, {"input": "1\r\n1 33\r\n", "output": "32\r\n"}, {"input": "2\r\n72 22 81 23 14 75\r\n", "output": "175\r\n"}, {"input": "2\r\n100 70 27 1 68 52\r\n", "output": "53\r\n"}, {"input": "2\r\n24 19 89 82 22 21\r\n", "output": "80\r\n"}, {"input": "3\r\n86 12 92 91 3 68 57 56 76 27 33 62 71 84\r\n", "output": "286\r\n"}, {"input": "3\r\n14 56 53 61 57 45 40 44 31 9 73 2 61 26\r\n", "output": "236\r\n"}, {"input": "3\r\n35 96 7 43 10 14 16 36 95 92 16 50 59 55\r\n", "output": "173\r\n"}, {"input": "4\r\n1 97 18 48 96 65 24 91 17 45 36 27 74 93 78 86 39 55 53 21 26 68 31 33 79 63 80 92 1 26\r\n", "output": "511\r\n"}, {"input": "4\r\n25 42 71 29 50 30 99 79 77 24 76 66 68 23 97 99 65 17 75 62 66 46 48 4 40 71 98 57 21 92\r\n", "output": "603\r\n"}, {"input": "4\r\n49 86 17 7 3 6 86 71 36 10 27 10 58 64 12 16 88 67 93 3 15 20 58 87 97 91 11 6 34 62\r\n", "output": "470\r\n"}, {"input": "5\r\n16 87 36 16 81 53 87 35 63 56 47 91 81 95 80 96 91 7 58 99 25 28 47 60 7 69 49 14 51 52 29 30 83 23 21 52 100 26 91 14 23 94 72 70 40 12 50 32 54 52 18 74 5 15 62 3 48 41 24 25 56 43\r\n", "output": "1060\r\n"}, {"input": "5\r\n40 27 82 94 38 22 66 23 18 34 87 31 71 28 95 5 14 61 76 52 66 6 60 40 68 77 70 63 64 18 47 13 82 55 34 64 30 1 29 24 24 9 65 17 29 96 61 76 72 23 32 26 90 39 54 41 35 66 71 29 75 48\r\n", "output": "1063\r\n"}, {"input": "5\r\n64 72 35 68 92 95 45 15 77 16 26 74 61 65 18 22 32 19 98 97 14 84 70 23 29 1 87 28 88 89 73 79 69 88 43 60 64 64 66 39 17 27 46 71 18 83 73 20 90 77 49 70 84 63 50 72 26 87 26 37 78 65\r\n", "output": "987\r\n"}, {"input": "6\r\n35 61 54 77 70 50 53 70 4 66 58 47 76 100 78 5 43 50 55 93 13 93 59 92 30 74 22 23 98 70 19 56 90 92 19 7 28 53 45 77 42 91 71 56 19 83 100 53 13 93 37 13 70 60 16 13 76 3 12 22 17 26 50 6 63 7 25 41 92 29 36 80 11 4 10 14 77 75 53 82 46 24 56 46 82 36 80 75 8 45 24 22 90 34 45 76 18 38 86 43 7 49 80 56 90 53 12 51 98 47 44 58 32 4 2 6 3 60 38 72 74 46 30 86 1 98\r\n", "output": "2499\r\n"}, {"input": "6\r\n63 13 100 54 31 15 29 58 59 44 2 99 70 33 97 14 70 12 73 42 65 71 68 67 87 83 43 84 18 41 37 22 81 24 27 11 57 28 83 92 39 1 56 15 16 67 16 97 31 52 50 65 63 89 8 52 55 20 71 27 28 35 86 92 94 60 10 65 83 63 89 71 34 20 78 40 34 62 2 86 100 81 87 69 25 4 52 17 57 71 62 38 1 3 54 71 34 85 20 60 80 23 82 47 4 19 7 18 14 18 28 27 4 55 26 71 45 9 2 40 67 28 32 19 81 92\r\n", "output": "2465\r\n"}, {"input": "6\r\n87 62 58 32 81 92 12 50 23 27 38 39 64 74 16 35 84 59 91 87 14 48 90 47 44 95 64 45 31 11 67 5 80 60 36 15 91 3 21 2 40 24 37 69 5 50 23 37 49 19 68 21 49 9 100 94 45 41 22 31 31 48 25 70 25 25 95 88 82 1 37 53 49 31 57 74 94 45 55 93 43 37 13 85 59 72 15 68 3 90 96 55 100 64 63 69 43 33 66 84 57 97 87 34 23 89 97 77 39 89 8 92 68 13 50 36 95 61 71 96 73 13 30 49 57 89\r\n", "output": "2513\r\n"}]
false
stdio
null
true
526/B
526
B
Python 3
PRETESTS
1
61
0
10576944
n = int(input()) a = list(map(int, input().split())) dp = [0] * (len(a) + 3) for i in range(2, 2 ** (n + 1)): dp[i] = a[i - 2] + dp[i // 2] print(max(dp) * (2 ** (n)) - sum(dp))
38
61
0
10578835
n = int(input()) M = 2 ** (n + 1) A = [0, 0] + list(map(int, input().split())) Ans = [0] * M ans = 0 for i in range(2 ** n - 1, 0, -1): left = i * 2 right = i * 2 + 1 m_l = A[left] + Ans[left] m_r = A[right] + Ans[right] Ans[i] = max(m_l, m_r) ans += abs(m_l - m_r) print(ans)
ZeptoLab Code Rush 2015
CF
2,015
1
256
Om Nom and Dark Park
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square $$\frac{i}{2}$$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and $$\frac{i}{2}$$. All numbers ai are positive integers, not exceeding 100.
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
null
Picture for the sample test. Green color denotes the additional street lights.
[{"input": "2\n1 2 3 4 5 6", "output": "5"}]
1,400
["dfs and similar", "greedy", "implementation"]
38
[{"input": "2\r\n1 2 3 4 5 6\r\n", "output": "5\r\n"}, {"input": "2\r\n1 2 3 3 2 2\r\n", "output": "0\r\n"}, {"input": "1\r\n39 52\r\n", "output": "13\r\n"}, {"input": "2\r\n59 96 34 48 8 72\r\n", "output": "139\r\n"}, {"input": "3\r\n87 37 91 29 58 45 51 74 70 71 47 38 91 89\r\n", "output": "210\r\n"}, {"input": "5\r\n39 21 95 89 73 90 9 55 85 32 30 21 68 59 82 91 20 64 52 70 6 88 53 47 30 47 34 14 11 22 42 15 28 54 37 48 29 3 14 13 18 77 90 58 54 38 94 49 45 66 13 74 11 14 64 72 95 54 73 79 41 35\r\n", "output": "974\r\n"}, {"input": "1\r\n49 36\r\n", "output": "13\r\n"}, {"input": "1\r\n77 88\r\n", "output": "11\r\n"}, {"input": "1\r\n1 33\r\n", "output": "32\r\n"}, {"input": "2\r\n72 22 81 23 14 75\r\n", "output": "175\r\n"}, {"input": "2\r\n100 70 27 1 68 52\r\n", "output": "53\r\n"}, {"input": "2\r\n24 19 89 82 22 21\r\n", "output": "80\r\n"}, {"input": "3\r\n86 12 92 91 3 68 57 56 76 27 33 62 71 84\r\n", "output": "286\r\n"}, {"input": "3\r\n14 56 53 61 57 45 40 44 31 9 73 2 61 26\r\n", "output": "236\r\n"}, {"input": "3\r\n35 96 7 43 10 14 16 36 95 92 16 50 59 55\r\n", "output": "173\r\n"}, {"input": "4\r\n1 97 18 48 96 65 24 91 17 45 36 27 74 93 78 86 39 55 53 21 26 68 31 33 79 63 80 92 1 26\r\n", "output": "511\r\n"}, {"input": "4\r\n25 42 71 29 50 30 99 79 77 24 76 66 68 23 97 99 65 17 75 62 66 46 48 4 40 71 98 57 21 92\r\n", "output": "603\r\n"}, {"input": "4\r\n49 86 17 7 3 6 86 71 36 10 27 10 58 64 12 16 88 67 93 3 15 20 58 87 97 91 11 6 34 62\r\n", "output": "470\r\n"}, {"input": "5\r\n16 87 36 16 81 53 87 35 63 56 47 91 81 95 80 96 91 7 58 99 25 28 47 60 7 69 49 14 51 52 29 30 83 23 21 52 100 26 91 14 23 94 72 70 40 12 50 32 54 52 18 74 5 15 62 3 48 41 24 25 56 43\r\n", "output": "1060\r\n"}, {"input": "5\r\n40 27 82 94 38 22 66 23 18 34 87 31 71 28 95 5 14 61 76 52 66 6 60 40 68 77 70 63 64 18 47 13 82 55 34 64 30 1 29 24 24 9 65 17 29 96 61 76 72 23 32 26 90 39 54 41 35 66 71 29 75 48\r\n", "output": "1063\r\n"}, {"input": "5\r\n64 72 35 68 92 95 45 15 77 16 26 74 61 65 18 22 32 19 98 97 14 84 70 23 29 1 87 28 88 89 73 79 69 88 43 60 64 64 66 39 17 27 46 71 18 83 73 20 90 77 49 70 84 63 50 72 26 87 26 37 78 65\r\n", "output": "987\r\n"}, {"input": "6\r\n35 61 54 77 70 50 53 70 4 66 58 47 76 100 78 5 43 50 55 93 13 93 59 92 30 74 22 23 98 70 19 56 90 92 19 7 28 53 45 77 42 91 71 56 19 83 100 53 13 93 37 13 70 60 16 13 76 3 12 22 17 26 50 6 63 7 25 41 92 29 36 80 11 4 10 14 77 75 53 82 46 24 56 46 82 36 80 75 8 45 24 22 90 34 45 76 18 38 86 43 7 49 80 56 90 53 12 51 98 47 44 58 32 4 2 6 3 60 38 72 74 46 30 86 1 98\r\n", "output": "2499\r\n"}, {"input": "6\r\n63 13 100 54 31 15 29 58 59 44 2 99 70 33 97 14 70 12 73 42 65 71 68 67 87 83 43 84 18 41 37 22 81 24 27 11 57 28 83 92 39 1 56 15 16 67 16 97 31 52 50 65 63 89 8 52 55 20 71 27 28 35 86 92 94 60 10 65 83 63 89 71 34 20 78 40 34 62 2 86 100 81 87 69 25 4 52 17 57 71 62 38 1 3 54 71 34 85 20 60 80 23 82 47 4 19 7 18 14 18 28 27 4 55 26 71 45 9 2 40 67 28 32 19 81 92\r\n", "output": "2465\r\n"}, {"input": "6\r\n87 62 58 32 81 92 12 50 23 27 38 39 64 74 16 35 84 59 91 87 14 48 90 47 44 95 64 45 31 11 67 5 80 60 36 15 91 3 21 2 40 24 37 69 5 50 23 37 49 19 68 21 49 9 100 94 45 41 22 31 31 48 25 70 25 25 95 88 82 1 37 53 49 31 57 74 94 45 55 93 43 37 13 85 59 72 15 68 3 90 96 55 100 64 63 69 43 33 66 84 57 97 87 34 23 89 97 77 39 89 8 92 68 13 50 36 95 61 71 96 73 13 30 49 57 89\r\n", "output": "2513\r\n"}]
false
stdio
null
true
526/B
526
B
PyPy 3
TESTS
1
93
0
106657103
input() l=list(map(int,input().split())) l2=[] for x in range(2): y=2 if x==0 else 3 t=0 z=1 while x<len(l): t+=sum(l[x:x+z]) x+=y z*=2 y*=2 l2.append(t) print(max(l2)-min(l2))
38
61
0
10581545
#!/usr/bin/python3 n = 2**(int(input())+1)-1 d = input().split(' ') for i in range(len(d)): d[i] = int(d[i]) p = 0 for i in range(len(d)-1, 0, -2): p += abs(d[i]-d[i-1]) d[i//2-1] += max(d[i], d[i-1]) print(p)
ZeptoLab Code Rush 2015
CF
2,015
1
256
Om Nom and Dark Park
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square $$\frac{i}{2}$$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and $$\frac{i}{2}$$. All numbers ai are positive integers, not exceeding 100.
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
null
Picture for the sample test. Green color denotes the additional street lights.
[{"input": "2\n1 2 3 4 5 6", "output": "5"}]
1,400
["dfs and similar", "greedy", "implementation"]
38
[{"input": "2\r\n1 2 3 4 5 6\r\n", "output": "5\r\n"}, {"input": "2\r\n1 2 3 3 2 2\r\n", "output": "0\r\n"}, {"input": "1\r\n39 52\r\n", "output": "13\r\n"}, {"input": "2\r\n59 96 34 48 8 72\r\n", "output": "139\r\n"}, {"input": "3\r\n87 37 91 29 58 45 51 74 70 71 47 38 91 89\r\n", "output": "210\r\n"}, {"input": "5\r\n39 21 95 89 73 90 9 55 85 32 30 21 68 59 82 91 20 64 52 70 6 88 53 47 30 47 34 14 11 22 42 15 28 54 37 48 29 3 14 13 18 77 90 58 54 38 94 49 45 66 13 74 11 14 64 72 95 54 73 79 41 35\r\n", "output": "974\r\n"}, {"input": "1\r\n49 36\r\n", "output": "13\r\n"}, {"input": "1\r\n77 88\r\n", "output": "11\r\n"}, {"input": "1\r\n1 33\r\n", "output": "32\r\n"}, {"input": "2\r\n72 22 81 23 14 75\r\n", "output": "175\r\n"}, {"input": "2\r\n100 70 27 1 68 52\r\n", "output": "53\r\n"}, {"input": "2\r\n24 19 89 82 22 21\r\n", "output": "80\r\n"}, {"input": "3\r\n86 12 92 91 3 68 57 56 76 27 33 62 71 84\r\n", "output": "286\r\n"}, {"input": "3\r\n14 56 53 61 57 45 40 44 31 9 73 2 61 26\r\n", "output": "236\r\n"}, {"input": "3\r\n35 96 7 43 10 14 16 36 95 92 16 50 59 55\r\n", "output": "173\r\n"}, {"input": "4\r\n1 97 18 48 96 65 24 91 17 45 36 27 74 93 78 86 39 55 53 21 26 68 31 33 79 63 80 92 1 26\r\n", "output": "511\r\n"}, {"input": "4\r\n25 42 71 29 50 30 99 79 77 24 76 66 68 23 97 99 65 17 75 62 66 46 48 4 40 71 98 57 21 92\r\n", "output": "603\r\n"}, {"input": "4\r\n49 86 17 7 3 6 86 71 36 10 27 10 58 64 12 16 88 67 93 3 15 20 58 87 97 91 11 6 34 62\r\n", "output": "470\r\n"}, {"input": "5\r\n16 87 36 16 81 53 87 35 63 56 47 91 81 95 80 96 91 7 58 99 25 28 47 60 7 69 49 14 51 52 29 30 83 23 21 52 100 26 91 14 23 94 72 70 40 12 50 32 54 52 18 74 5 15 62 3 48 41 24 25 56 43\r\n", "output": "1060\r\n"}, {"input": "5\r\n40 27 82 94 38 22 66 23 18 34 87 31 71 28 95 5 14 61 76 52 66 6 60 40 68 77 70 63 64 18 47 13 82 55 34 64 30 1 29 24 24 9 65 17 29 96 61 76 72 23 32 26 90 39 54 41 35 66 71 29 75 48\r\n", "output": "1063\r\n"}, {"input": "5\r\n64 72 35 68 92 95 45 15 77 16 26 74 61 65 18 22 32 19 98 97 14 84 70 23 29 1 87 28 88 89 73 79 69 88 43 60 64 64 66 39 17 27 46 71 18 83 73 20 90 77 49 70 84 63 50 72 26 87 26 37 78 65\r\n", "output": "987\r\n"}, {"input": "6\r\n35 61 54 77 70 50 53 70 4 66 58 47 76 100 78 5 43 50 55 93 13 93 59 92 30 74 22 23 98 70 19 56 90 92 19 7 28 53 45 77 42 91 71 56 19 83 100 53 13 93 37 13 70 60 16 13 76 3 12 22 17 26 50 6 63 7 25 41 92 29 36 80 11 4 10 14 77 75 53 82 46 24 56 46 82 36 80 75 8 45 24 22 90 34 45 76 18 38 86 43 7 49 80 56 90 53 12 51 98 47 44 58 32 4 2 6 3 60 38 72 74 46 30 86 1 98\r\n", "output": "2499\r\n"}, {"input": "6\r\n63 13 100 54 31 15 29 58 59 44 2 99 70 33 97 14 70 12 73 42 65 71 68 67 87 83 43 84 18 41 37 22 81 24 27 11 57 28 83 92 39 1 56 15 16 67 16 97 31 52 50 65 63 89 8 52 55 20 71 27 28 35 86 92 94 60 10 65 83 63 89 71 34 20 78 40 34 62 2 86 100 81 87 69 25 4 52 17 57 71 62 38 1 3 54 71 34 85 20 60 80 23 82 47 4 19 7 18 14 18 28 27 4 55 26 71 45 9 2 40 67 28 32 19 81 92\r\n", "output": "2465\r\n"}, {"input": "6\r\n87 62 58 32 81 92 12 50 23 27 38 39 64 74 16 35 84 59 91 87 14 48 90 47 44 95 64 45 31 11 67 5 80 60 36 15 91 3 21 2 40 24 37 69 5 50 23 37 49 19 68 21 49 9 100 94 45 41 22 31 31 48 25 70 25 25 95 88 82 1 37 53 49 31 57 74 94 45 55 93 43 37 13 85 59 72 15 68 3 90 96 55 100 64 63 69 43 33 66 84 57 97 87 34 23 89 97 77 39 89 8 92 68 13 50 36 95 61 71 96 73 13 30 49 57 89\r\n", "output": "2513\r\n"}]
false
stdio
null
true
526/B
526
B
Python 3
PRETESTS
1
46
614,400
10582416
import sys, os import fileinput n = int(input()) + 1 a = [int(x) for x in input().split()] all_count = 2 ** n - 1 b = [0] * all_count counter = 0 for i in range(n, 1, -1): lcnt = 2 ** (i - 1) first = 2 ** (i - 1) - 2 #print(lcnt, first) level = a[first:first + lcnt] for j in range(0, lcnt, 2): index = first + 2 + j if i == n: diff = abs(level[j] - level[j + 1]) counter += diff b[index//2] += level[j] + level[j + 1] + diff else: diff = abs((b[index] - level[j]) - (b[index + 1] - level[j + 1])) counter += diff b[index//2] += b[index] + b[index + 1] + level[j] + level[j + 1] + diff print(counter)
38
61
0
10583501
# fin = open("input.txt") # n = int(fin.readline()) # A = [0] + list(map(int, fin.readline().split())) n = int(input()) A = [0] + list(map(int, input().split())) C = 0 for i in range(2 ** n - 2, -1, -1): C += abs(A[i * 2 + 1] - A[i * 2 + 2]) A[i] += max(A[i * 2 + 1], A[i * 2 + 2]) print(C)
ZeptoLab Code Rush 2015
CF
2,015
1
256
Om Nom and Dark Park
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square $$\frac{i}{2}$$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and $$\frac{i}{2}$$. All numbers ai are positive integers, not exceeding 100.
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
null
Picture for the sample test. Green color denotes the additional street lights.
[{"input": "2\n1 2 3 4 5 6", "output": "5"}]
1,400
["dfs and similar", "greedy", "implementation"]
38
[{"input": "2\r\n1 2 3 4 5 6\r\n", "output": "5\r\n"}, {"input": "2\r\n1 2 3 3 2 2\r\n", "output": "0\r\n"}, {"input": "1\r\n39 52\r\n", "output": "13\r\n"}, {"input": "2\r\n59 96 34 48 8 72\r\n", "output": "139\r\n"}, {"input": "3\r\n87 37 91 29 58 45 51 74 70 71 47 38 91 89\r\n", "output": "210\r\n"}, {"input": "5\r\n39 21 95 89 73 90 9 55 85 32 30 21 68 59 82 91 20 64 52 70 6 88 53 47 30 47 34 14 11 22 42 15 28 54 37 48 29 3 14 13 18 77 90 58 54 38 94 49 45 66 13 74 11 14 64 72 95 54 73 79 41 35\r\n", "output": "974\r\n"}, {"input": "1\r\n49 36\r\n", "output": "13\r\n"}, {"input": "1\r\n77 88\r\n", "output": "11\r\n"}, {"input": "1\r\n1 33\r\n", "output": "32\r\n"}, {"input": "2\r\n72 22 81 23 14 75\r\n", "output": "175\r\n"}, {"input": "2\r\n100 70 27 1 68 52\r\n", "output": "53\r\n"}, {"input": "2\r\n24 19 89 82 22 21\r\n", "output": "80\r\n"}, {"input": "3\r\n86 12 92 91 3 68 57 56 76 27 33 62 71 84\r\n", "output": "286\r\n"}, {"input": "3\r\n14 56 53 61 57 45 40 44 31 9 73 2 61 26\r\n", "output": "236\r\n"}, {"input": "3\r\n35 96 7 43 10 14 16 36 95 92 16 50 59 55\r\n", "output": "173\r\n"}, {"input": "4\r\n1 97 18 48 96 65 24 91 17 45 36 27 74 93 78 86 39 55 53 21 26 68 31 33 79 63 80 92 1 26\r\n", "output": "511\r\n"}, {"input": "4\r\n25 42 71 29 50 30 99 79 77 24 76 66 68 23 97 99 65 17 75 62 66 46 48 4 40 71 98 57 21 92\r\n", "output": "603\r\n"}, {"input": "4\r\n49 86 17 7 3 6 86 71 36 10 27 10 58 64 12 16 88 67 93 3 15 20 58 87 97 91 11 6 34 62\r\n", "output": "470\r\n"}, {"input": "5\r\n16 87 36 16 81 53 87 35 63 56 47 91 81 95 80 96 91 7 58 99 25 28 47 60 7 69 49 14 51 52 29 30 83 23 21 52 100 26 91 14 23 94 72 70 40 12 50 32 54 52 18 74 5 15 62 3 48 41 24 25 56 43\r\n", "output": "1060\r\n"}, {"input": "5\r\n40 27 82 94 38 22 66 23 18 34 87 31 71 28 95 5 14 61 76 52 66 6 60 40 68 77 70 63 64 18 47 13 82 55 34 64 30 1 29 24 24 9 65 17 29 96 61 76 72 23 32 26 90 39 54 41 35 66 71 29 75 48\r\n", "output": "1063\r\n"}, {"input": "5\r\n64 72 35 68 92 95 45 15 77 16 26 74 61 65 18 22 32 19 98 97 14 84 70 23 29 1 87 28 88 89 73 79 69 88 43 60 64 64 66 39 17 27 46 71 18 83 73 20 90 77 49 70 84 63 50 72 26 87 26 37 78 65\r\n", "output": "987\r\n"}, {"input": "6\r\n35 61 54 77 70 50 53 70 4 66 58 47 76 100 78 5 43 50 55 93 13 93 59 92 30 74 22 23 98 70 19 56 90 92 19 7 28 53 45 77 42 91 71 56 19 83 100 53 13 93 37 13 70 60 16 13 76 3 12 22 17 26 50 6 63 7 25 41 92 29 36 80 11 4 10 14 77 75 53 82 46 24 56 46 82 36 80 75 8 45 24 22 90 34 45 76 18 38 86 43 7 49 80 56 90 53 12 51 98 47 44 58 32 4 2 6 3 60 38 72 74 46 30 86 1 98\r\n", "output": "2499\r\n"}, {"input": "6\r\n63 13 100 54 31 15 29 58 59 44 2 99 70 33 97 14 70 12 73 42 65 71 68 67 87 83 43 84 18 41 37 22 81 24 27 11 57 28 83 92 39 1 56 15 16 67 16 97 31 52 50 65 63 89 8 52 55 20 71 27 28 35 86 92 94 60 10 65 83 63 89 71 34 20 78 40 34 62 2 86 100 81 87 69 25 4 52 17 57 71 62 38 1 3 54 71 34 85 20 60 80 23 82 47 4 19 7 18 14 18 28 27 4 55 26 71 45 9 2 40 67 28 32 19 81 92\r\n", "output": "2465\r\n"}, {"input": "6\r\n87 62 58 32 81 92 12 50 23 27 38 39 64 74 16 35 84 59 91 87 14 48 90 47 44 95 64 45 31 11 67 5 80 60 36 15 91 3 21 2 40 24 37 69 5 50 23 37 49 19 68 21 49 9 100 94 45 41 22 31 31 48 25 70 25 25 95 88 82 1 37 53 49 31 57 74 94 45 55 93 43 37 13 85 59 72 15 68 3 90 96 55 100 64 63 69 43 33 66 84 57 97 87 34 23 89 97 77 39 89 8 92 68 13 50 36 95 61 71 96 73 13 30 49 57 89\r\n", "output": "2513\r\n"}]
false
stdio
null
true
703/B
703
B
PyPy 3-64
TESTS
1
46
0
176688839
t=1 while t>0: t-=1 n,k=(int(_) for _ in input().strip().split(' ')) a=list(map(int,input().split())) num=0 for i in range(0,n): num+=a[i] sum=0 for i in range(0,n-1): sum+=a[i]*a[i+1] sum+=a[0]*a[n-1] b=list(map(int,input().split())) for i in range(0,k): if b[i]==1: sum+=a[b[i]-1]*(num-a[0]-a[1]-a[n-1]) continue if b[i]==n: sum+=a[b[i]-1]*(num-a[n-2]-a[n-1]-a[0]) continue sum+=a[b[i]-1]*(num-a[b[i]-2]-a[b[i]-1]-a[b[i]]) print(sum)
63
108
19,148,800
176693684
t=1 while t>0: t-=1 n,k=(int(_) for _ in input().strip().split(' ')) a=list(map(int,input().split())) b=list(map(int,input().split())) vis=[0]*100005 sum=0 for i in range(0,n): sum+=a[i] ans=0 tmp=0 for i in range(0,k): vis[b[i]-1]=1 ans+=a[b[i]-1]*(sum-a[b[i]-1]-tmp) tmp+=a[b[i]-1] for i in range(0,n-1): if vis[i]!=1 and vis[i+1]!=1: ans+=a[i]*a[i+1] if vis[0]!=1 and vis[n-1]!=1: ans+=a[0]*a[n-1] print(ans)
Codeforces Round 365 (Div. 2)
CF
2,016
1
256
Mishka and trip
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country. Here are some interesting facts about XXX: 1. XXX consists of n cities, k of whose (just imagine!) are capital cities. 2. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. 3. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i < n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city. 4. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i. 5. There is at most one road between any two cities. 6. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj. Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a < b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?
The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them. The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities. The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.
Print the only integer — summary price of passing each of the roads in XXX.
null
This image describes first sample case: It is easy to see that summary price is equal to 17. This image describes second sample case: It is easy to see that summary price is equal to 71.
[{"input": "4 1\n2 3 1 2\n3", "output": "17"}, {"input": "5 2\n3 5 2 2 4\n1 4", "output": "71"}]
1,400
["implementation", "math"]
63
[{"input": "4 1\r\n2 3 1 2\r\n3\r\n", "output": "17"}, {"input": "5 2\r\n3 5 2 2 4\r\n1 4\r\n", "output": "71"}, {"input": "3 1\r\n1 1 1\r\n1\r\n", "output": "3"}, {"input": "3 3\r\n1 1 1\r\n1 2 3\r\n", "output": "3"}, {"input": "7 7\r\n6 9 2 7 4 8 7\r\n1 2 3 4 5 6 7\r\n", "output": "775"}, {"input": "5 5\r\n6 2 4 10 2\r\n1 2 3 4 5\r\n", "output": "208"}, {"input": "5 5\r\n6 7 8 8 8\r\n1 2 3 4 5\r\n", "output": "546"}, {"input": "9 4\r\n5 6 7 1 5 4 8 7 1\r\n1 5 7 9\r\n", "output": "647"}, {"input": "7 2\r\n1 6 8 3 3 5 5\r\n1 3\r\n", "output": "255"}, {"input": "9 4\r\n182 938 865 240 911 25 373 22 875\r\n3 6 7 8\r\n", "output": "4972597"}, {"input": "10 4\r\n7931 7116 4954 8578 847 6206 5398 4103 7814 1245\r\n1 3 5 7\r\n", "output": "836854437"}, {"input": "9 7\r\n341 106 584 605 495 512 66 992 713\r\n1 4 5 6 7 8 9\r\n", "output": "8322420"}, {"input": "8 2\r\n43 2961 202 2637 1007 4469 9031 9900\r\n4 7\r\n", "output": "246280951"}, {"input": "8 5\r\n751 782 792 243 111 161 746 331\r\n1 3 4 6 8\r\n", "output": "5635386"}, {"input": "8 4\r\n733 7990 4777 3024 7627 2283 4959 1698\r\n1 3 5 7\r\n", "output": "382022214"}, {"input": "8 6\r\n736 620 367 629 539 975 867 937\r\n1 2 5 6 7 8\r\n", "output": "13910835"}, {"input": "6 2\r\n9436 8718 315 2056 4898 7352\r\n4 6\r\n", "output": "319961666"}, {"input": "6 1\r\n916 913 649 645 312 968\r\n6\r\n", "output": "5373770"}, {"input": "6 2\r\n6703 5345 9335 5285 1268 5207\r\n3 6\r\n", "output": "361632002"}, {"input": "51 3\r\n834 817 726 282 783 437 729 423 444 422 692 522 479 27 744 955 634 885 280 839 851 781 555 286 761 459 245 494 709 464 470 254 862 597 409 276 372 746 135 464 742 400 970 766 388 351 474 104 702 945 835\r\n12 28 29\r\n", "output": "62712861"}, {"input": "52 17\r\n5281 7307 2542 1181 6890 5104 5081 4658 9629 6973 3504 4423 3184 6012 2538 6778 9611 3163 1907 4489 4923 685 5753 2553 5986 520 192 8643 4805 6469 5311 3074 2045 6836 6993 7126 1415 6149 9093 9635 6004 1983 7263 3171 4378 9436 9813 6464 8656 3819 130 763\r\n1 5 7 9 11 13 16 19 21 23 35 38 40 42 47 49 51\r\n", "output": "20412478312"}, {"input": "76 45\r\n29 219 740 819 616 699 8 557 969 550 66 259 615 101 560 640 75 632 752 598 820 714 418 858 669 819 456 597 290 956 461 941 359 318 155 378 257 292 699 249 306 676 890 292 25 225 22 520 776 268 397 438 468 239 174 508 265 216 933 857 564 165 59 779 526 826 597 77 704 420 688 1 689 769 323 98\r\n1 2 3 5 7 8 10 12 14 15 17 18 22 23 25 26 28 30 31 33 34 35 36 37 38 40 43 44 46 47 52 53 55 56 58 60 61 62 63 64 66 69 71 72 73\r\n", "output": "508857909"}, {"input": "76 24\r\n6814 3834 1131 6256 2598 850 7353 1702 5773 1699 35 5103 1368 2258 7891 7455 8546 7316 7428 8864 6536 5750 8455 2624 7326 2197 8239 3806 3016 7126 85 3249 1138 6783 9684 4417 7417 3660 6334 7324 9760 9755 7605 9891 3676 8784 8739 8266 3272 9250 5875 939 4130 6540 7813 6867 9148 781 6190 964 5612 1864 949 7826 9148 6293 4936 870 2042 5838 7141 2030 1241 259 5617 2539\r\n3 5 9 12 15 18 20 23 25 29 31 33 35 37 39 44 46 48 59 63 65 68 72 76\r\n", "output": "43060198680"}, {"input": "50 15\r\n915 8535 2997 4040 9747 2161 9628 8364 1943 136 1403 7037 9713 7741 7463 4316 1543 994 7320 95 6211 8110 2713 5806 7652 6749 3996 2886 8971 6878 1267 9546 1551 6835 9256 5725 9609 1748 8246 6169 9465 4620 9565 1419 3327 1003 9938 9556 882 6178\r\n3 8 10 12 15 18 22 24 27 29 33 37 41 43 46\r\n", "output": "19733750400"}, {"input": "73 27\r\n651 944 104 639 369 961 338 573 516 690 889 227 480 160 299 783 270 331 793 796 64 712 649 88 695 550 829 303 965 780 570 374 371 506 954 632 660 987 986 253 144 993 708 710 890 257 303 651 923 107 386 893 301 387 852 596 72 699 63 241 336 855 160 5 981 447 601 601 305 680 448 676 374\r\n1 3 4 5 6 11 17 18 19 20 27 29 32 33 40 43 46 47 48 53 55 57 61 62 63 67 71\r\n", "output": "460505110"}, {"input": "74 27\r\n8668 693 205 9534 6686 9598 2837 3425 8960 3727 8872 4393 4835 8438 7881 3591 7914 5218 8959 7342 7134 8170 1778 5107 3467 6998 9506 3635 8929 2004 49 701 5059 7285 5236 1540 7643 365 229 2062 7732 3142 7668 8871 2783 7309 529 1695 4255 8084 2708 6936 8300 4015 1142 3705 8564 1031 1685 9262 5077 3674 4788 4981 4693 9896 792 322 5482 584 3852 3484 9410 3889\r\n1 4 6 12 16 19 21 23 26 29 31 33 36 39 41 43 46 48 51 53 55 58 61 64 67 69 73\r\n", "output": "41845373785"}, {"input": "3 1\r\n1 2 3\r\n3\r\n", "output": "11"}]
false
stdio
null
true