contestId
int64
0
1.01k
name
stringlengths
2
58
tags
listlengths
0
11
title
stringclasses
523 values
time-limit
stringclasses
8 values
memory-limit
stringclasses
8 values
problem-description
stringlengths
0
7.15k
input-specification
stringlengths
0
2.05k
output-specification
stringlengths
0
1.5k
demo-input
listlengths
0
7
demo-output
listlengths
0
7
note
stringlengths
0
5.24k
test_cases
listlengths
0
402
timeConsumedMillis
int64
0
8k
memoryConsumedBytes
int64
0
537M
score
float64
-1
3.99
__index_level_0__
int64
0
621k
0
none
[ "none" ]
null
null
Imagine that you are in a building that has exactly *n* floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to *n*. Now you're on the floor number *a*. You are very bored, so you want to take the lift. Floor number *b* has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make *k* consecutive trips in the lift. Let us suppose that at the moment you are on the floor number *x* (initially, you were on floor *a*). For another trip between floors you choose some floor with number *y* (*y*<=≠<=*x*) and the lift travels to this floor. As you cannot visit floor *b* with the secret lab, you decided that the distance from the current floor *x* to the chosen *y* must be strictly less than the distance from the current floor *x* to floor *b* with the secret lab. Formally, it means that the following inequation must fulfill: |*x*<=-<=*y*|<=&lt;<=|*x*<=-<=*b*|. After the lift successfully transports you to floor *y*, you write down number *y* in your notepad. Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of *k* trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109<=+<=7).
The first line of the input contains four space-separated integers *n*, *a*, *b*, *k* (2<=≤<=*n*<=≤<=5000, 1<=≤<=*k*<=≤<=5000, 1<=≤<=*a*,<=*b*<=≤<=*n*, *a*<=≠<=*b*).
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109<=+<=7).
[ "5 2 4 1\n", "5 2 4 2\n", "5 3 4 1\n" ]
[ "2\n", "2\n", "0\n" ]
Two sequences *p*<sub class="lower-index">1</sub>, *p*<sub class="lower-index">2</sub>, ..., *p*<sub class="lower-index">*k*</sub> and *q*<sub class="lower-index">1</sub>, *q*<sub class="lower-index">2</sub>, ..., *q*<sub class="lower-index">*k*</sub> are distinct, if there is such integer *j* (1 ≤ *j* ≤ *k*), that *p*<sub class="lower-index">*j*</sub> ≠ *q*<sub class="lower-index">*j*</sub>. Notes to the samples: 1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| &lt; |2 - 4| and |3 - 2| &lt; |2 - 4|. 1. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip. 1. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
[ { "input": "5 2 4 1", "output": "2" }, { "input": "5 2 4 2", "output": "2" }, { "input": "5 3 4 1", "output": "0" }, { "input": "2 2 1 1", "output": "0" }, { "input": "10 1 10 2", "output": "44" }, { "input": "2222 1206 1425 2222", "output": "40257...
2,000
307,200
0
27,288
173
Camping Groups
[ "data structures", "sortings" ]
null
null
A club wants to take its members camping. In order to organize the event better the club directors decided to partition the members into several groups. Club member *i* has a responsibility value *r**i* and an age value *a**i*. A group is a non-empty subset of club members with one member known as group leader. A group leader should be one of the most responsible members of the group (his responsibility value is not less than responsibility of any other group member) and his age absolute difference with any other group member should not exceed *k*. Some club members are friends and want to be in the same group. They also like their group to be as large as possible. Now you should write a program that answers a series of questions like "What's the largest size of a group containing club member *x* and club member *y*?". It's possible for *x* or *y* to be the group leader.
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=105,<=0<=≤<=*k*<=≤<=109) — the number of club members and the age restriction for one group. The next line contains integer numbers *r*1,<=*r*2,<=...,<=*r**n* (1<=≤<=*r**i*<=≤<=109) separated by space: *r**i* denotes the *i*-th club member's responsibility. In the same way there are integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) in the third line: *a**i* denotes the *i*-th club member's age. The next line contains an integer *q* denoting the number of questions that you should answer (1<=≤<=*q*<=≤<=105). The next *q* lines describe the questions. Each line contains two space-separated integers *x**i* and *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*,<=*x**i*<=≠<=*y**i*) — the indices of the club members that should end up in the same group.
For each question print the maximum size of the group in a line. If making such a group is impossible print -1 instead.
[ "5 1\n1 5 4 1 2\n4 4 3 2 2\n4\n5 3\n2 3\n2 5\n4 1\n" ]
[ "4\n3\n-1\n4\n" ]
In the first query the largest group with members 3 and 5 is {1, 3, 4, 5} where member 3 is the leader. In the second query member 2 should be the leader so the group will be {1, 2, 3}. In the third query the leader of the group should have age 3 so the only leader can be member 3, who is less responsible than member 2. So making a group is impossible. The group for the fourth query is the same as first query.
[]
0
0
-1
27,292
807
T-Shirt Hunt
[ "brute force", "implementation" ]
null
null
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt. Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place *p*. Now the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let *s* be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed: Here "div" is the integer division operator, "mod" is the modulo (the remainder of division) operator. As the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of *s*. You're in the lead of the elimination round of 8VC Venture Cup 2017, having *x* points. You believe that having at least *y* points in the current round will be enough for victory. To change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though. You want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of successful hacks you have to do to achieve that?
The only line contains three integers *p*, *x* and *y* (26<=≤<=*p*<=≤<=500; 1<=≤<=*y*<=≤<=*x*<=≤<=20000) — your place in Codecraft-17, your current score in the elimination round of 8VC Venture Cup 2017, and the smallest number of points you consider sufficient for winning the current round.
Output a single integer — the smallest number of successful hacks you have to do in order to both win the elimination round of 8VC Venture Cup 2017 and ensure getting a Codecraft-17 T-shirt. It's guaranteed that your goal is achievable for any valid input data.
[ "239 10880 9889\n", "26 7258 6123\n", "493 8000 8000\n", "101 6800 6500\n", "329 19913 19900\n" ]
[ "0\n", "2\n", "24\n", "0\n", "8\n" ]
In the first example, there is no need to do any hacks since 10880 points already bring the T-shirt to the 239-th place of Codecraft-17 (that is, you). In this case, according to the pseudocode, the T-shirts will be given to the participants at the following places: In the second example, you have to do two successful and one unsuccessful hack to make your score equal to 7408. In the third example, you need to do as many as 24 successful hacks to make your score equal to 10400. In the fourth example, it's sufficient to do 6 unsuccessful hacks (and no successful ones) to make your score equal to 6500, which is just enough for winning the current round and also getting the T-shirt.
[ { "input": "239 10880 9889", "output": "0" }, { "input": "26 7258 6123", "output": "2" }, { "input": "493 8000 8000", "output": "24" }, { "input": "101 6800 6500", "output": "0" }, { "input": "329 19913 19900", "output": "8" }, { "input": "264 19252 10...
62
0
0
27,371
638
Road Improvement
[ "*special", "dfs and similar", "graphs", "greedy", "trees" ]
null
null
In Berland there are *n* cities and *n*<=-<=1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are.
The first line of the input contains a positive integer *n* (2<=≤<=*n*<=≤<=200<=000) — the number of cities in Berland. Each of the next *n*<=-<=1 lines contains two numbers *u**i*, *v**i*, meaning that the *i*-th road connects city *u**i* and city *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*).
First print number *k* — the minimum number of days needed to repair all the roads in Berland. In next *k* lines print the description of the roads that should be repaired on each of the *k* days. On the *i*-th line print first number *d**i* — the number of roads that should be repaired on the *i*-th day, and then *d**i* space-separated integers — the numbers of the roads that should be repaired on the *i*-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them.
[ "4\n1 2\n3 4\n3 2\n", "6\n3 4\n5 4\n3 2\n1 3\n4 6\n" ]
[ "2\n2 2 1\n1 3\n", "3\n1 1 \n2 2 3 \n2 4 5 \n" ]
In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 — on the second day.
[ { "input": "4\n1 2\n3 4\n3 2", "output": "2\n2 1 2 \n1 3 " }, { "input": "6\n3 4\n5 4\n3 2\n1 3\n4 6", "output": "3\n1 1 \n2 2 3 \n2 4 5 " }, { "input": "8\n1 3\n1 6\n3 4\n6 2\n5 6\n6 7\n7 8", "output": "4\n3 2 3 7 \n2 1 4 \n1 5 \n1 6 " }, { "input": "5\n1 2\n1 3\n1 4\n1 5", ...
62
4,608,000
0
27,383
653
Move by Prime
[ "combinatorics", "math", "number theory" ]
null
null
Pussycat Sonya has an array consisting of *n* positive integers. There are 2*n* possible subsequences of the array. For each subsequence she counts the minimum number of operations to make all its elements equal. Each operation must be one of two: - Choose some element of the subsequence and multiply it by some prime number. - Choose some element of the subsequence and divide it by some prime number. The chosen element must be divisible by the chosen prime number. What is the sum of minimum number of operations for all 2*n* possible subsequences? Find and print this sum modulo 109<=+<=7.
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=300<=000) — the size of the array. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=300<=000) — elements of the array.
Print the sum of minimum number of operation for all possible subsequences of the given array modulo 109<=+<=7.
[ "3\n60 60 40\n", "4\n1 2 3 4\n" ]
[ "6\n", "24\n" ]
In the first sample, there are 8 possible subsequences: (60, 60, 40), (60, 60), (60, 40), (60, 40), (60), (60), (40) and () (empty subsequence). For a subsequence (60, 60, 40) we can make all elements equal by two operations — divide 40 by 2 to get 20, and then multiply 20 by 3 to get 60. It's impossible to achieve the goal using less operations and thus we add 2 to the answer. There are two subsequences equal to (60, 40) and for each of them the also need to make at least 2 operations. In each of other subsequences all numbers are already equal, so we need 0 operations for each of them. The sum is equal to 2 + 2 + 2 = 6.
[]
30
0
0
27,458
990
Graph And Its Complement
[ "constructive algorithms", "graphs", "implementation" ]
null
null
Given three numbers $n, a, b$. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to $a$, and the number of components in its complement is $b$. The matrix must be symmetric, and all digits on the main diagonal must be zeroes. In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices. The adjacency matrix of an undirected graph is a square matrix of size $n$ consisting only of "0" and "1", where $n$ is the number of vertices of the graph and the $i$-th row and the $i$-th column correspond to the $i$-th vertex of the graph. The cell $(i,j)$ of the adjacency matrix contains $1$ if and only if the $i$-th and $j$-th vertices in the graph are connected by an edge. A connected component is a set of vertices $X$ such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to $X$ violates this rule. The complement or inverse of a graph $G$ is a graph $H$ on the same vertices such that two distinct vertices of $H$ are adjacent if and only if they are not adjacent in $G$.
In a single line, three numbers are given $n, a, b \,(1 \le n \le 1000, 1 \le a, b \le n)$: is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.
If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes). Otherwise, on the first line, print "YES"(without quotes). In each of the next $n$ lines, output $n$ digits such that $j$-th digit of $i$-th line must be $1$ if and only if there is an edge between vertices $i$ and $j$ in $G$ (and $0$ otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes. If there are several matrices that satisfy the conditions — output any of them.
[ "3 1 2\n", "3 3 3\n" ]
[ "YES\n001\n001\n110\n", "NO\n" ]
none
[ { "input": "3 1 2", "output": "YES\n001\n001\n110" }, { "input": "3 3 3", "output": "NO" }, { "input": "5 1 1", "output": "YES\n01000\n10100\n01010\n00101\n00010" }, { "input": "123 1 84", "output": "YES\n0011111111111111111111111111111111111111111111111111111111111111111...
46
0
0
27,492
0
none
[ "none" ]
null
null
This is an interactive problem. You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to *x*. More formally, there is a singly liked list built on an array of *n* elements. Element with index *i* contains two integers: *value**i* is the integer value in this element, and *next**i* that is the index of the next element of the singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if *next**i*<=≠<=<=-<=1, then *value**next**i*<=&gt;<=*value**i*. You are given the number of elements in the list *n*, the index of the first element *start*, and the integer *x*. You can make up to 2000 queries of the following two types: - ? i (1<=≤<=*i*<=≤<=*n*) — ask the values *value**i* and *next**i*, - ! ans — give the answer for the problem: the minimum integer, greater than or equal to *x*, or ! -1, if there are no such integers. Your program should terminate after this query. Write a program that solves this problem.
The first line contains three integers *n*, *start*, *x* (1<=≤<=*n*<=≤<=50000, 1<=≤<=*start*<=≤<=*n*, 0<=≤<=*x*<=≤<=109) — the number of elements in the list, the index of the first element and the integer *x*.
To print the answer for the problem, print ! ans, where ans is the minimum integer in the list greater than or equal to *x*, or -1, if there is no such integer.
[ "5 3 80\n97 -1\n58 5\n16 2\n81 1\n79 4\n" ]
[ "? 1\n? 2\n? 3\n? 4\n? 5\n! 81" ]
You can read more about singly linked list by the following link: [https://en.wikipedia.org/wiki/Linked_list#Singly_linked_list](https://en.wikipedia.org/wiki/Linked_list#Singly_linked_list) The illustration for the first sample case. Start and finish elements are marked dark. <img class="tex-graphics" src="https://espresso.codeforces.com/5202ec3b5e896b7db692ff7b80457c26cf6adb32.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "5 3 80\n97 -1\n58 5\n16 2\n81 1\n79 4", "output": "81\n1003" }, { "input": "5 1 6\n1 2\n2 3\n3 4\n4 5\n5 -1", "output": "-1\n1002" }, { "input": "1 1 0\n0 -1", "output": "0\n2" }, { "input": "1 1 2\n0 -1", "output": "-1\n1002" }, { "input": "1 1 100000...
93
1,536,000
-1
27,528
22
Bargaining Table
[ "brute force", "dp" ]
B. Bargaining Table
2
256
Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room *n*<=×<=*m* meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.
The first line contains 2 space-separated numbers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=25) — the office room dimensions. Then there follow *n* lines with *m* characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free.
Output one number — the maximum possible perimeter of a bargaining table for Bob's office room.
[ "3 3\n000\n010\n000\n", "5 4\n1100\n0000\n0000\n0000\n0000\n" ]
[ "8\n", "16\n" ]
none
[ { "input": "3 3\n000\n010\n000", "output": "8" }, { "input": "5 4\n1100\n0000\n0000\n0000\n0000", "output": "16" }, { "input": "3 3\n000\n110\n000", "output": "8" }, { "input": "4 2\n00\n10\n11\n00", "output": "6" }, { "input": "3 5\n00001\n00000\n10100", "out...
154
1,740,800
3.958258
27,556
50
Happy Farm 5
[ "geometry" ]
C. Happy Farm 5
2
256
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them. For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum. The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to . The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
The first line contains an integer *N* which represents the number of cows in the herd (1<=≤<=*N*<=≤<=105). Each of the next *N* lines contains two integers *X**i* and *Y**i* which represent the coordinates of one cow of (|*X**i*|,<=|*Y**i*|<=≤<=106). Several cows can stand on one point.
Print the single number — the minimum number of moves in the sought path.
[ "4\n1 1\n5 1\n5 3\n1 3\n" ]
[ "16\n" ]
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
[ { "input": "4\n1 1\n5 1\n5 3\n1 3", "output": "16" }, { "input": "3\n0 0\n5 0\n0 5", "output": "19" }, { "input": "5\n0 0\n7 7\n7 5\n5 7\n1 1", "output": "22" }, { "input": "5\n1 0\n-1 0\n1 0\n-1 0\n0 0", "output": "8" }, { "input": "9\n1 0\n-1 0\n1 0\n-1 0\n0 0\n...
280
5,324,800
0
27,621
988
Divisibility by 25
[ "brute force", "greedy" ]
null
null
You are given an integer $n$ from $1$ to $10^{18}$ without leading zeroes. In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes. What is the minimum number of moves you have to make to obtain a number that is divisible by $25$? Print -1 if it is impossible to obtain a number that is divisible by $25$.
The first line contains an integer $n$ ($1 \le n \le 10^{18}$). It is guaranteed that the first (left) digit of the number $n$ is not a zero.
If it is impossible to obtain a number that is divisible by $25$, print -1. Otherwise print the minimum number of moves required to obtain such number. Note that you can swap only adjacent digits in the given number.
[ "5071\n", "705\n", "1241367\n" ]
[ "4\n", "1\n", "-1\n" ]
In the first example one of the possible sequences of moves is 5071 $\rightarrow$ 5701 $\rightarrow$ 7501 $\rightarrow$ 7510 $\rightarrow$ 7150.
[ { "input": "5071", "output": "4" }, { "input": "705", "output": "1" }, { "input": "1241367", "output": "-1" }, { "input": "7501", "output": "2" }, { "input": "507", "output": "2" }, { "input": "17010", "output": "1" }, { "input": "52231", ...
62
0
0
27,626
237
Primes on Interval
[ "binary search", "number theory", "two pointers" ]
null
null
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors. Consider positive integers *a*, *a*<=+<=1, ..., *b* (*a*<=≤<=*b*). You want to find the minimum integer *l* (1<=≤<=*l*<=≤<=*b*<=-<=*a*<=+<=1) such that for any integer *x* (*a*<=≤<=*x*<=≤<=*b*<=-<=*l*<=+<=1) among *l* integers *x*, *x*<=+<=1, ..., *x*<=+<=*l*<=-<=1 there are at least *k* prime numbers. Find and print the required minimum *l*. If no value *l* meets the described limitations, print -1.
A single line contains three space-separated integers *a*,<=*b*,<=*k* (1<=≤<=*a*,<=*b*,<=*k*<=≤<=106; *a*<=≤<=*b*).
In a single line print a single integer — the required minimum *l*. If there's no solution, print -1.
[ "2 4 2\n", "6 13 1\n", "1 4 3\n" ]
[ "3\n", "4\n", "-1\n" ]
none
[ { "input": "2 4 2", "output": "3" }, { "input": "6 13 1", "output": "4" }, { "input": "1 4 3", "output": "-1" }, { "input": "5 8 2", "output": "4" }, { "input": "8 10 3", "output": "-1" }, { "input": "1 5 2", "output": "3" }, { "input": "6 ...
623
8,908,800
0
27,646
13
Letter A
[ "geometry", "implementation" ]
B. Letter A
1
64
Little Petya learns how to write. The teacher gave pupils the task to write the letter *A* on the sheet of paper. It is required to check whether Petya really had written the letter *A*. You are given three segments on the plane. They form the letter *A* if the following conditions hold: - Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments. - The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. - The third segment divides each of the first two segments in proportion not less than 1<=/<=4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1<=/<=4).
The first line contains one integer *t* (1<=≤<=*t*<=≤<=10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.
Output one line for each test case. Print «YES» (without quotes), if the segments form the letter *A* and «NO» otherwise.
[ "3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1\n" ]
[ "YES\nNO\nYES\n" ]
none
[ { "input": "3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1", "output": "YES\nNO\nYES" } ]
1,000
10,342,400
0
27,822
785
Anton and Permutation
[ "brute force", "data structures" ]
null
null
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of *n* elements is a sequence of numbers {*a*1,<=*a*2,<=...,<=*a**n*}, in which every number from 1 to *n* appears exactly once. One day Anton got a new permutation and started to play with it. He does the following operation *q* times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (*i*,<=*j*) such that 1<=≤<=*i*<=&lt;<=*j*<=≤<=*n* and *a**i*<=&gt;<=*a**j*. Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him. Initially Anton's permutation was {1,<=2,<=...,<=*n*}, that is *a**i*<==<=*i* for all *i* such that 1<=≤<=*i*<=≤<=*n*.
The first line of the input contains two integers *n* and *q* (1<=≤<=*n*<=≤<=200<=000,<=1<=≤<=*q*<=≤<=50<=000) — the length of the permutation and the number of operations that Anton does. Each of the following *q* lines of the input contains two integers *l**i* and *r**i* (1<=≤<=*l**i*,<=*r**i*<=≤<=*n*) — the indices of elements that Anton swaps during the *i*-th operation. Note that indices of elements that Anton swaps during the *i*-th operation can coincide. Elements in the permutation are numbered starting with one.
Output *q* lines. The *i*-th line of the output is the number of inversions in the Anton's permutation after the *i*-th operation.
[ "5 4\n4 5\n2 4\n2 5\n2 2\n", "2 1\n2 1\n", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1\n" ]
[ "1\n4\n3\n3\n", "1\n", "5\n6\n7\n7\n10\n11\n8\n" ]
Consider the first sample. After the first Anton's operation the permutation will be {1, 2, 3, 5, 4}. There is only one inversion in it: (4, 5). After the second Anton's operation the permutation will be {1, 5, 3, 2, 4}. There are four inversions: (2, 3), (2, 4), (2, 5) and (3, 4). After the third Anton's operation the permutation will be {1, 4, 3, 2, 5}. There are three inversions: (2, 3), (2, 4) and (3, 4). After the fourth Anton's operation the permutation doesn't change, so there are still three inversions.
[ { "input": "5 4\n4 5\n2 4\n2 5\n2 2", "output": "1\n4\n3\n3" }, { "input": "2 1\n2 1", "output": "1" }, { "input": "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1", "output": "5\n6\n7\n7\n10\n11\n8" }, { "input": "42 42\n23 7\n9 6\n17 22\n19 23\n15 42\n14 10\n17 12\n2 25\n8 39\n13 9\...
77
536,883,200
0
27,824
208
Police Station
[ "dp", "graphs", "shortest paths" ]
null
null
The Berland road network consists of *n* cities and of *m* bidirectional roads. The cities are numbered from 1 to *n*, where the main capital city has number *n*, and the culture capital — number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time. All residents of Berland are very lazy people, and so when they want to get from city *v* to city *u*, they always choose one of the shortest paths (no matter which one). The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous. Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
The first input line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=100, ) — the number of cities and the number of roads in Berland, correspondingly. Next *m* lines contain pairs of integers *v**i*, *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*n*, *v**i*<=≠<=*u**i*) — the numbers of cities that are connected by the *i*-th road. The numbers on a line are separated by a space. It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10<=-<=6.
[ "4 4\n1 2\n2 4\n1 3\n3 4\n", "11 14\n1 2\n1 3\n2 4\n3 4\n4 5\n4 6\n5 11\n6 11\n1 8\n8 9\n9 7\n11 7\n1 10\n10 4\n" ]
[ "1.000000000000\n", "1.714285714286\n" ]
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8f23cc2cd3bef67bde56e16911c7af627da25d4d.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d7723df54e28c93b1c3b9d4c68b039b5071092af.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[]
92
0
0
27,844
597
Subsequences
[ "data structures", "dp" ]
null
null
For the given sequence with *n* different elements find the number of increasing subsequences with *k*<=+<=1 elements. It is guaranteed that the answer is not greater than 8·1018.
First line contain two integer values *n* and *k* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*k*<=≤<=10) — the length of sequence and the number of elements in increasing subsequences. Next *n* lines contains one integer *a**i* (1<=≤<=*a**i*<=≤<=*n*) each — elements of sequence. All values *a**i* are different.
Print one integer — the answer to the problem.
[ "5 2\n1\n2\n3\n5\n4\n" ]
[ "7\n" ]
none
[ { "input": "5 2\n1\n2\n3\n5\n4", "output": "7" }, { "input": "1 0\n1", "output": "1" }, { "input": "2 1\n1\n2", "output": "1" }, { "input": "2 1\n2\n1", "output": "0" }, { "input": "3 2\n1\n2\n3", "output": "1" }, { "input": "3 1\n1\n3\n2", "output...
1,000
17,408,000
0
27,907
616
Expensive Strings
[ "string suffix structures", "strings" ]
null
null
You are given *n* strings *t**i*. Each string has cost *c**i*. Let's define the function of string , where *p**s*,<=*i* is the number of occurrences of *s* in *t**i*, |*s*| is the length of the string *s*. Find the maximal value of function *f*(*s*) over all strings. Note that the string *s* is not necessarily some string from *t*.
The first line contains the only integer *n* (1<=≤<=*n*<=≤<=105) — the number of strings in *t*. Each of the next *n* lines contains contains a non-empty string *t**i*. *t**i* contains only lowercase English letters. It is guaranteed that the sum of lengths of all strings in *t* is not greater than 5·105. The last line contains *n* integers *c**i* (<=-<=107<=≤<=*c**i*<=≤<=107) — the cost of the *i*-th string.
Print the only integer *a* — the maximal value of the function *f*(*s*) over all strings *s*. Note one more time that the string *s* is not necessarily from *t*.
[ "2\naa\nbb\n2 1\n", "2\naa\nab\n2 1\n" ]
[ "4\n", "5\n" ]
none
[ { "input": "2\naa\nbb\n2 1", "output": "4" }, { "input": "2\naa\nab\n2 1", "output": "5" }, { "input": "1\naaa\n2", "output": "8" }, { "input": "3\na\naa\naaa\n1 2 3", "output": "16" }, { "input": "3\na\naaa\naa\n2 1 3", "output": "11" }, { "input": "1...
30
0
0
27,960
440
One-Based Arithmetic
[ "brute force", "dfs and similar", "divide and conquer" ]
null
null
Prof. Vasechkin wants to represent positive integer *n* as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
The first line of the input contains integer *n* (1<=≤<=*n*<=&lt;<=1015).
Print expected minimal number of digits 1.
[ "121\n" ]
[ "6\n" ]
none
[ { "input": "121", "output": "6" }, { "input": "10", "output": "3" }, { "input": "72", "output": "15" }, { "input": "1", "output": "1" }, { "input": "2", "output": "2" }, { "input": "3", "output": "3" }, { "input": "4", "output": "4" }...
139
2,457,600
3
27,961
208
Prizes, Prizes, more Prizes
[ "implementation" ]
null
null
Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points. Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points. The sweepstake has the following prizes (the prizes are sorted by increasing of their cost): - a mug (costs *a* points), - a towel (costs *b* points), - a bag (costs *c* points), - a bicycle (costs *d* points), - a car (costs *e* points). Now Vasya wants to recollect what prizes he has received. You know sequence *p*1,<=*p*2,<=...,<=*p**n*, where *p**i* is the number of points Vasya got for the *i*-th bar. The sequence of points is given in the chronological order. You also know numbers *a*, *b*, *c*, *d*, *e*. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=109). The third line contains 5 integers *a*, *b*, *c*, *d*, *e* (1<=≤<=*a*<=&lt;<=*b*<=&lt;<=*c*<=&lt;<=*d*<=&lt;<=*e*<=≤<=109) — the prizes' costs.
Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. 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.
[ "3\n3 10 4\n2 4 10 15 20\n", "4\n10 4 39 2\n3 5 10 11 12\n" ]
[ "1 1 1 0 0 \n1\n", "3 0 1 0 3 \n0\n" ]
In the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.
[ { "input": "3\n3 10 4\n2 4 10 15 20", "output": "1 1 1 0 0 \n1" }, { "input": "4\n10 4 39 2\n3 5 10 11 12", "output": "3 0 1 0 3 \n0" }, { "input": "1\n45\n1 2 3 4 5", "output": "0 0 0 0 9 \n0" }, { "input": "1\n50\n1 2 4 5 6", "output": "0 1 0 0 8 \n0" }, { "inpu...
2,000
0
0
28,024
952
Cheese Board
[]
null
null
Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard).
The first line of input contains a single integer *N* (1<=≤<=*N*<=≤<=100) — the number of cheeses you have. The next *N* lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.
Output a single number.
[ "9\nbrie soft\ncamembert soft\nfeta soft\ngoat soft\nmuenster soft\nasiago hard\ncheddar hard\ngouda hard\nswiss hard\n", "6\nparmesan hard\nemmental hard\nedam hard\ncolby hard\ngruyere hard\nasiago hard\n" ]
[ "3\n", "4\n" ]
none
[ { "input": "9\nbrie soft\ncamembert soft\nfeta soft\ngoat soft\nmuenster soft\nasiago hard\ncheddar hard\ngouda hard\nswiss hard", "output": "3" }, { "input": "6\nparmesan hard\nemmental hard\nedam hard\ncolby hard\ngruyere hard\nasiago hard", "output": "4" }, { "input": "9\ngorgonzola s...
61
0
0
28,073
975
Hag's Khashba
[ "geometry" ]
null
null
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering. Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance. Hag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a strictly convex polygon with $n$ vertices. Hag brought two pins and pinned the polygon with them in the $1$-st and $2$-nd vertices to the wall. His dad has $q$ queries to Hag of two types. - $1$ $f$ $t$: pull a pin from the vertex $f$, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex $t$. - $2$ $v$: answer what are the coordinates of the vertex $v$. Please help Hag to answer his father's queries. You can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.
The first line contains two integers $n$ and $q$ ($3\leq n \leq 10\,000$, $1 \leq q \leq 200000$) — the number of vertices in the polygon and the number of queries. The next $n$ lines describe the wooden polygon, the $i$-th line contains two integers $x_i$ and $y_i$ ($|x_i|, |y_i|\leq 10^8$) — the coordinates of the $i$-th vertex of the polygon. It is guaranteed that polygon is strictly convex and the vertices are given in the counter-clockwise order and all vertices are distinct. The next $q$ lines describe the queries, one per line. Each query starts with its type $1$ or $2$. Each query of the first type continues with two integers $f$ and $t$ ($1 \le f, t \le n$) — the vertex the pin is taken from, and the vertex the pin is put to and the polygon finishes rotating. It is guaranteed that the vertex $f$ contains a pin. Each query of the second type continues with a single integer $v$ ($1 \le v \le n$) — the vertex the coordinates of which Hag should tell his father. It is guaranteed that there is at least one query of the second type.
The output should contain the answer to each query of second type — two numbers in a separate line. Your answer is considered correct, if its absolute or relative error does not exceed $10^{-4}$. Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is considered correct if $\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}$
[ "3 4\n0 0\n2 0\n2 2\n1 1 2\n2 1\n2 2\n2 3\n", "3 2\n-1 1\n0 0\n1 1\n1 1 2\n2 1\n" ]
[ "3.4142135624 -1.4142135624\n2.0000000000 0.0000000000\n0.5857864376 -1.4142135624\n", "1.0000000000 -1.0000000000\n" ]
In the first test note the initial and the final state of the wooden polygon. Red Triangle is the initial state and the green one is the triangle after rotation around $(2,0)$. In the second sample note that the polygon rotates $180$ degrees counter-clockwise or clockwise direction (it does not matter), because Hag's father makes sure that the polygon is stable and his son does not trick him.
[ { "input": "3 4\n0 0\n2 0\n2 2\n1 1 2\n2 1\n2 2\n2 3", "output": "3.4142135624 -1.4142135624\n2.0000000000 0.0000000000\n0.5857864376 -1.4142135624" }, { "input": "3 2\n-1 1\n0 0\n1 1\n1 1 2\n2 1", "output": "1.0000000000 -1.0000000000" }, { "input": "10 10\n0 -100000000\n1 -100000000\n1...
30
0
0
28,081
300
Empire Strikes Back
[ "binary search", "math", "number theory" ]
null
null
In a far away galaxy there is war again. The treacherous Republic made *k* precision strikes of power *a**i* on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces. To successfully complete the conflict, the confrontation balance after the blow should be a positive integer. The balance of confrontation is a number that looks like , where *p*<==<=*n*! (*n* is the power of the Imperial strike), . After many years of war the Empire's resources are low. So to reduce the costs, *n* should be a minimum positive integer that is approved by the commanders. Help the Empire, find the minimum positive integer *n*, where the described fraction is a positive integer.
The first line contains integer *k* (1<=≤<=*k*<=≤<=106). The second line contains *k* integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=107).
Print the minimum positive integer *n*, needed for the Empire to win. Please, do not use the %lld to read or write 64-but integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
[ "2\n1000 1000\n", "1\n2\n" ]
[ "2000", "2" ]
none
[]
62
0
0
28,091
711
Chris and Magic Square
[ "constructive algorithms", "implementation" ]
null
null
ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a *n*<=×<=*n* magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell. Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=500) — the number of rows and columns of the magic grid. *n* lines follow, each of them contains *n* integers. The *j*-th number in the *i*-th of them denotes *a**i*,<=*j* (1<=≤<=*a**i*,<=*j*<=≤<=109 or *a**i*,<=*j*<==<=0), the number in the *i*-th row and *j*-th column of the magic grid. If the corresponding cell is empty, *a**i*,<=*j* will be equal to 0. Otherwise, *a**i*,<=*j* is positive. It is guaranteed that there is exactly one pair of integers *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) such that *a**i*,<=*j*<==<=0.
Output a single integer, the positive integer *x* (1<=≤<=*x*<=≤<=1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer *x* does not exist, output <=-<=1 instead. If there are multiple solutions, you may print any of them.
[ "3\n4 0 2\n3 5 7\n8 1 6\n", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1\n", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1\n" ]
[ "9\n", "1\n", "-1\n" ]
In the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is: 4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15. The sum of numbers in each column is: 4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15. The sum of numbers in the two diagonals is: 4 + 5 + 6 = 2 + 5 + 8 = 15. In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.
[ { "input": "3\n4 0 2\n3 5 7\n8 1 6", "output": "9" }, { "input": "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "output": "1" }, { "input": "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1", "output": "-1" }, { "input": "1\n0", "output": "1" }, { "input": "10\n92 67 99 74 1 51 8 ...
46
6,963,200
-1
28,175
549
Happy Line
[ "constructive algorithms", "greedy", "sortings" ]
null
null
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of *n* Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person *a* stands just behind person *b*, then person *a* can pay person *b* 1 dollar, then *a* and *b* get swapped. Of course, if person *a* has zero dollars, he can not swap places with person *b*. Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them. Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.
The first line contains integer *n* (1<=≤<=*n*<=≤<=200<=000) — the number of residents who stand in the line. The second line contains *n* space-separated integers *a**i* (0<=≤<=*a**i*<=≤<=109), where *a**i* is the number of Berland dollars of a man standing on the *i*-th position in the line. The positions are numbered starting from the end of the line.
If it is impossible to make all the residents happy, print ":(" without the quotes. Otherwise, print in the single line *n* space-separated integers, the *i*-th of them must be equal to the number of money of the person on position *i* in the new line. If there are multiple answers, print any of them.
[ "2\n11 8\n", "5\n10 9 7 10 6\n", "3\n12 3 3\n" ]
[ "9 10 ", ":(\n", "4 4 10 " ]
In the first sample two residents should swap places, after that the first resident has 10 dollars and he is at the head of the line and the second resident will have 9 coins and he will be at the end of the line. In the second sample it is impossible to achieve the desired result. In the third sample the first person can swap with the second one, then they will have the following numbers of dollars: 4 11 3, then the second person (in the new line) swaps with the third one, and the resulting numbers of dollars will equal to: 4 4 10. In this line everybody will be happy.
[ { "input": "2\n11 8", "output": "9 10 " }, { "input": "5\n10 9 7 10 6", "output": ":(" }, { "input": "3\n12 3 3", "output": "4 4 10 " }, { "input": "4\n7 3 9 10", "output": "4 6 9 10 " }, { "input": "1\n1", "output": "1 " }, { "input": "5\n15 5 8 6 3",...
124
2,048,000
-1
28,199
121
Lucky Transformation
[ "strings" ]
null
null
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has a number consisting of *n* digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it *d*. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation *k* times: find the minimum *x* (1<=≤<=*x*<=&lt;<=*n*) such that *d**x*<==<=4 and *d**x*<=+<=1<==<=7, if *x* is odd, then to assign *d**x*<==<=*d**x*<=+<=1<==<=4, otherwise to assign *d**x*<==<=*d**x*<=+<=1<==<=7. Note that if no *x* was found, then the operation counts as completed and the array doesn't change at all. You are given the initial number as an array of digits and the number *k*. Help Petya find the result of completing *k* operations.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*k*<=≤<=109) — the number of digits in the number and the number of completed operations. The second line contains *n* digits without spaces representing the array of digits *d*, starting with *d*1. It is guaranteed that the first digit of the number does not equal zero.
In the single line print the result without spaces — the number after the *k* operations are fulfilled.
[ "7 4\n4727447\n", "4 2\n4478\n" ]
[ "4427477\n", "4478\n" ]
In the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477. In the second sample: 4478 → 4778 → 4478.
[ { "input": "7 4\n4727447", "output": "4427477" }, { "input": "4 2\n4478", "output": "4478" }, { "input": "7 7\n4211147", "output": "4211177" }, { "input": "7 6\n4747477", "output": "4444477" }, { "input": "10 2\n9474444474", "output": "9774444774" }, { ...
340
9,728,000
0
28,227
0
none
[ "none" ]
null
null
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point *d*. Johnny's truck has a gas tank that holds exactly *n* liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are *m* gas stations located at various points along the way to the district center. The *i*-th station is located at the point *x**i* on the number line and sells an unlimited amount of fuel at a price of *p**i* dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.
The first line of input contains three space separated integers *d*, *n*, and *m* (1<=≤<=*n*<=≤<=*d*<=≤<=109, 1<=≤<=*m*<=≤<=200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively. Each of the next *m* lines contains two integers *x**i*, *p**i* (1<=≤<=*x**i*<=≤<=*d*<=-<=1, 1<=≤<=*p**i*<=≤<=106) — the position and cost of gas at the *i*-th gas station. It is guaranteed that the positions of the gas stations are distinct.
Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.
[ "10 4 4\n3 5\n5 8\n6 3\n8 4\n", "16 5 2\n8 2\n5 1\n" ]
[ "22\n", "-1\n" ]
In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars. In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
[ { "input": "10 4 4\n3 5\n5 8\n6 3\n8 4", "output": "22" }, { "input": "16 5 2\n8 2\n5 1", "output": "-1" }, { "input": "400000000 400000000 3\n1 139613\n19426 13509\n246298622 343529", "output": "0" }, { "input": "229 123 2\n170 270968\n76 734741", "output": "50519939" ...
1,403
17,715,200
3
28,242
862
Mahmoud and Ehab and the function
[ "binary search", "data structures", "sortings" ]
null
null
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array *a* of length *n* and array *b* of length *m*. He introduced a function *f*(*j*) which is defined for integers *j*, which satisfy 0<=≤<=*j*<=≤<=*m*<=-<=*n*. Suppose, *c**i*<==<=*a**i*<=-<=*b**i*<=+<=*j*. Then *f*(*j*)<==<=|*c*1<=-<=*c*2<=+<=*c*3<=-<=*c*4... *c**n*|. More formally, . Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid *j*. They found it a bit easy, so Dr. Evil made their task harder. He will give them *q* update queries. During each update they should add an integer *x**i* to all elements in *a* in range [*l**i*;*r**i*] i.e. they should add *x**i* to *a**l**i*,<=*a**l**i*<=+<=1,<=... ,<=*a**r**i* and then they should calculate the minimum value of *f*(*j*) for all valid *j*. Please help Mahmoud and Ehab.
The first line contains three integers *n*,<=*m* and *q* (1<=≤<=*n*<=≤<=*m*<=≤<=105, 1<=≤<=*q*<=≤<=105) — number of elements in *a*, number of elements in *b* and number of queries, respectively. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n*. (<=-<=109<=≤<=*a**i*<=≤<=109) — elements of *a*. The third line contains *m* integers *b*1,<=*b*2,<=...,<=*b**m*. (<=-<=109<=≤<=*b**i*<=≤<=109) — elements of *b*. Then *q* lines follow describing the queries. Each of them contains three integers *l**i* *r**i* *x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*, <=-<=109<=≤<=*x*<=≤<=109) — range to be updated and added value.
The first line should contain the minimum value of the function *f* before any update. Then output *q* lines, the *i*-th of them should contain the minimum value of the function *f* after performing the *i*-th update .
[ "5 6 3\n1 2 3 4 5\n1 2 3 4 5 6\n1 1 10\n1 1 -9\n1 5 -1\n" ]
[ "0\n9\n0\n0\n" ]
For the first example before any updates it's optimal to choose *j* = 0, *f*(0) = |(1 - 1) - (2 - 2) + (3 - 3) - (4 - 4) + (5 - 5)| = |0| = 0. After the first update *a* becomes {11, 2, 3, 4, 5} and it's optimal to choose *j* = 1, *f*(1) = |(11 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6) = |9| = 9. After the second update *a* becomes {2, 2, 3, 4, 5} and it's optimal to choose *j* = 1, *f*(1) = |(2 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6)| = |0| = 0. After the third update *a* becomes {1, 1, 2, 3, 4} and it's optimal to choose *j* = 0, *f*(0) = |(1 - 1) - (1 - 2) + (2 - 3) - (3 - 4) + (4 - 5)| = |0| = 0.
[ { "input": "5 6 3\n1 2 3 4 5\n1 2 3 4 5 6\n1 1 10\n1 1 -9\n1 5 -1", "output": "0\n9\n0\n0" }, { "input": "1 1 1\n937982044\n179683049\n1 1 821220804", "output": "758298995\n1579519799" } ]
46
4,812,800
-1
28,329
364
Matrix
[ "combinatorics", "data structures", "implementation" ]
null
null
You have a string of decimal digits *s*. Let's define *b**ij*<==<=*s**i*·*s**j*. Find in matrix *b* the number of such rectangles that the sum *b**ij* for all cells (*i*,<=*j*) that are the elements of the rectangle equals *a* in each rectangle. A rectangle in a matrix is a group of four integers (*x*,<=*y*,<=*z*,<=*t*) (*x*<=≤<=*y*,<=*z*<=≤<=*t*). The elements of the rectangle are all cells (*i*,<=*j*) such that *x*<=≤<=*i*<=≤<=*y*,<=*z*<=≤<=*j*<=≤<=*t*.
The first line contains integer *a* (0<=≤<=*a*<=≤<=109), the second line contains a string of decimal integers *s* (1<=≤<=|*s*|<=≤<=4000).
Print a single integer — the answer to a problem. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "10\n12345\n", "16\n439873893693495623498263984765\n" ]
[ "6\n", "40\n" ]
none
[ { "input": "10\n12345", "output": "6" }, { "input": "16\n439873893693495623498263984765", "output": "40" }, { "input": "0\n1230", "output": "19" }, { "input": "8398\n67950927224842887617892831243606761170908507858527", "output": "0" }, { "input": "2\n11", "out...
639
31,436,800
3
28,444
0
none
[ "none" ]
null
null
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of *n* small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than *k* characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than *k* characters are deleted. You also have to find any possible way to delete the characters.
The first input data line contains a string whose length is equal to *n* (1<=≤<=*n*<=≤<=105). The string consists of lowercase Latin letters. The second line contains the number *k* (0<=≤<=*k*<=≤<=105).
Print on the first line the only number *m* — the least possible number of different characters that could remain in the given string after it loses no more than *k* characters. Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly *m* distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly *m* distinct characters, print any of them.
[ "aaaaa\n4\n", "abacaba\n4\n", "abcdefgh\n10\n" ]
[ "1\naaaaa\n", "1\naaaa\n", "0\n\n" ]
In the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length. In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string. In the third sample you are given a line whose length is equal to 8, and *k* = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string.
[ { "input": "aaaaa\n4", "output": "1\naaaaa" }, { "input": "abacaba\n4", "output": "1\naaaa" }, { "input": "abcdefgh\n10", "output": "0" }, { "input": "aaaaaaaaaaaaaaaaaaaa\n19", "output": "1\naaaaaaaaaaaaaaaaaaaa" }, { "input": "abcdefghijjihgedcba\n0", "outpu...
92
0
0
28,502
0
none
[ "none" ]
null
null
You are given a tree with *n* vertices and you are allowed to perform no more than 2*n* transformations on it. Transformation is defined by three vertices *x*,<=*y*,<=*y*' and consists of deleting edge (*x*,<=*y*) and adding edge (*x*,<=*y*'). Transformation *x*,<=*y*,<=*y*' could be performed if all the following conditions are satisfied: 1. There is an edge (*x*,<=*y*) in the current tree. 1. After the transformation the graph remains a tree. 1. After the deletion of edge (*x*,<=*y*) the tree would consist of two connected components. Let's denote the set of nodes in the component containing vertex *x* by *V**x*, and the set of nodes in the component containing vertex *y* by *V**y*. Then condition |*V**x*|<=&gt;<=|*V**y*| should be satisfied, i.e. the size of the component with *x* should be strictly larger than the size of the component with *y*. You should minimize the sum of squared distances between all pairs of vertices in a tree, which you could get after no more than 2*n* transformations and output any sequence of transformations leading initial tree to such state. Note that you don't need to minimize the number of operations. It is necessary to minimize only the sum of the squared distances.
The first line of input contains integer *n* (1<=≤<=*n*<=≤<=2·105) — number of vertices in tree. The next *n*<=-<=1 lines of input contains integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=*n*,<=*a*<=≠<=*b*) — the descriptions of edges. It is guaranteed that the given edges form a tree.
In the first line output integer *k* (0<=≤<=*k*<=≤<=2*n*) — the number of transformations from your example, minimizing sum of squared distances between all pairs of vertices. In each of the next *k* lines output three integers *x*,<=*y*,<=*y*' — indices of vertices from the corresponding transformation. Transformations with *y*<==<=*y*' are allowed (even though they don't change tree) if transformation conditions are satisfied. If there are several possible answers, print any of them.
[ "3\n3 2\n1 3\n", "7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n" ]
[ "0\n", "2\n4 3 2\n4 5 6" ]
This is a picture for the second sample. Added edges are dark, deleted edges are dotted. <img class="tex-graphics" src="https://espresso.codeforces.com/e673f9bdb501a0674ec4a21da846eef00abe1aaf.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[]
46
0
0
28,552
215
Crosses
[ "brute force", "implementation" ]
null
null
There is a board with a grid consisting of *n* rows and *m* columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number *i* and column number *j* as (*i*,<=*j*). A group of six numbers (*a*,<=*b*,<=*c*,<=*d*,<=*x*0,<=*y*0), where 0<=≤<=*a*,<=*b*,<=*c*,<=*d*, is a cross, and there is a set of cells that are assigned to it. Cell (*x*,<=*y*) belongs to this set if at least one of two conditions are fulfilled: - |*x*0<=-<=*x*|<=≤<=*a* and |*y*0<=-<=*y*|<=≤<=*b* - |*x*0<=-<=*x*|<=≤<=*c* and |*y*0<=-<=*y*|<=≤<=*d* Your task is to find the number of different groups of six numbers, (*a*,<=*b*,<=*c*,<=*d*,<=*x*0,<=*y*0) that determine the crosses of an area equal to *s*, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell (*x*,<=*y*) of the cross 1<=≤<=*x*<=≤<=*n*; 1<=≤<=*y*<=≤<=*m* holds). The area of the cross is the number of cells it has. Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.
The input consists of a single line containing three integers *n*, *m* and *s* (1<=≤<=*n*,<=*m*<=≤<=500, 1<=≤<=*s*<=≤<=*n*·*m*). The integers are separated by a space.
Print a single integer — the number of distinct groups of six integers that denote crosses with area *s* and that are fully placed on the *n*<=×<=*m* grid. 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.
[ "2 2 1\n", "3 4 5\n" ]
[ "4\n", "4\n" ]
In the first sample the sought groups of six numbers are: (0, 0, 0, 0, 1, 1), (0, 0, 0, 0, 1, 2), (0, 0, 0, 0, 2, 1), (0, 0, 0, 0, 2, 2). In the second sample the sought groups of six numbers are: (0, 1, 1, 0, 2, 2), (0, 1, 1, 0, 2, 3), (1, 0, 0, 1, 2, 2), (1, 0, 0, 1, 2, 3).
[ { "input": "2 2 1", "output": "4" }, { "input": "3 4 5", "output": "4" }, { "input": "2 2 3", "output": "0" }, { "input": "5 1 3", "output": "9" }, { "input": "9 7 55", "output": "4" }, { "input": "5 10 25", "output": "102" }, { "input": "2...
60
0
0
28,606
559
Gerald and Path
[ "dp", "sortings" ]
null
null
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight. The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument. You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of spotlights. Each of the *n* lines contains two space-separated integers, *a**i* and *l**i* (0<=≤<=*a**i*<=≤<=108, 1<=≤<=*l**i*<=≤<=108). Number *a**i* shows how much further the *i*-th spotlight to the north, and number *l**i* shows the length of the segment it illuminates. It is guaranteed that all the *a**i*'s are distinct.
Print a single integer — the maximum total length of the illuminated part of the path.
[ "3\n1 1\n2 2\n3 3\n", "4\n1 2\n3 3\n4 3\n6 2\n" ]
[ "5\n", "9\n" ]
none
[ { "input": "3\n1 1\n2 2\n3 3", "output": "5" }, { "input": "4\n1 2\n3 3\n4 3\n6 2", "output": "9" }, { "input": "5\n3 3\n4 1\n2 2\n0 3\n9 5", "output": "13" }, { "input": "5\n3 3\n4 3\n6 4\n2 3\n1 5", "output": "14" }, { "input": "5\n1 2\n7 5\n9 4\n5 1\n3 5", ...
342
20,787,200
3
28,663
215
Hot Days
[ "greedy" ]
null
null
The official capital and the cultural capital of Berland are connected by a single road running through *n* regions. Each region has a unique climate, so the *i*-th (1<=≤<=*i*<=≤<=*n*) region has a stable temperature of *t**i* degrees in summer. This summer a group of *m* schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the *i*-th region and has *k* schoolchildren, then the temperature inside the bus is *t**i*<=+<=*k* degrees. Of course, nobody likes it when the bus is hot. So, when the bus drives through the *i*-th region, if it has more than *T**i* degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as *x**i* rubles and it is charged in each region where the temperature in the bus exceeds the limit. To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the *i*-th region will cost the organizers *cost**i* rubles. Please note that sorting children into buses takes no money. Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
The first input line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=106) — the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next *n* lines contain four integers each: the *i*-th line contains *t**i*, *T**i*, *x**i* and *cost**i* (1<=≤<=*t**i*,<=*T**i*,<=*x**i*,<=*cost**i*<=≤<=106). The numbers in the lines are separated by single spaces.
Print the only integer — the minimum number of roubles the organizers will have to spend to transport all schoolchildren. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
[ "2 10\n30 35 1 100\n20 35 10 10\n", "3 100\n10 30 1000 1\n5 10 1000 3\n10 40 1000 100000\n" ]
[ "120\n", "200065\n" ]
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.
[ { "input": "2 10\n30 35 1 100\n20 35 10 10", "output": "120" }, { "input": "3 100\n10 30 1000 1\n5 10 1000 3\n10 40 1000 100000", "output": "200065" }, { "input": "10 1\n8 6 3 4\n9 10 7 7\n1 3 9 5\n10 9 4 2\n1 10 2 10\n1 1 8 5\n5 5 9 2\n5 8 4 3\n4 4 9 7\n5 7 5 10", "output": "88" }...
1,372
307,200
3
28,689
337
Quiz
[ "binary search", "greedy", "math", "matrices", "number theory" ]
null
null
Manao is taking part in a quiz. The quiz consists of *n* consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number *k*, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly *m* questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109<=+<=9).
The single line contains three space-separated integers *n*, *m* and *k* (2<=≤<=*k*<=≤<=*n*<=≤<=109; 0<=≤<=*m*<=≤<=*n*).
Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109<=+<=9).
[ "5 3 2\n", "5 4 2\n" ]
[ "3\n", "6\n" ]
Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 *mod* 1000000009, even though 2000000020 *mod* 1000000009 is a smaller number.
[ { "input": "5 3 2", "output": "3" }, { "input": "5 4 2", "output": "6" }, { "input": "300 300 3", "output": "17717644" }, { "input": "300 282 7", "output": "234881124" }, { "input": "1000000000 1000000000 1000000000", "output": "999999991" }, { "input"...
92
0
0
28,787
272
Dima and Staircase
[ "data structures", "implementation" ]
null
null
Dima's got a staircase that consists of *n* stairs. The first stair is at height *a*1, the second one is at *a*2, the last one is at *a**n* (1<=≤<=*a*1<=≤<=*a*2<=≤<=...<=≤<=*a**n*). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The *i*-th box has width *w**i* and height *h**i*. Dima throws each box vertically down on the first *w**i* stairs of the staircase, that is, the box covers stairs with numbers 1,<=2,<=...,<=*w**i*. Each thrown box flies vertically down until at least one of the two following events happen: - the bottom of the box touches the top of a stair; - the bottom of the box touches the top of a box, thrown earlier. We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width *w**i* cannot touch the stair number *w**i*<=+<=1. You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of *n* integers, *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109; *a**i*<=≤<=*a**i*<=+<=1). The next line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of boxes. Each of the following *m* lines contains a pair of integers *w**i*,<=*h**i* (1<=≤<=*w**i*<=≤<=*n*; 1<=≤<=*h**i*<=≤<=109) — the size of the *i*-th thrown box. The numbers in the lines are separated by spaces.
Print *m* integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input. 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.
[ "5\n1 2 3 6 6\n4\n1 1\n3 1\n1 1\n4 3\n", "3\n1 2 3\n2\n1 1\n3 1\n", "1\n1\n5\n1 2\n1 10\n1 10\n1 10\n1 10\n" ]
[ "1\n3\n4\n6\n", "1\n3\n", "1\n3\n13\n23\n33\n" ]
The first sample are shown on the picture.
[ { "input": "5\n1 2 3 6 6\n4\n1 1\n3 1\n1 1\n4 3", "output": "1\n3\n4\n6" }, { "input": "3\n1 2 3\n2\n1 1\n3 1", "output": "1\n3" }, { "input": "1\n1\n5\n1 2\n1 10\n1 10\n1 10\n1 10", "output": "1\n3\n13\n23\n33" }, { "input": "8\n6 10 18 23 30 31 31 33\n1\n5 3", "output":...
2,000
13,004,800
0
28,798
145
Lucky Subsequence
[ "combinatorics", "dp", "math" ]
null
null
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has sequence *a* consisting of *n* integers. The subsequence of the sequence *a* is such subsequence that can be obtained from *a* by removing zero or more of its elements. Two sequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, any sequence of length *n* has exactly 2*n* different subsequences (including an empty subsequence). A subsequence is considered lucky if it has a length exactly *k* and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times). Help Petya find the number of different lucky subsequences of the sequence *a*. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109<=+<=7).
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=105). The next line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the sequence *a*.
On the single line print the single number — the answer to the problem modulo prime number 1000000007 (109<=+<=7).
[ "3 2\n10 10 10\n", "4 2\n4 4 7 7\n" ]
[ "3\n", "4\n" ]
In the first sample all 3 subsequences of the needed length are considered lucky. In the second sample there are 4 lucky subsequences. For them the sets of indexes equal (the indexation starts from 1): {1, 3}, {1, 4}, {2, 3} and {2, 4}.
[ { "input": "3 2\n10 10 10", "output": "3" }, { "input": "4 2\n4 4 7 7", "output": "4" }, { "input": "7 4\n1 2 3 4 5 6 7", "output": "35" }, { "input": "7 4\n7 7 7 7 7 7 7", "output": "0" }, { "input": "10 1\n1 2 3 4 5 6 7 8 9 10", "output": "10" }, { "...
466
19,558,400
3
28,814
0
none
[ "none" ]
null
null
Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least *p* experience points, and a desired flat in Moscow costs *q* dollars. Mikhail is determined to follow his dreams and registered at a freelance site. He has suggestions to work on *n* distinct projects. Mikhail has already evaluated that the participation in the *i*-th project will increase his experience by *a**i* per day and bring *b**i* dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time. Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true. For example, suppose Mikhail is suggested to work on three projects and *a*1<==<=6, *b*1<==<=2, *a*2<==<=1, *b*2<==<=3, *a*3<==<=2, *b*3<==<=6. Also, *p*<==<=20 and *q*<==<=20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, *a*1·2.5<=+<=*a*2·0<=+<=*a*3·2.5<==<=6·2.5<=+<=1·0<=+<=2·2.5<==<=20 and *b*1·2.5<=+<=*b*2·0<=+<=*b*3·2.5<==<=2·2.5<=+<=3·0<=+<=6·2.5<==<=20.
The first line of the input contains three integers *n*, *p* and *q* (1<=≤<=*n*<=≤<=100<=000,<=1<=≤<=*p*,<=*q*<=≤<=1<=000<=000) — the number of projects and the required number of experience and money. Each of the next *n* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=1<=000<=000) — the daily increase in experience and daily income for working on the *i*-th project.
Print a real value — the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6. Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if .
[ "3 20 20\n6 2\n1 3\n2 6\n", "4 1 1\n2 3\n3 2\n2 3\n3 2\n" ]
[ "5.000000000000000\n", "0.400000000000000\n" ]
First sample corresponds to the example in the problem statement.
[ { "input": "3 20 20\n6 2\n1 3\n2 6", "output": "5.000000000000000" }, { "input": "4 1 1\n2 3\n3 2\n2 3\n3 2", "output": "0.400000000000000" }, { "input": "3 12 12\n5 1\n2 2\n1 5", "output": "4.000000000000000" }, { "input": "3 12 12\n5 1\n4 4\n1 5", "output": "3.000000000...
109
0
0
28,843
662
Gambling Nim
[ "bitmasks", "math", "matrices", "probabilities" ]
null
null
As you know, the game of "Nim" is played with *n* piles of stones, where the *i*-th pile initially contains *a**i* stones. Two players alternate the turns. During a turn a player picks any non-empty pile and removes any positive number of stones from it. The one who is not able to make a move loses the game. Petya and Vasya are tired of playing Nim, so they invented their own version of the game and named it the "Gambling Nim". They have *n* two-sided cards, one side of the *i*-th card has number *a**i* written on it, while the other side has number *b**i*. At the beginning of the game the players put all the cards on the table, each card only one of its sides up, and this side is chosen independently and uniformly. Thus they obtain a sequence *c*1,<=*c*2,<=...,<=*c**n*, where *c**i* is equal to *a**i* or *b**i*. Then they take *n* piles of stones, with *i*-th pile containing exactly *c**i* stones and play Nim. Petya takes the first turn. Given that both players play optimally, find the probability of Petya's victory. Output the answer as an irreducible fraction.
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=500<=000) — the number of cards in the deck. Each of the following *n* lines contains the description of one card, consisting of two integers *a**i* and *b**i* (0<=≤<=*a**i*,<=*b**i*<=≤<=1018).
Output the answer as an irreducible fraction *p*<=/<=*q*. If the probability of Petya's victory is 0, print 0/1.
[ "2\n1 1\n1 1\n", "2\n1 2\n1 2\n", "3\n0 4\n1 5\n2 3\n" ]
[ "0/1\n", "1/2\n", "1/1\n" ]
none
[ { "input": "2\n1 1\n1 1", "output": "0/1" }, { "input": "2\n1 2\n1 2", "output": "1/2" }, { "input": "3\n0 4\n1 5\n2 3", "output": "1/1" }, { "input": "1\n0 0", "output": "0/1" }, { "input": "1\n8 10", "output": "1/1" }, { "input": "3\n0 0\n0 0\n0 0", ...
2,000
6,246,400
0
28,851
852
Property
[ "greedy", "sortings" ]
null
null
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property. Bill’s property can be observed as a convex regular 2*n*-sided polygon *A*0 *A*1... *A*2*n*<=-<=1 *A*2*n*,<= *A*2*n*<==<= *A*0, with sides of the exactly 1 meter in length. Court rules for removing part of his property are as follows: - Split every edge *A**k* *A**k*<=+<=1,<= *k*<==<=0... 2*n*<=-<=1 in *n* equal parts of size 1<=/<=*n* with points *P*0,<=*P*1,<=...,<=*P**n*<=-<=1 - On every edge *A*2*k* *A*2*k*<=+<=1,<= *k*<==<=0... *n*<=-<=1 court will choose one point *B*2*k*<==<= *P**i* for some *i*<==<=0,<=...,<= *n*<=-<=1 such that - On every edge *A*2*k*<=+<=1*A*2*k*<=+<=2,<= *k*<==<=0...*n*<=-<=1 Bill will choose one point *B*2*k*<=+<=1<==<= *P**i* for some *i*<==<=0,<=...,<= *n*<=-<=1 such that - Bill gets to keep property inside of 2*n*-sided polygon *B*0 *B*1... *B*2*n*<=-<=1 Luckily, Bill found out which *B*2*k* points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
The first line contains one integer number *n* (2<=≤<=*n*<=≤<=50000), representing number of edges of 2*n*-sided polygon. The second line contains *n* distinct integer numbers *B*2*k* (0<=≤<=*B*2*k*<=≤<=*n*<=-<=1,<= *k*<==<=0... *n*<=-<=1) separated by a single space, representing points the court chose. If *B*2*k*<==<=*i*, the court chose point *P**i* on side *A*2*k* *A*2*k*<=+<=1.
Output contains *n* distinct integers separated by a single space representing points *B*1,<=*B*3,<=...,<=*B*2*n*<=-<=1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.
[ "3\n0 1 2\n" ]
[ "0 2 1\n" ]
To maximize area Bill should choose points: *B*<sub class="lower-index">1</sub> = *P*<sub class="lower-index">0</sub>, *B*<sub class="lower-index">3</sub> = *P*<sub class="lower-index">2</sub>, *B*<sub class="lower-index">5</sub> = *P*<sub class="lower-index">1</sub> <img class="tex-graphics" src="https://espresso.codeforces.com/03c7bbc496053c0ca19cfcf073d88965c4c90895.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "3\n0 1 2", "output": "0 2 1" }, { "input": "10\n0 1 2 3 4 5 6 7 8 9", "output": "0 1 2 3 5 6 7 8 9 4" }, { "input": "10\n1 7 3 6 8 2 4 5 0 9", "output": "2 6 5 9 7 1 4 0 3 8" }, { "input": "10\n4 9 7 2 3 5 6 1 8 0", "output": "8 9 6 1 4 7 2 5 3 0" }, { ...
46
0
0
28,887
774
Perfectionist Arkadiy
[ "*special", "number theory" ]
null
null
Arkadiy has lots square photos with size *a*<=×<=*a*. He wants to put some of them on a rectangular wall with size *h*<=×<=*w*. The photos which Arkadiy will put on the wall must form a rectangular grid and the distances between neighboring vertically and horizontally photos and also the distances between outside rows and columns of photos to the nearest bound of the wall must be equal to *x*, where *x* is some non-negative real number. Look on the picture below for better understanding of the statement. Arkadiy haven't chosen yet how many photos he would put on the wall, however, he want to put at least one photo. Your task is to determine the minimum value of *x* which can be obtained after putting photos, or report that there is no way to put positive number of photos and satisfy all the constraints. Suppose that Arkadiy has enough photos to make any valid arrangement according to the constraints. Note that Arkadiy wants to put at least one photo on the wall. The photos should not overlap, should completely lie inside the wall bounds and should have sides parallel to the wall sides.
The first line contains three integers *a*, *h* and *w* (1<=≤<=*a*,<=*h*,<=*w*<=≤<=109) — the size of photos and the height and the width of the wall.
Print one non-negative real number — the minimum value of *x* which can be obtained after putting the photos on the wall. The absolute or the relative error of the answer must not exceed 10<=-<=6. Print -1 if there is no way to put positive number of photos and satisfy the constraints.
[ "2 18 13\n", "4 4 4\n", "3 4 3\n" ]
[ "0.5\n", "0\n", "-1\n" ]
In the first example Arkadiy can put 7 rows of photos with 5 photos in each row, so the minimum value of *x* equals to 0.5. In the second example Arkadiy can put only 1 photo which will take the whole wall, so the minimum value of *x* equals to 0. In the third example there is no way to put positive number of photos and satisfy the constraints described in the statement, so the answer is -1.
[ { "input": "2 18 13", "output": "0.50000000000000000000" }, { "input": "4 4 4", "output": "0.00000000000000000000" }, { "input": "3 4 3", "output": "-1" }, { "input": "9 81 23", "output": "-1" }, { "input": "11 21 21", "output": "5.00000000000000000000" }, ...
0
0
-1
28,902
818
Card Game Again
[ "binary search", "data structures", "number theory", "two pointers" ]
null
null
Vova again tries to play some computer card game. The rules of deck creation in this game are simple. Vova is given an existing deck of *n* cards and a magic number *k*. The order of the cards in the deck is fixed. Each card has a number written on it; number *a**i* is written on the *i*-th card in the deck. After receiving the deck and the magic number, Vova removes *x* (possibly *x*<==<=0) cards from the top of the deck, *y* (possibly *y*<==<=0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards *x*<=+<=1, *x*<=+<=2, ... *n*<=-<=*y*<=-<=1, *n*<=-<=*y* from the original deck. Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by *k*. So Vova received a deck (possibly not a valid one) and a number *k*, and now he wonders, how many ways are there to choose *x* and *y* so the deck he will get after removing *x* cards from the top and *y* cards from the bottom is valid?
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*k*<=≤<=109). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=109) — the numbers written on the cards.
Print the number of ways to choose *x* and *y* so the resulting deck is valid.
[ "3 4\n6 2 8\n", "3 6\n9 1 14\n" ]
[ "4\n", "1\n" ]
In the first example the possible values of *x* and *y* are: 1. *x* = 0, *y* = 0; 1. *x* = 1, *y* = 0; 1. *x* = 2, *y* = 0; 1. *x* = 0, *y* = 1.
[ { "input": "3 4\n6 2 8", "output": "4" }, { "input": "3 6\n9 1 14", "output": "1" }, { "input": "5 1\n1 3 1 3 1", "output": "15" }, { "input": "5 1\n5 5 5 5 5", "output": "15" }, { "input": "5 1\n5 4 4 4 4", "output": "15" }, { "input": "100 1\n1 1 1 1...
124
0
0
28,910
566
Restructuring Company
[ "data structures", "dsu" ]
null
null
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company. There are *n* people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of *n* departments, one person in each). However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use *team*(*person*) to represent a team where person *person* works. A crisis manager can make decisions of two types: 1. Merge departments *team*(*x*) and *team*(*y*) into one large department containing all the employees of *team*(*x*) and *team*(*y*), where *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*) — are numbers of two of some company employees. If *team*(*x*) matches *team*(*y*), then nothing happens. 1. Merge departments *team*(*x*),<=*team*(*x*<=+<=1),<=...,<=*team*(*y*), where *x* and *y* (1<=≤<=*x*<=≤<=*y*<=≤<=*n*) — the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*) work at the same department. Help the crisis manager and answer all of his queries.
The first line of the input contains two integers *n* and *q* (1<=≤<=*n*<=≤<=200<=000, 1<=≤<=*q*<=≤<=500<=000) — the number of the employees of the company and the number of queries the crisis manager has. Next *q* lines contain the queries of the crisis manager. Each query looks like *type* *x* *y*, where . If *type*<==<=1 or *type*<==<=2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If *type*<==<=3, then your task is to determine whether employees *x* and *y* work at the same department. Note that *x* can be equal to *y* in the query of any type.
For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.
[ "8 6\n3 2 5\n1 2 5\n3 2 5\n2 4 7\n2 1 2\n3 1 7\n" ]
[ "NO\nYES\nYES\n" ]
none
[ { "input": "8 6\n3 2 5\n1 2 5\n3 2 5\n2 4 7\n2 1 2\n3 1 7", "output": "NO\nYES\nYES" }, { "input": "1 1\n3 1 1", "output": "YES" }, { "input": "1 3\n1 1 1\n2 1 1\n3 1 1", "output": "YES" } ]
30
0
-1
28,914
696
Legen...
[ "data structures", "dp", "matrices", "strings" ]
null
null
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible. Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows *n* pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees *i*-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by *a**i*. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab. Due to texting app limits, Barney's text may have up to *l* characters. Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
The first line of input contains two integers *n* and *l* (1<=≤<=*n*<=≤<=200,<=1<=≤<=*l*<=≤<=1014) — the number of pickup lines and the maximum length of Barney's text. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100), meaning that Nora's happiness level increases by *a**i* after every time seeing *i*-th pickup line. The next *n* lines contain the pickup lines. *i*-th of them contains a single string *s**i* consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200. All strings are not empty.
Print the only integer — the maximum possible value of Nora's happiness level after reading Barney's text.
[ "3 6\n3 2 1\nheart\nearth\nart\n", "3 6\n3 2 8\nheart\nearth\nart\n" ]
[ "6\n", "16\n" ]
An optimal answer for the first sample case is hearth containing each pickup line exactly once. An optimal answer for the second sample case is artart.
[]
108
307,200
0
28,934
617
Watering Flowers
[ "implementation" ]
null
null
A flowerbed has many flowers and two fountains. You can adjust the water pressure and set any values *r*1(*r*1<=≥<=0) and *r*2(*r*2<=≥<=0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such *r*1 and *r*2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed *r*1, or the distance to the second fountain doesn't exceed *r*2. 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 *r*1 and *r*2 that all the flowers are watered and the *r*12<=+<=*r*22 is minimum possible. Find this minimum value.
The first line of the input contains integers *n*, *x*1, *y*1, *x*2, *y*2 (1<=≤<=*n*<=≤<=2000, <=-<=107<=≤<=*x*1,<=*y*1,<=*x*2,<=*y*2<=≤<=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 *x**i* and *y**i* (<=-<=107<=≤<=*x**i*,<=*y**i*<=≤<=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 *r*12<=+<=*r*22. Note, that in this problem optimal answer is always integer.
[ "2 -1 0 5 3\n0 2\n5 2\n", "4 0 0 5 0\n9 4\n8 3\n-1 0\n1 4\n" ]
[ "6\n", "33\n" ]
The first sample is (*r*<sub class="lower-index">1</sub><sup class="upper-index">2</sup> = 5, *r*<sub class="lower-index">2</sub><sup class="upper-index">2</sup> = 1): <img class="tex-graphics" src="https://espresso.codeforces.com/15e780f508832a19b14698dd8eb54b4c0dd131bf.png" style="max-width: 100.0%;max-height: 100.0%;"/> The second sample is (*r*<sub class="lower-index">1</sub><sup class="upper-index">2</sup> = 1, *r*<sub class="lower-index">2</sub><sup class="upper-index">2</sup> = 32): <img class="tex-graphics" src="https://espresso.codeforces.com/da4dc31002cc9b37092d64035ab56ad8544c0d7b.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "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" }, { "input": "5 -6 -4 0 10\n-7 6\n-9 7\n-5 -1\n-2 1\n-8 10", "output": "100" }, { "input": "10 -68 10 87 22\n30 89\n82 -97\n-52 25\n76 -22\n-20 95\n21 25\n2 -3\n45...
155
3,686,400
0
28,985
723
One-Way Reform
[ "constructive algorithms", "dfs and similar", "flows", "graphs", "greedy" ]
null
null
There are *n* cities and *m* two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads. The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to maximize the number of cities, for which the number of roads that begins in the city equals to the number of roads that ends in it.
The first line contains a positive integer *t* (1<=≤<=*t*<=≤<=200) — the number of testsets in the input. Each of the testsets is given in the following way. The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=200, 0<=≤<=*m*<=≤<=*n*·(*n*<=-<=1)<=/<=2) — the number of cities and the number of roads in Berland. The next *m* lines contain the description of roads in Berland. Each line contains two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*) — the cities the corresponding road connects. It's guaranteed that there are no self-loops and multiple roads. It is possible that there is no way along roads between a pair of cities. It is guaranteed that the total number of cities in all testset of input data doesn't exceed 200. Pay attention that for hacks, you can only use tests consisting of one testset, so *t* should be equal to one.
For each testset print the maximum number of such cities that the number of roads that begins in the city, is equal to the number of roads that ends in it. In the next *m* lines print oriented roads. First print the number of the city where the road begins and then the number of the city where the road ends. If there are several answers, print any of them. It is allowed to print roads in each test in arbitrary order. Each road should be printed exactly once.
[ "2\n5 5\n2 1\n4 5\n2 3\n1 3\n3 5\n7 2\n3 7\n4 2\n" ]
[ "3\n1 3\n3 5\n5 4\n3 2\n2 1\n3\n2 4\n3 7\n" ]
none
[ { "input": "2\n5 5\n2 1\n4 5\n2 3\n1 3\n3 5\n7 2\n3 7\n4 2", "output": "3\n1 3\n3 5\n5 4\n3 2\n2 1\n3\n2 4\n3 7" }, { "input": "4\n9 17\n3 6\n2 6\n6 9\n4 1\n2 8\n1 9\n7 9\n8 5\n1 7\n4 9\n6 7\n3 4\n9 3\n8 4\n2 1\n3 8\n2 7\n5 6\n2 5\n3 4\n1 3\n4 5\n5 3\n2 3\n12 8\n10 2\n9 2\n6 9\n10 6\n8 2\n4 10\n11 2...
15
0
0
29,125
886
Maximum Element
[ "combinatorics", "dp", "math" ]
null
null
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of *n* positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter *k*, so now his function contains the following code: That way the function iteratively checks array elements, storing the intermediate maximum, and if after *k* consecutive iterations that maximum has not changed, it is returned as the answer. Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to *n* such that the return value of his function on those permutations is not equal to *n*. Since this number could be very big, output the answer modulo 109<=+<=7.
The only line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=106), separated by a space — the length of the permutations and the parameter *k*.
Output the answer to the problem modulo 109<=+<=7.
[ "5 2\n", "5 3\n", "6 3\n" ]
[ "22\n", "6\n", "84\n" ]
Permutations from second example: [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5].
[ { "input": "5 2", "output": "22" }, { "input": "5 3", "output": "6" }, { "input": "6 3", "output": "84" }, { "input": "5 10", "output": "0" }, { "input": "1 1", "output": "0" }, { "input": "2 1", "output": "0" }, { "input": "2 2", "outp...
0
0
-1
29,139
573
Bear and Bowling
[ "data structures", "greedy" ]
null
null
Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record! For rolling a ball one gets a score — an integer (maybe negative) number of points. Score for *i*-th roll is multiplied by *i* and scores are summed up. So, for *k* rolls with scores *s*1,<=*s*2,<=...,<=*s**k*, total score is . Total score is 0 if there were no rolls. Limak made *n* rolls and got score *a**i* for *i*-th of them. He wants to maximize his total score and he came up with an interesting idea. He will cancel some rolls, saying that something distracted him or there was a strong wind. Limak is able to cancel any number of rolls, maybe even all or none of them. Total score is calculated as if there were only non-canceled rolls. Look at the sample tests for clarification. What maximum total score can Limak get?
The first line contains single integer *n* (1<=≤<=*n*<=≤<=105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=≤<=107) - scores for Limak's rolls.
Print the maximum possible total score after choosing rolls to cancel.
[ "5\n-2 -8 0 5 -3\n", "6\n-10 20 -30 40 -50 60\n" ]
[ "13\n", "400\n" ]
In first sample Limak should cancel rolls with scores  - 8 and  - 3. Then he is left with three rolls with scores  - 2, 0, 5. Total score is 1·( - 2) + 2·0 + 3·5 = 13. In second sample Limak should cancel roll with score  - 50. Total score is 1·( - 10) + 2·20 + 3·( - 30) + 4·40 + 5·60 = 400.
[]
30
0
0
29,179
736
Permutations
[ "math", "matrices" ]
null
null
Ostap Bender is worried that people started to forget that he is the Great Combinator. Now he wants to show them his skills in combinatorics. Now he studies the permutations of length *n*. He has a list of *m* valid pairs, pair *a**i* and *b**i* means that he is allowed to place integers *b**i* at position *a**i*. He knows that the number of permutations that use only valid pairs is odd. Now, for each pair he wants to find out, will the number of valid permutations be odd if he removes this pair (and only it) from the list.
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=2000, *n*<=≤<=*m*<=≤<=*min*(*n*2,<=500<=000)) — the number of elements in the permutation. Then follow *m* lines, each containing some valid pair (*a**i*,<=*b**i*) (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*). It's guaranteed that no pair occurs in the input twice and that the total number of valid permutations (i.e. using only allowed pairs position-elements) is odd.
Print *m* lines, one line for each valid pair. The *i*-th line should contain "YES" if after Ostap removes the *i*-th pair (and only it) the remaining number of valid permutations is odd. Otherwise, print «NO».
[ "2 3\n1 1\n1 2\n2 2\n", "3 3\n1 1\n2 2\n3 3\n", "3 7\n3 3\n3 1\n1 3\n1 1\n2 2\n1 2\n2 1\n" ]
[ "NO\nYES\nNO\n", "NO\nNO\nNO\n", "YES\nNO\nNO\nNO\nYES\nNO\nNO\n" ]
none
[]
2,000
39,219,200
0
29,182
180
Defragmentation
[ "implementation" ]
null
null
In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to *n*. The disk has *m* recorded files, the *i*-th file occupies clusters with numbers *a**i*,<=1, *a**i*,<=2, ..., *a**i*,<=*n**i*. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster *a**i*,<=1 contains the first fragment of the *i*-th file, cluster *a**i*,<=2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files. You are permitted to perform operations of copying the contents of cluster number *i* to cluster number *j* (*i* and *j* must be different). Moreover, if the cluster number *j* used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files). Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes. Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2*n*.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=200) — the number of clusters and the number of files, correspondingly. Next *m* lines contain descriptions of the files. The first number in the line is *n**i* (*n**i*<=≥<=1), the number of clusters occupied by the *i*-th file. Then follow *n**i* numbers *a**i*,<=1, *a**i*,<=2, ..., *a**i*,<=*n**i* (1<=≤<=*a**i*,<=*j*<=≤<=*n*). It is guaranteed that each cluster number occurs not more than once and , that is, there exists at least one unused cluster. Numbers on each line are separated by spaces.
In the first line print a single integer *k* (0<=≤<=*k*<=≤<=2*n*) — the number of operations needed to defragment the disk. Next *k* lines should contain the operations' descriptions as "*i* *j*" (copy the contents of the cluster number *i* to the cluster number *j*).
[ "7 2\n2 1 2\n3 3 4 5\n", "7 2\n2 1 3\n3 2 4 5\n" ]
[ "0\n", "3\n2 6\n3 2\n6 3\n" ]
Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. Example 2: each file must occupy a contiguous area of memory. Example 3: the order of files to each other is not important, at first the second file can be written, and then — the first one. Example 4: violating the order of file fragments to each other is not allowed. Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8.
[ { "input": "7 2\n2 1 2\n3 3 4 5", "output": "0" }, { "input": "7 2\n2 1 3\n3 2 4 5", "output": "3\n2 6\n3 2\n6 3" }, { "input": "2 1\n1 2", "output": "1\n2 1" }, { "input": "3 1\n2 3 1", "output": "2\n1 2\n3 1" }, { "input": "3 2\n1 3\n1 2", "output": "1\n3 1"...
124
0
0
29,227
0
none
[ "none" ]
null
null
A famous sculptor Cicasso goes to a world tour! Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country — Berland. Cicasso is very devoted to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has "favourites". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help. There are *n* cities and *m* one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities — will be the largest. Note that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: . Four cities in the order of visiting marked as overlines: [1,<=5,<=2,<=4]. Note that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do.
In the first line there is a pair of integers *n* and *m* (4<=≤<=*n*<=≤<=3000,<=3<=≤<=*m*<=≤<=5000) — a number of cities and one-way roads in Berland. Each of the next *m* lines contains a pair of integers *u**i*,<=*v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*) — a one-way road from the city *u**i* to the city *v**i*. Note that *u**i* and *v**i* are not required to be distinct. Moreover, it can be several one-way roads between the same pair of cities.
Print four integers — numbers of cities which Cicasso will visit according to optimal choice of the route. Numbers of cities should be printed in the order that Cicasso will visit them. If there are multiple solutions, print any of them.
[ "8 9\n1 2\n2 3\n3 4\n4 1\n4 5\n5 6\n6 7\n7 8\n8 5\n" ]
[ "2 1 8 7\n" ]
Let *d*(*x*, *y*) be the shortest distance between cities *x* and *y*. Then in the example *d*(2, 1) = 3, *d*(1, 8) = 7, *d*(8, 7) = 3. The total distance equals 13.
[]
30
0
0
29,257
963
Destruction of a Tree
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
null
null
You are given a tree (a graph with *n* vertices and *n*<=-<=1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or determine that it is impossible.
The first line contains integer *n* (1<=≤<=*n*<=≤<=2·105) — number of vertices in a tree. The second line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* (0<=≤<=*p**i*<=≤<=*n*). If *p**i*<=≠<=0 there is an edge between vertices *i* and *p**i*. It is guaranteed that the given graph is a tree.
If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes). If it's possible to destroy all vertices, in the next *n* lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any.
[ "5\n0 1 2 1 2\n", "4\n0 1 2 3\n" ]
[ "YES\n1\n2\n3\n5\n4\n", "NO\n" ]
In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order.
[ { "input": "5\n0 1 2 1 2", "output": "YES\n1\n2\n3\n5\n4" }, { "input": "4\n0 1 2 3", "output": "NO" }, { "input": "1\n0", "output": "YES\n1" }, { "input": "8\n3 1 4 0 4 2 4 5", "output": "NO" }, { "input": "100\n81 96 65 28 4 40 5 49 5 89 48 70 94 70 17 58 58 1 6...
31
6,963,200
0
29,369
599
Day at the Beach
[ "sortings" ]
null
null
One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles. At the end of the day there were *n* castles built by friends. Castles are numbered from 1 to *n*, and the height of the *i*-th castle is equal to *h**i*. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition *h**i*<=≤<=*h**i*<=+<=1 holds for all *i* from 1 to *n*<=-<=1. Squidward suggested the following process of sorting castles: - Castles are split into blocks — groups of consecutive castles. Therefore the block from *i* to *j* will include castles *i*,<=*i*<=+<=1,<=...,<=*j*. A block may consist of a single castle. - The partitioning is chosen in such a way that every castle is a part of exactly one block. - Each block is sorted independently from other blocks, that is the sequence *h**i*,<=*h**i*<=+<=1,<=...,<=*h**j* becomes sorted. - The partitioning should satisfy the condition that after each block is sorted, the sequence *h**i* becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of castles Spongebob, Patrick and Squidward made from sand during the day. The next line contains *n* integers *h**i* (1<=≤<=*h**i*<=≤<=109). The *i*-th of these integers corresponds to the height of the *i*-th castle.
Print the maximum possible number of blocks in a valid partitioning.
[ "3\n1 2 3\n", "4\n2 1 3 2\n" ]
[ "3\n", "2\n" ]
In the first sample the partitioning looks like that: [1][2][3]. In the second sample the partitioning is: [2, 1][3, 2]
[ { "input": "3\n1 2 3", "output": "3" }, { "input": "4\n2 1 3 2", "output": "2" }, { "input": "17\n1 45 22 39 28 23 23 100 500 778 777 778 1001 1002 1005 1003 1005", "output": "10" }, { "input": "101\n1 50 170 148 214 153 132 234 181 188 180 225 226 200 197 122 181 168 87 220 ...
155
16,486,400
3
29,394
873
Forbidden Indices
[ "dsu", "string suffix structures", "strings" ]
null
null
You are given a string *s* consisting of *n* lowercase Latin letters. Some indices in this string are marked as forbidden. You want to find a string *a* such that the value of |*a*|·*f*(*a*) is maximum possible, where *f*(*a*) is the number of occurences of *a* in *s* such that these occurences end in non-forbidden indices. So, for example, if *s* is aaaa, *a* is aa and index 3 is forbidden, then *f*(*a*)<==<=2 because there are three occurences of *a* in *s* (starting in indices 1, 2 and 3), but one of them (starting in index 2) ends in a forbidden index. Calculate the maximum possible value of |*a*|·*f*(*a*) you can get.
The first line contains an integer number *n* (1<=≤<=*n*<=≤<=200000) — the length of *s*. The second line contains a string *s*, consisting of *n* lowercase Latin letters. The third line contains a string *t*, consisting of *n* characters 0 and 1. If *i*-th character in *t* is 1, then *i* is a forbidden index (otherwise *i* is not forbidden).
Print the maximum possible value of |*a*|·*f*(*a*).
[ "5\nababa\n00100\n", "5\nababa\n00000\n", "5\nababa\n11111\n" ]
[ "5\n", "6\n", "0\n" ]
none
[ { "input": "5\nababa\n00100", "output": "5" }, { "input": "5\nababa\n00000", "output": "6" }, { "input": "5\nababa\n11111", "output": "0" }, { "input": "100\neebdeddddbecdbddaaecbbaccbecdeacedddcaddcdebedbabbceeeadecadbbeaecdaeabbceacbdbdbbdacebbbccdcbbeedbe\n1101101101110110...
2,000
250,470,400
0
29,468
360
Levko and Strings
[ "combinatorics", "dp" ]
null
null
Levko loves strings of length *n*, consisting of lowercase English letters, very much. He has one such string *s*. For each string *t* of length *n*, Levko defines its beauty relative to *s* as the number of pairs of indexes *i*, *j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*), such that substring *t*[*i*..*j*] is lexicographically larger than substring *s*[*i*..*j*]. The boy wondered how many strings *t* are there, such that their beauty relative to *s* equals exactly *k*. Help him, find the remainder after division this number by 1000000007 (109<=+<=7). A substring *s*[*i*..*j*] of string *s*<==<=*s*1*s*2... *s**n* is string *s**i**s**i*<=<=+<=<=1... *s**j*. String *x*<=<==<=<=*x*1*x*2... *x**p* is lexicographically larger than string *y*<=<==<=<=*y*1*y*2... *y**p*, if there is such number *r* (*r*<=&lt;<=*p*), that *x*1<=<==<=<=*y*1,<=<=*x*2<=<==<=<=*y*2,<=<=... ,<=<=*x**r*<=<==<=<=*y**r* and *x**r*<=<=+<=<=1<=&gt;<=*y**r*<=<=+<=<=1. The string characters are compared by their ASCII codes.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=2000, 0<=≤<=*k*<=≤<=2000). The second line contains a non-empty string *s* of length *n*. String *s* consists only of lowercase English letters.
Print a single number — the answer to the problem modulo 1000000007 (109<=+<=7).
[ "2 2\nyz\n", "2 3\nyx\n", "4 7\nabcd\n" ]
[ "26\n", "2\n", "21962\n" ]
none
[]
1,000
268,390,400
0
29,539
274
Zero Tree
[ "dfs and similar", "dp", "greedy", "trees" ]
null
null
A tree is a graph with *n* vertices and exactly *n*<=-<=1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree *T* is a tree with both vertices and edges as subsets of vertices and edges of *T*. You're given a tree with *n* vertices. Consider its vertices numbered with integers from 1 to *n*. Additionally an integer is written on every vertex of this tree. Initially the integer written on the *i*-th vertex is equal to *v**i*. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
The first line of the input contains *n* (1<=≤<=*n*<=≤<=105). Each of the next *n*<=-<=1 lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*) indicating there's an edge between vertices *a**i* and *b**i*. It's guaranteed that the input graph is a tree. The last line of the input contains a list of *n* space-separated integers *v*1,<=*v*2,<=...,<=*v**n* (|*v**i*|<=≤<=109).
Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "3\n1 2\n1 3\n1 -1 1\n" ]
[ "3\n" ]
none
[ { "input": "3\n1 2\n1 3\n1 -1 1", "output": "3" }, { "input": "5\n2 3\n4 5\n2 5\n1 3\n0 2 1 4 3", "output": "8" }, { "input": "10\n5 6\n8 2\n9 3\n4 1\n6 10\n9 8\n7 10\n7 4\n5 2\n0 -6 -9 -1 -5 -4 -2 -7 -8 -3", "output": "18" }, { "input": "5\n3 1\n2 4\n3 4\n2 5\n0 -3 -1 2 4", ...
248
22,220,800
-1
29,541
811
Vladik and Favorite Game
[ "constructive algorithms", "dfs and similar", "graphs", "interactive" ]
null
null
This is an interactive problem. Vladik has favorite game, in which he plays all his free time. Game field could be represented as *n*<=×<=*m* matrix which consists of cells of three types: - «.» — normal cell, player can visit it. - «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type. - «*» — dangerous cell, if player comes to this cell, he loses. Initially player is located in the left top cell with coordinates (1,<=1). Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively. But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game. Help Vladik win the game!
First line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — number of rows and columns respectively. Each of next *n* lines contains *m* characters describing corresponding row of field. Set of characters in field is described above. Guaranteed that cell with coordinates (1,<=1) is normal and there is at least one way from initial cell to finish cell without dangerous cells.
none
[ "4 3\n...\n**.\nF*.\n...\n1 1\n1 2\n1 3\n1 3\n2 3\n3 3\n4 3\n4 2\n4 1\n3 1\n" ]
[ "R\nL\nL\nD\nU\nU\nU\nR\nR\nD\n" ]
In first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form: <img class="tex-graphics" src="https://espresso.codeforces.com/d9b78340a3793547cc8ccc2c1c34484f3cfe0453.png" style="max-width: 100.0%;max-height: 100.0%;"/> This test could be presenter for hack in following way:
[]
0
0
-1
29,579
260
Black and White Tree
[ "constructive algorithms", "dsu", "graphs", "greedy", "trees" ]
null
null
The board has got a painted tree graph, consisting of *n* nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles. Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer. A bad boy Vasya came up to the board and wrote number *s**v* near each node *v* — the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board. Your task is to restore the original tree by the node colors and numbers *s**v*.
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=105) — the number of nodes in the tree. Next *n* lines contain pairs of space-separated integers *c**i*, *s**i* (0<=≤<=*c**i*<=≤<=1, 0<=≤<=*s**i*<=≤<=109), where *c**i* stands for the color of the *i*-th vertex (0 is for white, 1 is for black), and *s**i* represents the sum of values of the edges that are incident to the *i*-th vertex of the tree that is painted on the board.
Print the description of *n*<=-<=1 edges of the tree graph. Each description is a group of three integers *v**i*, *u**i*, *w**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*n*, *v**i*<=≠<=*u**i*, 0<=≤<=*w**i*<=≤<=109), where *v**i* and *u**i* — are the numbers of the nodes that are connected by the *i*-th edge, and *w**i* is its value. Note that the following condition must fulfill *c**v**i*<=≠<=*c**u**i*. It is guaranteed that for any input data there exists at least one graph that meets these data. If there are multiple solutions, print any of them. You are allowed to print the edges in any order. As you print the numbers, separate them with spaces.
[ "3\n1 3\n1 2\n0 5\n", "6\n1 0\n0 3\n1 8\n0 2\n0 3\n0 0\n" ]
[ "3 1 3\n3 2 2\n", "2 3 3\n5 3 3\n4 3 2\n1 6 0\n2 1 0\n" ]
none
[ { "input": "3\n1 3\n1 2\n0 5", "output": "3 1 3\n3 2 2" }, { "input": "6\n1 0\n0 3\n1 8\n0 2\n0 3\n0 0", "output": "2 3 3\n5 3 3\n4 3 2\n1 6 0\n2 1 0" }, { "input": "2\n0 0\n1 0", "output": "1 2 0" }, { "input": "5\n1 11\n0 9\n1 4\n0 4\n0 2", "output": "2 1 9\n4 3 4\n5 1 ...
77
307,200
0
29,620
0
none
[ "none" ]
null
null
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). Ivan has beads of *n* colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.
The first line of the input contains a single number *n* (1<=≤<=*n*<=≤<=26) — the number of colors of beads. The second line contains after *n* positive integers *a**i*   — the quantity of beads of *i*-th color. It is guaranteed that the sum of *a**i* is at least 2 and does not exceed 100<=000.
In the first line print a single number — the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace. Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.
[ "3\n4 2 1\n", "1\n4\n", "2\n1 1\n" ]
[ "1\nabacaba", "4\naaaa\n", "0\nab\n" ]
In the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture. In the second sample there is only one way to compose a necklace.
[ { "input": "3\n4 2 1", "output": "1\naabcbaa" }, { "input": "1\n4", "output": "4\naaaa" }, { "input": "2\n1 1", "output": "0\nab" }, { "input": "1\n2", "output": "2\naa" }, { "input": "1\n3", "output": "3\naaa" }, { "input": "1\n5", "output": "5\na...
30
0
0
29,628
362
Petya and Pipes
[ "flows", "graphs", "shortest paths" ]
null
null
A little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in. The Berland capital has *n* water tanks numbered from 1 to *n*. These tanks are connected by unidirectional pipes in some manner. Any pair of water tanks is connected by at most one pipe in each direction. Each pipe has a strictly positive integer width. Width determines the number of liters of water per a unit of time this pipe can transport. The water goes to the city from the main water tank (its number is 1). The water must go through some pipe path and get to the sewer tank with cleaning system (its number is *n*). Petya wants to increase the width of some subset of pipes by at most *k* units in total so that the width of each pipe remains integer. Help him determine the maximum amount of water that can be transmitted per a unit of time from the main tank to the sewer tank after such operation is completed.
The first line contains two space-separated integers *n* and *k* (2<=≤<=*n*<=≤<=50, 0<=≤<=*k*<=≤<=1000). Then follow *n* lines, each line contains *n* integers separated by single spaces. The *i*<=+<=1-th row and *j*-th column contain number *c**ij* — the width of the pipe that goes from tank *i* to tank *j* (0<=≤<=*c**ij*<=≤<=106,<=*c**ii*<==<=0). If *c**ij*<==<=0, then there is no pipe from tank *i* to tank *j*.
Print a single integer — the maximum amount of water that can be transmitted from the main tank to the sewer tank per a unit of time.
[ "5 7\n0 1 0 2 0\n0 0 4 10 0\n0 0 0 0 5\n0 0 0 0 10\n0 0 0 0 0\n", "5 10\n0 1 0 0 0\n0 0 2 0 0\n0 0 0 3 0\n0 0 0 0 4\n100 0 0 0 0\n" ]
[ "10\n", "5\n" ]
In the first test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 7 units. In the second test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 4 units, from the 2nd to the 3rd water tank by 3 units, from the 3rd to the 4th water tank by 2 units and from the 4th to 5th water tank by 1 unit.
[]
46
0
0
29,671
796
Bank Hacking
[ "constructive algorithms", "data structures", "dp", "trees" ]
null
null
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are *n* banks, numbered from 1 to *n*. There are also *n*<=-<=1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank *i* has initial strength *a**i*. Let us define some keywords before we proceed. Bank *i* and bank *j* are neighboring if and only if there exists a wire directly connecting them. Bank *i* and bank *j* are semi-neighboring if and only if there exists an online bank *k* such that bank *i* and bank *k* are neighboring and bank *k* and bank *j* are neighboring. When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1. To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank *x* if and only if all these conditions are met: 1. Bank *x* is online. That is, bank *x* is not hacked yet. 1. Bank *x* is neighboring to some offline bank. 1. The strength of bank *x* is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.
The first line contains one integer *n* (1<=≤<=*n*<=≤<=3·105) — the total number of banks. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109) — the strengths of the banks. Each of the next *n*<=-<=1 lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*) — meaning that there is a wire directly connecting banks *u**i* and *v**i*. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
[ "5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5\n", "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6\n", "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4\n" ]
[ "5", "93", "8" ]
In the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: - Initially, strengths of the banks are [1, 2, 3, 4, 5]. - He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ]. - He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ]. - He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ]. - He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ]. - He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
[ { "input": "5\n1 2 3 4 5\n1 2\n2 3\n3 4\n4 5", "output": "5" }, { "input": "7\n38 -29 87 93 39 28 -55\n1 2\n2 5\n3 2\n2 4\n1 7\n7 6", "output": "93" }, { "input": "5\n1 2 7 6 7\n1 5\n5 3\n3 4\n2 4", "output": "8" }, { "input": "3\n2 2 2\n3 2\n1 2", "output": "3" }, { ...
2,000
48,230,400
0
29,809
623
Array GCD
[ "dp", "greedy", "number theory" ]
null
null
You are given array *a**i* of length *n*. You may consecutively apply two operations to this array: - remove some subsegment (continuous subsequence) of length *m*<=&lt;<=*n* and pay for it *m*·*a* coins; - change some elements of the array by at most 1, and pay *b* coins for each change. Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array. Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.
The first line of the input contains integers *n*, *a* and *b* (1<=≤<=*n*<=≤<=1<=000<=000,<=0<=≤<=*a*,<=*b*<=≤<=109) — the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively. The second line contains *n* integers *a**i* (2<=≤<=*a**i*<=≤<=109) — elements of the array.
Print a single number — the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.
[ "3 1 4\n4 2 3\n", "5 3 2\n5 17 13 5 6\n", "8 3 4\n3 7 5 4 3 12 9 4\n" ]
[ "1\n", "8\n", "13\n" ]
In the first sample the optimal way is to remove number 3 and pay 1 coin for it. In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2·3 + 2 = 8 coins.
[]
62
1,331,200
0
29,821
700
Connecting Universities
[ "dfs and similar", "dp", "graphs", "trees" ]
null
null
Treeland is a country in which there are *n* towns connected by *n*<=-<=1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2*k* universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in *k* pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1.
The first line of the input contains two integers *n* and *k* (2<=≤<=*n*<=≤<=200<=000, 1<=≤<=*k*<=≤<=*n*<=/<=2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to *n*. The second line contains 2*k* distinct integers *u*1,<=*u*2,<=...,<=*u*2*k* (1<=≤<=*u**i*<=≤<=*n*) — indices of towns in which universities are located. The next *n*<=-<=1 line contains the description of roads. Each line contains the pair of integers *x**j* and *y**j* (1<=≤<=*x**j*,<=*y**j*<=≤<=*n*), which means that the *j*-th road connects towns *x**j* and *y**j*. All of them are two-way roads. You can move from any town to any other using only these roads.
Print the maximum possible sum of distances in the division of universities into *k* pairs.
[ "7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6\n", "9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8\n" ]
[ "6\n", "9\n" ]
The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example.
[ { "input": "7 2\n1 5 6 2\n1 3\n3 2\n4 5\n3 7\n4 3\n4 6", "output": "6" }, { "input": "9 3\n3 2 1 6 5 9\n8 9\n3 2\n2 7\n3 4\n7 6\n4 5\n2 1\n2 8", "output": "9" }, { "input": "41 3\n11 10 15 35 34 6\n28 2\n25 3\n9 4\n11 5\n7 6\n24 7\n19 8\n1 9\n34 10\n23 11\n17 12\n32 13\n32 14\n32 15\n33 ...
1,357
32,870,400
3
30,051
0
none
[ "none" ]
null
null
This is an interactive problem. Bob lives in a square grid of size $n \times n$, with rows numbered $1$ through $n$ from top to bottom, and columns numbered $1$ through $n$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $n$. Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed. You can ask at most $4 \cdot n$ queries of form "? $r_1$ $c_1$ $r_2$ $c_2$" ($1 \le r_1 \le r_2 \le n$, $1 \le c_1 \le c_2 \le n$). The answer will be "YES" if Bob can get from a cell $(r_1, c_1)$ to a cell $(r_2, c_2)$, and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $n - 1$, i.e. the following condition must be satisfied: $(r_2 - r_1) + (c_2 - c_1) \ge n - 1$. It's guaranteed that Bob can get from the top-left corner $(1, 1)$ to the bottom-right corner $(n, n)$ and your task is to find a way to do it. You should print the answer in form "! S" where $S$ is a string of length $2 \cdot n - 2$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $1$, the right move increases the second coordinate by $1$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.
The only line of the input contains an integer $n$ ($2 \le n \le 500$) — the size of the grid.
When you are ready to print the answer, print a single line containing "! S" where where $S$ is a string of length $2 \cdot n - 2$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell $(1, 1)$ to the cell $(n, n)$ passing only through allowed cells.
[ "4\n \nYES\n \nNO\n \nYES\n \nYES\n \n" ]
[ "? 1 1 4 4\n \n? 1 2 4 3\n \n? 4 1 4 4\n \n? 1 4 4 4\n \n! RDRRDD\n" ]
The first example is shown on the picture below. To hack, use the following input format: The first line should contain a single integer $n$ ($2 \le n \le 500$) — the size of the grid. Each of the next $n$ lines should contain a string of $n$ characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell. For example, the following text encodes the example shown above:
[ { "input": "5\n.....\n.###.\n.###.\n.###.\n...#.", "output": "used 8 queries\nRRRRDDDD" }, { "input": "7\n.......\n.......\n.......\n.......\n......#\n.......\n....#..", "output": "used 12 queries\nRRRRRDDDDDRD" }, { "input": "2\n..\n..", "output": "used 2 queries\nRD" }, { "...
109
0
0
30,066
35
Warehouse
[ "implementation" ]
B. Warehouse
2
64
Once upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn’t program or make up problems (in fact, few people saw a computer those days) but he was nevertheless happy. He worked in a warehouse where a magical but non-alcoholic drink Ogudar-Olok was kept. We won’t describe his work in detail and take a better look at a simplified version of the warehouse. The warehouse has one set of shelving. It has *n* shelves, each of which is divided into *m* sections. The shelves are numbered from top to bottom starting from 1 and the sections of each shelf are numbered from left to right also starting from 1. Each section can contain exactly one box of the drink, and try as he might, DravDe can never put a box in a section that already has one. In the course of his work DravDe frequently notices that he has to put a box in a filled section. In that case his solution is simple. DravDe ignores that section and looks at the next one to the right. If it is empty, he puts the box there. Otherwise he keeps looking for the first empty section to the right. If no empty section is found by the end of the shelf, he looks at the shelf which is under it, then the next one, etc. Also each time he looks at a new shelf he starts from the shelf’s beginning. If DravDe still can’t find an empty section for the box, he immediately drinks it all up and throws the empty bottles away not to be caught. After one great party with a lot of Ogudar-Olok drunk DravDe asked you to help him. Unlike him, you can program and therefore modeling the process of counting the boxes in the warehouse will be easy work for you. The process of counting contains two types of query messages: - «+1 x y id» (where *x*, *y* are integers, 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m*, and *id* is a string of lower case Latin letters — from 1 to 10 characters long). That query means that the warehouse got a box identified as *id*, which should be put in the section *y* on the shelf *x*. If the section is full, use the rules described above. It is guaranteed that every moment of the process the identifiers of all the boxes in the warehouse are different. You don’t have to answer this query. - «-1 id» (where *id* is a string of lower case Latin letters — from 1 to 10 characters long). That query means that a box identified as *id* is removed from the warehouse. You have to answer this query (see output format).
The first input line contains integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=30, 1<=≤<=*k*<=≤<=2000) — the height, the width of shelving and the amount of the operations in the warehouse that you need to analyze. In the following *k* lines the queries are given in the order of appearance in the format described above.
For each query of the «-1 id» type output two numbers in a separate line — index of the shelf and index of the section where the box with this identifier lay. If there was no such box in the warehouse when the query was made, output «-1 -1» without quotes.
[ "2 2 9\n+1 1 1 cola\n+1 1 1 fanta\n+1 1 1 sevenup\n+1 1 1 whitekey\n-1 cola\n-1 fanta\n-1 sevenup\n-1 whitekey\n-1 cola\n", "2 2 8\n+1 1 1 cola\n-1 cola\n+1 1 1 fanta\n-1 fanta\n+1 1 1 sevenup\n-1 sevenup\n+1 1 1 whitekey\n-1 whitekey\n" ]
[ "1 1\n1 2\n2 1\n2 2\n-1 -1\n", "1 1\n1 1\n1 1\n1 1\n" ]
none
[ { "input": "2 2 9\n+1 1 1 cola\n+1 1 1 fanta\n+1 1 1 sevenup\n+1 1 1 whitekey\n-1 cola\n-1 fanta\n-1 sevenup\n-1 whitekey\n-1 cola", "output": "1 1\n1 2\n2 1\n2 2\n-1 -1" }, { "input": "2 2 8\n+1 1 1 cola\n-1 cola\n+1 1 1 fanta\n-1 fanta\n+1 1 1 sevenup\n-1 sevenup\n+1 1 1 whitekey\n-1 whitekey", ...
654
102,400
3.835737
30,112
767
Garland
[ "dfs and similar", "graphs", "greedy", "trees" ]
null
null
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps. There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp. Help Dima to find a suitable way to cut the garland, or determine that this is impossible. While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
The first line contains single integer *n* (3<=≤<=*n*<=≤<=106) — the number of lamps in the garland. Then *n* lines follow. The *i*-th of them contain the information about the *i*-th lamp: the number lamp *a**i*, it is hanging on (and 0, if is there is no such lamp), and its temperature *t**i* (<=-<=100<=≤<=*t**i*<=≤<=100). The lamps are numbered from 1 to *n*.
If there is no solution, print -1. Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them.
[ "6\n2 4\n0 5\n4 2\n2 1\n1 1\n4 2\n", "6\n2 4\n0 6\n4 2\n2 1\n1 1\n4 2\n" ]
[ "1 4\n", "-1\n" ]
The garland and cuts scheme for the first example:
[ { "input": "6\n2 4\n0 5\n4 2\n2 1\n1 1\n4 2", "output": "1 4" }, { "input": "6\n2 4\n0 6\n4 2\n2 1\n1 1\n4 2", "output": "-1" }, { "input": "6\n2 4\n0 -1\n4 2\n2 3\n1 2\n4 5", "output": "6 4" }, { "input": "3\n2 1\n0 1\n2 1", "output": "1 3" }, { "input": "5\n0 5\...
77
268,390,400
0
30,134
16
Logging
[ "implementation", "strings" ]
D. Logging
1
64
The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer — Alex — managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format «[time]: message». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written. So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications). We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.
The first input line contains number *n* (1<=≤<=*n*<=≤<=100). The following *n* lines contain recordings in format «[time]: message», where time is given in format «hh:mm x.m.». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character «a» or character «p». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20.
Output one number — the minimum amount of days covered by the log.
[ "5\n[05:00 a.m.]: Server is started\n[05:00 a.m.]: Rescan initialized\n[01:13 p.m.]: Request processed\n[01:10 p.m.]: Request processed\n[11:40 p.m.]: Rescan completed\n", "3\n[09:00 a.m.]: User logged in\n[08:00 a.m.]: User logged in\n[07:00 a.m.]: User logged in\n" ]
[ "2\n", "3\n" ]
Formally the 12-hour time format is described at: - http://en.wikipedia.org/wiki/12-hour_clock.
[ { "input": "5\n[05:00 a.m.]: Server is started\n[05:00 a.m.]: Rescan initialized\n[01:13 p.m.]: Request processed\n[01:10 p.m.]: Request processed\n[11:40 p.m.]: Rescan completed", "output": "2" }, { "input": "3\n[09:00 a.m.]: User logged in\n[08:00 a.m.]: User logged in\n[07:00 a.m.]: User logged i...
0
0
-1
30,139
261
Maxim and Increasing Subsequence
[ "dp" ]
null
null
Maxim loves sequences, especially those that strictly increase. He is wondering, what is the length of the longest increasing subsequence of the given sequence *a*? Sequence *a* is given as follows: - the length of the sequence equals *n*<=×<=*t*; - (1<=≤<=*i*<=≤<=*n*<=×<=*t*), where operation means taking the remainder after dividing number *x* by number *y*. Sequence *s*1,<=<=*s*2,<=<=...,<=<=*s**r* of length *r* is a subsequence of sequence *a*1,<=<=*a*2,<=<=...,<=<=*a**n*, if there is such increasing sequence of indexes *i*1,<=*i*2,<=...,<=*i**r* (1<=<=≤<=<=*i*1<=<=&lt;<=<=*i*2<=<=&lt;<=... <=<=&lt;<=<=*i**r*<=<=≤<=<=*n*), that *a**i**j*<=<==<=<=*s**j*. In other words, the subsequence can be obtained from the sequence by crossing out some elements. Sequence *s*1,<=<=*s*2,<=<=...,<=<=*s**r* is increasing, if the following inequality holds: *s*1<=&lt;<=*s*2<=&lt;<=<=...<=&lt;<=<=*s**r*. Maxim have *k* variants of the sequence *a*. Help Maxim to determine for each sequence the length of the longest increasing subsequence.
The first line contains four integers *k*, *n*, *maxb* and *t* (1<=≤<=*k*<=≤<=10; 1<=≤<=*n*,<=*maxb*<=≤<=105; 1<=≤<=*t*<=≤<=109; *n*<=×<=*maxb*<=≤<=2·107). Each of the next *k* lines contain *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=*maxb*). Note that for each variant of the sequence *a* the values *n*, *maxb* and *t* coincide, the only arrays *b*s differ. The numbers in the lines are separated by single spaces.
Print *k* integers — the answers for the variants of the sequence *a*. Print the answers in the order the variants follow in the input.
[ "3 3 5 2\n3 2 1\n1 2 3\n2 3 1\n" ]
[ "2\n3\n3\n" ]
none
[]
62
0
0
30,141
962
Byteland, Berland and Disputed Cities
[ "constructive algorithms", "greedy" ]
null
null
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 &lt; c &lt; 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.
[ "4\n-5 R\n0 P\n3 P\n7 B\n", "5\n10 R\n14 B\n16 B\n21 R\n32 R\n" ]
[ "12\n", "24\n" ]
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" }, { "input": "10\n66 R\n67 R\n72 R\n73 R\n76 R\n78 B\n79 B\n83 B\n84 B\n85 P", "output": "26" }, { "input": "10\n61 R\n64 R\n68 R\n71 R\n72 R\n73 R\n74 P\n86 P...
93
204,800
0
30,177
413
2048
[ "bitmasks", "dp" ]
null
null
The programmers from the R2 company love playing 2048. One day, they decided to invent their own simplified version of this game — 2*k* on a stripe. Imagine an infinite in one direction stripe, consisting of unit squares (the side of each square is equal to the height of the stripe). Each square can either be empty or contain some number. Initially, all squares are empty. Then at infinity one of the unit squares number 2 or 4 appears. Then the player presses a button once, and the appeared number begins to move towards the beginning of the stripe. Let's assume that some number *x* moves to the beginning of the stripe, then it will stop if: 1. it either gets in the first square of the stripe; 1. or it is in the square that is preceded by a square with number *y* (*y*<=≠<=*x*). But if number *x* at some point of time gets to the square with the same number then both numbers add to each other and result in 2*x*. The new number 2*x* continues moving to the beginning of the stripe by the same rules. After the final stop of the number moving process, the infinity gets a new number 2 or 4 and the process repeats. Read the notes to the test samples to better understand the moving strategy. I guess you've understood that the game progress fully depends on the order in which numbers 2 and 4 appear. Let's look at some sequence of numbers 2 and 4 in the game. We assume that the sequence is winning if it results in at least one square getting the number greater or equal than 2*k*. The goal of the game is to make up a winning sequence of *n* numbers. But not everything is so simple, some numbers in the sequence are identified beforehand. You are given a sequence consisting of numbers 0, 2, 4. Count how many ways there are to replace each 0 of the sequence with 2 or 4 to get a winning sequence.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=2000; 3<=≤<=*k*<=≤<=11). The next line contains sequence of *n* integers, each of them is either 0, or 2, or 4.
Print a single integer — the number of ways to replace zeroes by numbers 2 or 4 to get a winning sequence. As this number can be rather large, print it modulo 1000000007 (109<=+<=7).
[ "7 4\n2 2 4 2 2 2 2\n", "1 3\n0\n", "2 3\n0 4\n", "5 4\n2 0 0 4 4\n" ]
[ "1\n", "0\n", "1\n", "2\n" ]
Consider the first example. The beginning of the strip will look as follows: 2  →  4  →  8  →  8 2  →  8 4  →  8 4 2  →  16. To better understand the game, you can see the original game on http://gabrielecirulli.github.io/2048/. Please note that the game that is described on the strip is slightly different from the original game (when the two numbers add up in the original game, they do not keep moving). Be careful, the game is addictive, there isn't much time for the contest!
[]
46
0
0
30,282
825
Tree Queries
[ "dfs and similar", "graphs", "trees" ]
null
null
You are given a tree consisting of *n* vertices (numbered from 1 to *n*). Initially all vertices are white. You have to process *q* queries of two different types: 1. 1 *x* — change the color of vertex *x* to black. It is guaranteed that the first query will be of this type. 1. 2 *x* — for the vertex *x*, find the minimum index *y* such that the vertex with index *y* belongs to the simple path from *x* to some black vertex (a simple path never visits any vertex more than once). For each query of type 2 print the answer to it. Note that the queries are given in modified way.
The first line contains two numbers *n* and *q* (3<=≤<=*n*,<=*q*<=≤<=106). Then *n*<=-<=1 lines follow, each line containing two numbers *x**i* and *y**i* (1<=≤<=*x**i*<=&lt;<=*y**i*<=≤<=*n*) and representing the edge between vertices *x**i* and *y**i*. It is guaranteed that these edges form a tree. Then *q* lines follow. Each line contains two integers *t**i* and *z**i*, where *t**i* is the type of *i*th query, and *z**i* can be used to restore *x**i* for this query in this way: you have to keep track of the answer to the last query of type 2 (let's call this answer *last*, and initially *last*<==<=0); then *x**i*<==<=(*z**i*<=+<=*last*)<=*mod*<=*n*<=+<=1. It is guaranteed that the first query is of type 1, and there is at least one query of type 2.
For each query of type 2 output the answer to it.
[ "4 6\n1 2\n2 3\n3 4\n1 2\n1 2\n2 2\n1 3\n2 2\n2 2\n" ]
[ "3\n2\n1\n" ]
none
[ { "input": "4 6\n1 2\n2 3\n3 4\n1 2\n1 2\n2 2\n1 3\n2 2\n2 2", "output": "3\n2\n1" }, { "input": "10 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n1 3\n2 10\n1 8\n1 7\n1 6\n1 4\n2 9\n2 7\n1 5\n1 5", "output": "1\n1\n4" }, { "input": "10 10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 1...
1,138
14,643,200
-1
30,300
513
Inversions problem
[ "brute force", "dfs and similar", "dp", "meet-in-the-middle" ]
null
null
You are given a permutation of *n* numbers *p*1,<=*p*2,<=...,<=*p**n*. We perform *k* operations of the following type: choose uniformly at random two indices *l* and *r* (*l*<=≤<=*r*) and reverse the order of the elements *p**l*,<=*p**l*<=+<=1,<=...,<=*p**r*. Your task is to find the expected value of the number of inversions in the resulting permutation.
The first line of input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=109). The next line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* — the given permutation. All *p**i* are different and in range from 1 to *n*. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. - In subproblem G1 (3 points), the constraints 1<=≤<=*n*<=≤<=6, 1<=≤<=*k*<=≤<=4 will hold. - In subproblem G2 (5 points), the constraints 1<=≤<=*n*<=≤<=30, 1<=≤<=*k*<=≤<=200 will hold. - In subproblem G3 (16 points), the constraints 1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=109 will hold.
Output the answer with absolute or relative error no more than 1*e*<=-<=9.
[ "3 1\n1 2 3\n", "3 4\n1 3 2\n" ]
[ "0.833333333333333\n", "1.458333333333334\n" ]
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/eb946338365d9781f7d2e9ec692c26702d0ae3a7.png" style="max-width: 100.0%;max-height: 100.0%;"/>, the interval will consist of a single element and the permutation will not be altered. With probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a063853bdfd761520e06382373fe270b6078994b.png" style="max-width: 100.0%;max-height: 100.0%;"/> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a063853bdfd761520e06382373fe270b6078994b.png" style="max-width: 100.0%;max-height: 100.0%;"/> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/cc9273ddc69be58e22251bdf070c83670617a9a2.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "3 1\n1 2 3", "output": "0.833333333333333" }, { "input": "3 4\n1 3 2", "output": "1.458333333333334" }, { "input": "6 1\n4 2 5 1 3 6", "output": "6.380952380952381" }, { "input": "6 2\n1 4 6 5 2 3", "output": "6.954648526077097" }, { "input": "4 4\n2 3...
561
0
3
30,356
690
Collective Mindsets (medium)
[]
null
null
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)? The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the *N*<=-<=1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive.
The only line of input contains one integer: *N*, the number of attendees (1<=≤<=*N*<=≤<=109).
Output one integer: the smallest number of brains in the chest which allows Heidi to merely survive.
[ "1\n", "3\n", "99\n" ]
[ "0\n", "1\n", "49\n" ]
none
[ { "input": "1", "output": "0" }, { "input": "3", "output": "1" }, { "input": "2", "output": "0" }, { "input": "4", "output": "0" }, { "input": "5", "output": "2" }, { "input": "6", "output": "1" }, { "input": "7", "output": "3" }, {...
46
0
0
30,371
995
Tesla
[ "constructive algorithms", "implementation" ]
null
null
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $4$ rows and $n$ ($n \le 50$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $k$ ($k \le 2n$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $20000$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
The first line of the input contains two space-separated integers $n$ and $k$ ($1 \le n \le 50$, $1 \le k \le 2n$), representing the number of columns and the number of cars, respectively. The next four lines will contain $n$ integers each between $0$ and $k$ inclusive, representing the initial state of the parking lot. The rows are numbered $1$ to $4$ from top to bottom and the columns are numbered $1$ to $n$ from left to right. In the first and last line, an integer $1 \le x \le k$ represents a parking spot assigned to car $x$ (you can only move this car to this place), while the integer $0$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $1 \le x \le k$ represents initial position of car $x$, while the integer $0$ represents an empty space (you can move any car to this place). Each $x$ between $1$ and $k$ appears exactly once in the second and third line, and exactly once in the first and fourth line.
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $20000$ car moves, then print $m$, the number of moves, on the first line. On the following $m$ lines, print the moves (one move per line) in the format $i$ $r$ $c$, which corresponds to Allen moving car $i$ to the neighboring space at row $r$ and column $c$. If it is not possible for Allen to move all the cars to the correct spaces with at most $20000$ car moves, print a single line with the integer $-1$.
[ "4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3\n", "1 2\n1\n2\n1\n2\n", "1 2\n1\n1\n2\n2\n" ]
[ "6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2\n", "-1\n", "2\n1 1 1\n2 4 1\n" ]
In the first sample test case, all cars are in front of their spots except car $5$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $20000$ will be accepted. In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
[ { "input": "4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "output": "6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2" }, { "input": "1 2\n1\n2\n1\n2", "output": "-1" }, { "input": "1 2\n1\n1\n2\n2", "output": "2\n1 1 1\n2 4 1" }, { "input": "2 2\n1 0\n0 2\n0 1\n0 2", "output": "7...
1,465
268,390,400
0
30,486
87
Vasya and Types
[ "implementation", "strings" ]
B. Vasya and Types
2
256
Programmer Vasya is studying a new programming language &amp;K*. The &amp;K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages. There is a very powerful system of pointers on &amp;K* — you can add an asterisk to the right of the existing type *X* — that will result in new type *X*<=*<=. That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of *X*, which is a pointer, you can add an ampersand — that will result in a type &amp;*X*, to which refers *X*. That is called a dereference operation. The &amp;K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof. - The operator "typedef *A* *B*" defines a new data type *B*, which is equivalent to *A*. *A* can have asterisks and ampersands, and *B* cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.- The operator "typeof *A*" returns type of *A*, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**. An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype*<==<=&amp;errtype<==<=errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype. Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change. Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &amp;*T*<=*<= is always equal to *T*. Note, that the operators are executed consecutively one by one. If we have two operators "typedef &amp;void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &amp;void* = void (see sample 2). Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of operators. Then follow *n* lines with operators. Each operator is of one of two types: either "typedef *A* *B*", or "typeof *A*". In the first case the *B* type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands. All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.
[ "5\ntypedef void* ptv\ntypeof ptv\ntypedef &amp;&amp;ptv node\ntypeof node\ntypeof &amp;ptv\n", "17\ntypedef void* b\ntypedef b* c\ntypeof b\ntypeof c\ntypedef &amp;b b\ntypeof b\ntypeof c\ntypedef &amp;&amp;b* c\ntypeof c\ntypedef &amp;b* c\ntypeof c\ntypedef &amp;void b\ntypeof b\ntypedef b******* c\ntypeof c\n...
[ "void*\nerrtype\nvoid\n", "void*\nvoid**\nvoid\nvoid**\nerrtype\nvoid\nerrtype\nerrtype\nerrtype\n" ]
Let's look at the second sample. After the first two queries typedef the b type is equivalent to void*, and с — to void**. The next query typedef redefines b — it is now equal to &amp;b = &amp;void* = void. At that, the с type doesn't change. After that the с type is defined as &amp;&amp;b* = &amp;&amp;void* = &amp;void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &amp;void* = void. Then the b type is again redefined as &amp;void = errtype. Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &amp;void******* = void******. The same happens in the last typedef.
[ { "input": "5\ntypedef void* ptv\ntypeof ptv\ntypedef &&ptv node\ntypeof node\ntypeof &ptv", "output": "void*\nerrtype\nvoid" }, { "input": "17\ntypedef void* b\ntypedef b* c\ntypeof b\ntypeof c\ntypedef &b b\ntypeof b\ntypeof c\ntypedef &&b* c\ntypeof c\ntypedef &b* c\ntypeof c\ntypedef &void b\nty...
92
0
0
30,487
180
Cubes
[ "binary search", "dp", "two pointers" ]
null
null
Let's imagine that you're playing the following simple computer game. The screen displays *n* lined-up cubes. Each cube is painted one of *m* colors. You are allowed to delete not more than *k* cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) and the system counts the score. The number of points you score equals to the length of the maximum sequence of cubes of the same color that follow consecutively. Write a program that determines the maximum possible number of points you can score. Remember, you may delete no more than *k* any cubes. It is allowed not to delete cubes at all.
The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=2·105,<=1<=≤<=*m*<=≤<=105,<=0<=≤<=*k*<=&lt;<=*n*). The second line contains *n* integers from 1 to *m* — the numbers of cube colors. The numbers of colors are separated by single spaces.
Print the maximum possible number of points you can score.
[ "10 3 2\n1 2 1 1 3 2 1 1 2 2\n", "10 2 2\n1 2 1 2 1 1 2 1 1 2\n", "3 1 2\n1 1 1\n" ]
[ "4\n", "5\n", "3\n" ]
In the first sample you should delete the fifth and the sixth cubes. In the second sample you should delete the fourth and the seventh cubes. In the third sample you shouldn't delete any cubes.
[ { "input": "10 3 2\n1 2 1 1 3 2 1 1 2 2", "output": "4" }, { "input": "10 2 2\n1 2 1 2 1 1 2 1 1 2", "output": "5" }, { "input": "3 1 2\n1 1 1", "output": "3" }, { "input": "10 2 2\n1 1 1 2 1 2 1 2 1 1", "output": "5" }, { "input": "1 1 0\n1", "output": "1" ...
280
23,756,800
3
30,507
507
The Maths Lecture
[ "dp", "implementation" ]
null
null
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't. First he gave Amr two positive integers *n* and *k*. Then he asked Amr, how many integer numbers *x*<=&gt;<=0 exist such that: - Decimal representation of *x* (without leading zeroes) consists of exactly *n* digits; - There exists some integer *y*<=&gt;<=0 such that: ; - decimal representation of *y* is a suffix of decimal representation of *x*. As the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number *m*. Can you help Amr escape this embarrassing situation?
Input consists of three integers *n*,<=*k*,<=*m* (1<=≤<=*n*<=≤<=1000, 1<=≤<=*k*<=≤<=100, 1<=≤<=*m*<=≤<=109).
Print the required number modulo *m*.
[ "1 2 1000\n", "2 2 1000\n", "5 3 1103\n" ]
[ "4", "45", "590" ]
A suffix of a string *S* is a non-empty string that can be obtained by removing some number (possibly, zero) of first characters from *S*.
[ { "input": "1 2 1000", "output": "4" }, { "input": "2 2 1000", "output": "45" }, { "input": "5 3 1103", "output": "590" }, { "input": "2 17 10000", "output": "5" }, { "input": "3 9 10000", "output": "252" }, { "input": "6 64 941761822", "output": "...
30
0
0
30,547
222
Cosmic Tables
[ "data structures", "implementation" ]
null
null
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an *n*<=×<=*m* table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: - The query to swap two table rows; - The query to swap two table columns; - The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
The first line contains three space-separated integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=1000, 1<=≤<=*k*<=≤<=500000) — the number of table columns and rows and the number of queries, correspondingly. Next *n* lines contain *m* space-separated numbers each — the initial state of the table. Each number *p* in the table is an integer and satisfies the inequality 0<=≤<=*p*<=≤<=106. Next *k* lines contain queries in the format "*s**i* *x**i* *y**i*", where *s**i* is one of the characters "с", "r" or "g", and *x**i*, *y**i* are two integers. - If *s**i* = "c", then the current query is the query to swap columns with indexes *x**i* and *y**i* (1<=≤<=*x*,<=*y*<=≤<=*m*,<=*x*<=≠<=*y*); - If *s**i* = "r", then the current query is the query to swap rows with indexes *x**i* and *y**i* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*); - If *s**i* = "g", then the current query is the query to obtain the number that located in the *x**i*-th row and in the *y**i*-th column (1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*). The table rows are considered to be indexed from top to bottom from 1 to *n*, and the table columns — from left to right from 1 to *m*.
For each query to obtain a number (*s**i* = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
[ "3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2\n", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3\n" ]
[ "8\n9\n6\n", "5\n" ]
Let's see how the table changes in the second test case. After the first operation is fulfilled, the table looks like that: 2 1 4 1 3 5 After the second operation is fulfilled, the table looks like that: 1 3 5 2 1 4 So the answer to the third query (the number located in the first row and in the third column) will be 5.
[ { "input": "3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "output": "8\n9\n6" }, { "input": "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3", "output": "5" }, { "input": "1 1 15\n1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1 1\ng 1...
186
307,200
-1
30,595
545
Equidistant String
[ "greedy" ]
null
null
Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance: We will define the distance between two strings *s* and *t* of the same length consisting of digits zero and one as the number of positions *i*, such that *s**i* isn't equal to *t**i*. As besides everything else Susie loves symmetry, she wants to find for two strings *s* and *t* of length *n* such string *p* of length *n*, that the distance from *p* to *s* was equal to the distance from *p* to *t*. It's time for Susie to go to bed, help her find such string *p* or state that it is impossible.
The first line contains string *s* of length *n*. The second line contains string *t* of length *n*. The length of string *n* is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.
Print a string of length *n*, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes). If there are multiple possible answers, print any of them.
[ "0001\n1011\n", "000\n111\n" ]
[ "0011\n", "impossible\n" ]
In the first sample different answers are possible, namely — 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.
[ { "input": "0001\n1011", "output": "0011" }, { "input": "000\n111", "output": "impossible" }, { "input": "1010101011111110111111001111111111111111111111101101110111111111111110110110101011111110110111111101\n01011111110001000101000011000101010000000110000000000110110000011001000011101110...
62
307,200
3
30,689
496
Tennis Game
[ "binary search" ]
null
null
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores *t* points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of *s* sets, he wins the match and the match is over. Here *s* and *t* are some positive integer numbers. To spice it up, Petya and Gena choose new numbers *s* and *t* before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores *t* points and the match is over as soon as one of the players wins *s* sets. Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers *s* and *t* for the given match are also lost. The players now wonder what values of *s* and *t* might be. Can you determine all the possible options?
The first line contains a single integer *n* — the length of the sequence of games (1<=≤<=*n*<=≤<=105). The second line contains *n* space-separated integers *a**i*. If *a**i*<==<=1, then the *i*-th serve was won by Petya, if *a**i*<==<=2, then the *i*-th serve was won by Gena. It is not guaranteed that at least one option for numbers *s* and *t* corresponds to the given record.
In the first line print a single number *k* — the number of options for numbers *s* and *t*. In each of the following *k* lines print two integers *s**i* and *t**i* — the option for numbers *s* and *t*. Print the options in the order of increasing *s**i*, and for equal *s**i* — in the order of increasing *t**i*.
[ "5\n1 2 1 2 1\n", "4\n1 1 1 1\n", "4\n1 2 1 2\n", "8\n2 1 2 1 1 1 1 1\n" ]
[ "2\n1 3\n3 1\n", "3\n1 4\n2 2\n4 1\n", "0\n", "3\n1 6\n2 3\n6 1\n" ]
none
[ { "input": "5\n1 2 1 2 1", "output": "2\n1 3\n3 1" }, { "input": "4\n1 1 1 1", "output": "3\n1 4\n2 2\n4 1" }, { "input": "4\n1 2 1 2", "output": "0" }, { "input": "8\n2 1 2 1 1 1 1 1", "output": "3\n1 6\n2 3\n6 1" }, { "input": "14\n2 1 2 1 1 1 1 2 1 1 2 1 2 1", ...
2,000
0
0
30,719
924
Contact ATC
[]
null
null
Arkady the air traffic controller is now working with *n* planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point 0 on it. The *i*-th plane, small enough to be represented by a point, currently has a coordinate of *x**i* and is moving with speed *v**i*. It's guaranteed that *x**i*·*v**i*<=&lt;<=0, i.e., all planes are moving towards the station. Occasionally, the planes are affected by winds. With a wind of speed *v**wind* (not necessarily positive or integral), the speed of the *i*-th plane becomes *v**i*<=+<=*v**wind*. According to weather report, the current wind has a steady speed falling inside the range [<=-<=*w*,<=*w*] (inclusive), but the exact value cannot be measured accurately since this value is rather small — smaller than the absolute value of speed of any plane. Each plane should contact Arkady at the exact moment it passes above his station. And you are to help Arkady count the number of pairs of planes (*i*,<=*j*) (*i*<=&lt;<=*j*) there are such that there is a possible value of wind speed, under which planes *i* and *j* contact Arkady at the same moment. This value needn't be the same across different pairs. The wind speed is the same for all planes. You may assume that the wind has a steady speed and lasts arbitrarily long.
The first line contains two integers *n* and *w* (1<=≤<=*n*<=≤<=100<=000, 0<=≤<=*w*<=&lt;<=105) — the number of planes and the maximum wind speed. The *i*-th of the next *n* lines contains two integers *x**i* and *v**i* (1<=≤<=|*x**i*|<=≤<=105, *w*<=+<=1<=≤<=|*v**i*|<=≤<=105, *x**i*·*v**i*<=&lt;<=0) — the initial position and speed of the *i*-th plane. Planes are pairwise distinct, that is, no pair of (*i*,<=*j*) (*i*<=&lt;<=*j*) exists such that both *x**i*<==<=*x**j* and *v**i*<==<=*v**j*.
Output a single integer — the number of unordered pairs of planes that can contact Arkady at the same moment.
[ "5 1\n-3 2\n-3 3\n-1 2\n1 -3\n3 -5\n", "6 1\n-3 2\n-2 2\n-1 2\n1 -2\n2 -2\n3 -2\n" ]
[ "3\n", "9\n" ]
In the first example, the following 3 pairs of planes satisfy the requirements: - (2, 5) passes the station at time 3 / 4 with *v*<sub class="lower-index">*wind*</sub> = 1; - (3, 4) passes the station at time 2 / 5 with *v*<sub class="lower-index">*wind*</sub> = 1 / 2; - (3, 5) passes the station at time 4 / 7 with *v*<sub class="lower-index">*wind*</sub> =  - 1 / 4. In the second example, each of the 3 planes with negative coordinates can form a valid pair with each of the other 3, totaling 9 pairs.
[]
1,000
35,840,000
0
30,736
95
Volleyball
[ "shortest paths" ]
C. Volleyball
2
256
Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has *n* junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths. Initially each junction has exactly one taxi standing there. The taxi driver from the *i*-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than *t**i* meters. Also, the cost of the ride doesn't depend on the distance and is equal to *c**i* bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially. At the moment Petya is located on the junction *x* and the volleyball stadium is on the junction *y*. Determine the minimum amount of money Petya will need to drive to the stadium.
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=1000,<=0<=≤<=*m*<=≤<=1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to *n*, inclusive. The next line contains two integers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*). They are the numbers of the initial and final junctions correspondingly. Next *m* lines contain the roads' description. Each road is described by a group of three integers *u**i*, *v**i*, *w**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=1<=≤<=*w**i*<=≤<=109) — they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next *n* lines contain *n* pairs of integers *t**i* and *c**i* (1<=≤<=*t**i*,<=*c**i*<=≤<=109), which describe the taxi driver that waits at the *i*-th junction — the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character.
If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
[ "4 4\n1 3\n1 2 3\n1 4 1\n2 4 1\n2 3 5\n2 7\n7 2\n1 2\n7 7\n" ]
[ "9\n" ]
An optimal way — ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles.
[ { "input": "4 4\n1 3\n1 2 3\n1 4 1\n2 4 1\n2 3 5\n2 7\n7 2\n1 2\n7 7", "output": "9" }, { "input": "3 3\n1 3\n1 2 2\n1 3 3\n3 2 1\n2 7\n2 7\n3 6", "output": "14" }, { "input": "3 1\n1 3\n1 2 2\n2 7\n2 7\n3 6", "output": "-1" }, { "input": "3 2\n3 3\n1 2 2\n1 3 3\n2 7\n2 7\n3 ...
92
0
0
30,760
768
Game of Stones
[ "bitmasks", "dp", "games" ]
null
null
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: - The game starts with *n* piles of stones indexed from 1 to *n*. The *i*-th pile contains *s**i* stones.- The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of 0 stones does not count as a move.- The player who is unable to make a move loses. Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game. In this modified version, no move can be made more than once on a pile. For example, if 4 stones are removed from a pile, 4 stones cannot be removed from that pile again. Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.
First line consists of a single integer *n* (1<=≤<=*n*<=≤<=106) — the number of piles. Each of next *n* lines contains an integer *s**i* (1<=≤<=*s**i*<=≤<=60) — the number of stones in *i*-th pile.
Print a single line containing "YES" (without quotes) if Jon wins, otherwise print "NO" (without quotes)
[ "1\n5\n", "2\n1\n2\n" ]
[ "NO", "YES" ]
In the first case, Sam removes all the stones and Jon loses. In second case, the following moves are possible by Sam: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/53b9c060b675da85f39a960b8ab29df7fe51f6e3.png" style="max-width: 100.0%;max-height: 100.0%;"/> In each of these cases, last move can be made by Jon to win the game as follows: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5089ff5bcdbeb10a07b0bf16566d6f4703e99334.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "1\n5", "output": "NO" }, { "input": "2\n1\n2", "output": "YES" }, { "input": "3\n34\n44\n21", "output": "NO" }, { "input": "6\n34\n44\n21\n55\n1\n36", "output": "NO" }, { "input": "14\n34\n44\n21\n55\n1\n36\n53\n31\n58\n59\n11\n40\n20\n32", "output...
46
0
0
30,761
180
Divisibility Rules
[ "math", "number theory" ]
null
null
Vasya studies divisibility rules at school. Here are some of them: - Divisibility by 2. A number is divisible by 2 if and only if its last digit is divisible by 2 or in other words, is even.- Divisibility by 3. A number is divisible by 3 if and only if the sum of its digits is divisible by 3.- Divisibility by 4. A number is divisible by 4 if and only if its last two digits form a number that is divisible by 4.- Divisibility by 5. A number is divisible by 5 if and only if its last digit equals 5 or 0.- Divisibility by 6. A number is divisible by 6 if and only if it is divisible by 2 and 3 simultaneously (that is, if the last digit is even and the sum of all digits is divisible by 3).- Divisibility by 7. Vasya doesn't know such divisibility rule.- Divisibility by 8. A number is divisible by 8 if and only if its last three digits form a number that is divisible by 8.- Divisibility by 9. A number is divisible by 9 if and only if the sum of its digits is divisible by 9.- Divisibility by 10. A number is divisible by 10 if and only if its last digit is a zero.- Divisibility by 11. A number is divisible by 11 if and only if the sum of digits on its odd positions either equals to the sum of digits on the even positions, or they differ in a number that is divisible by 11. Vasya got interested by the fact that some divisibility rules resemble each other. In fact, to check a number's divisibility by 2, 4, 5, 8 and 10 it is enough to check fulfiling some condition for one or several last digits. Vasya calls such rules the 2-type rules. If checking divisibility means finding a sum of digits and checking whether the sum is divisible by the given number, then Vasya calls this rule the 3-type rule (because it works for numbers 3 and 9). If we need to find the difference between the sum of digits on odd and even positions and check whether the difference is divisible by the given divisor, this rule is called the 11-type rule (it works for number 11). In some cases we should divide the divisor into several factors and check whether rules of different types (2-type, 3-type or 11-type) work there. For example, for number 6 we check 2-type and 3-type rules, for number 66 we check all three types. Such mixed divisibility rules are called 6-type rules. And finally, there are some numbers for which no rule works: neither 2-type, nor 3-type, nor 11-type, nor 6-type. The least such number is number 7, so we'll say that in such cases the mysterious 7-type rule works, the one that Vasya hasn't discovered yet. Vasya's dream is finding divisibility rules for all possible numbers. He isn't going to stop on the decimal numbers only. As there are quite many numbers, ha can't do it all by himself. Vasya asked you to write a program that determines the divisibility rule type in the *b*-based notation for the given divisor *d*.
The first input line contains two integers *b* and *d* (2<=≤<=*b*,<=*d*<=≤<=100) — the notation system base and the divisor. Both numbers are given in the decimal notation.
On the first output line print the type of the rule in the *b*-based notation system, where the divisor is *d*: "2-type", "3-type", "11-type", "6-type" or "7-type". If there are several such types, print the one that goes earlier in the given sequence. If a number belongs to the 2-type, print on the second line the least number of the last *b*-based digits that we will need to use to check the divisibility.
[ "10 10\n", "2 3\n" ]
[ "2-type\n1\n", "11-type\n" ]
The divisibility rule for number 3 in binary notation looks as follows: "A number is divisible by 3 if and only if the sum of its digits that occupy the even places differs from the sum of digits that occupy the odd places, in a number that is divisible by 3". That's an 11-type rule. For example, 21<sub class="lower-index">10</sub> = 10101<sub class="lower-index">2</sub>. For it the sum of digits on odd positions equals 1 + 1 + 1 = 3, an on even positions — 0 + 0 = 0. The rule works and the number is divisible by 3. In some notations a number can fit into the 3-type rule and the 11-type rule. In this case the correct answer is "3-type".
[ { "input": "10 10", "output": "2-type\n1" }, { "input": "2 3", "output": "11-type" }, { "input": "2 2", "output": "2-type\n1" }, { "input": "2 3", "output": "11-type" }, { "input": "2 4", "output": "2-type\n2" }, { "input": "2 5", "output": "7-type...
92
0
0
30,878
1,000
Codehorses T-shirts
[ "greedy", "implementation" ]
null
null
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from $0$ to $3$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. There are $n$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words. What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one? The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
The first line contains one integer $n$ ($1 \le n \le 100$) — the number of T-shirts. The $i$-th of the next $n$ lines contains $a_i$ — the size of the $i$-th T-shirt of the list for the previous year. The $i$-th of the next $n$ lines contains $b_i$ — the size of the $i$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $b$ from the list $a$.
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
[ "3\nXS\nXS\nM\nXL\nS\nXS\n", "2\nXXXL\nXXL\nXXL\nXXXS\n", "2\nM\nXS\nXS\nM\n" ]
[ "2\n", "1\n", "0\n" ]
In the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L". In the second example Ksenia should replace "L" in "XXXL" with "S". In the third example lists are equal.
[ { "input": "3\nXS\nXS\nM\nXL\nS\nXS", "output": "2" }, { "input": "2\nXXXL\nXXL\nXXL\nXXXS", "output": "1" }, { "input": "2\nM\nXS\nXS\nM", "output": "0" }, { "input": "1\nXXXL\nXXXL", "output": "0" }, { "input": "1\nM\nM", "output": "0" }, { "input": ...
30
4,505,600
-1
30,944
722
Cyclic Cipher
[ "chinese remainder theorem", "data structures", "implementation", "number theory", "two pointers" ]
null
null
You are given *n* sequences. Each sequence consists of positive integers, not exceeding *m*. All integers in one sequence are distinct, but the same integer may appear in multiple sequences. The length of the *i*-th sequence is *k**i*. Each second integers in each of the sequences are shifted by one to the left, i.e. integers at positions *i*<=&gt;<=1 go to positions *i*<=-<=1, while the first integers becomes the last. Each second we take the first integer of each sequence and write it down to a new array. Then, for each value *x* from 1 to *m* we compute the longest segment of the array consisting of element *x* only. The above operation is performed for 10100 seconds. For each integer from 1 to *m* find out the longest segment found at this time.
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100<=000) — the number of sequences and the maximum integer that can appear in the sequences. Then follow *n* lines providing the sequences. Each of them starts with an integer *k**i* (1<=≤<=*k**i*<=≤<=40) — the number of integers in the sequence, proceeded by *k**i* positive integers — elements of the sequence. It's guaranteed that all integers in each sequence are pairwise distinct and do not exceed *m*. The total length of all sequences doesn't exceed 200<=000.
Print *m* integers, the *i*-th of them should be equal to the length of the longest segment of the array with all its values equal to *i* during the first 10100 seconds.
[ "3 4\n3 3 4 1\n4 1 3 4 2\n3 3 1 4\n", "5 5\n2 3 1\n4 5 1 3 2\n4 2 1 3 5\n1 3\n2 5 3\n", "4 6\n3 4 5 3\n2 6 3\n2 3 6\n3 3 6 5\n" ]
[ "2\n1\n3\n2\n", "3\n1\n4\n0\n1\n", "0\n0\n2\n1\n1\n2\n" ]
none
[ { "input": "3 4\n3 3 4 1\n4 1 3 4 2\n3 3 1 4", "output": "2\n1\n3\n2" }, { "input": "5 5\n2 3 1\n4 5 1 3 2\n4 2 1 3 5\n1 3\n2 5 3", "output": "3\n1\n4\n0\n1" }, { "input": "4 6\n3 4 5 3\n2 6 3\n2 3 6\n3 3 6 5", "output": "0\n0\n2\n1\n1\n2" }, { "input": "10 5\n2 2 4\n2 4 5\n2...
108
4,096,000
0
30,979
110
Lucky String
[ "constructive algorithms", "strings" ]
B. Lucky String
2
256
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: - b: 2- c: 3,<=10- d: 4,<=8- e: 6- f: 7- z: 1,<=5,<=9- Lists of positions of letters a, g, h, ..., y are empty. This string is lucky as all differences are lucky numbers. For letters z: 5<=-<=1<==<=4, 9<=-<=5<==<=4, for letters c: 10<=-<=3<==<=7, for letters d: 8<=-<=4<==<=4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky. Find the lexicographically minimal lucky string whose length equals *n*.
The single line contains a positive integer *n* (1<=≤<=*n*<=≤<=105) — the length of the sought string.
Print on the single line the lexicographically minimal lucky string whose length equals *n*.
[ "5\n", "3\n" ]
[ "abcda\n", "abc\n" ]
The lexical comparison of strings is performed by the &lt; operator in modern programming languages. String *a* is lexicographically less than string *b* if exists such *i* (1 ≤ *i* ≤ *n*), that *a*<sub class="lower-index">*i*</sub> &lt; *b*<sub class="lower-index">*i*</sub>, and for any *j* (1 ≤ *j* &lt; *i*) *a*<sub class="lower-index">*j*</sub> = *b*<sub class="lower-index">*j*</sub>.
[ { "input": "5", "output": "abcda" }, { "input": "3", "output": "abc" }, { "input": "8", "output": "abcdabcd" }, { "input": "10", "output": "abcdabcdab" }, { "input": "16", "output": "abcdabcdabcdabcd" }, { "input": "64", "output": "abcdabcdabcdabcd...
248
204,800
3.937619
31,100
216
Hiring Staff
[ "greedy" ]
null
null
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff. The store will work seven days a week, but not around the clock. Every day at least *k* people must work in the store. Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly *n* consecutive days, then rest for exactly *m* days, then work for *n* more days and rest for *m* more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day *x*, then he should work on days [*x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*n*<=-<=1], [*x*<=+<=*m*<=+<=*n*,<=*x*<=+<=*m*<=+<=*n*<=+<=1,<=...,<=*x*<=+<=*m*<=+<=2*n*<=-<=1], and so on. Day *x* can be chosen arbitrarily by Vitaly. There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day — otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day. Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least *k* working employees, and one of the working employees should have the key to the store. Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.
The first line contains three integers *n*, *m* and *k* (1<=≤<=*m*<=≤<=*n*<=≤<=1000, *n*<=≠<=1, 1<=≤<=*k*<=≤<=1000).
In the first line print a single integer *z* — the minimum required number of employees. In the second line print *z* positive integers, separated by spaces: the *i*-th integer *a**i* (1<=≤<=*a**i*<=≤<=104) should represent the number of the day, on which Vitaly should hire the *i*-th employee. If there are multiple answers, print any of them.
[ "4 3 2\n", "3 3 1\n" ]
[ "4\n1 1 4 5", "3\n1 3 5" ]
none
[ { "input": "4 3 2", "output": "4\n1 1 4 5" }, { "input": "3 3 1", "output": "3\n1 3 5" }, { "input": "5 5 3", "output": "7\n1 1 1 5 6 6 7" }, { "input": "7 6 8", "output": "16\n1 1 1 1 1 1 1 1 7 7 7 7 7 7 7 8" }, { "input": "8 3 2", "output": "4\n1 1 8 9" },...
154
6,758,400
0
31,177
549
Looksery Party
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
null
null
The Looksery company, consisting of *n* staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself. Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates *n* numbers, the *i*-th of which indicates how many messages, in his view, the *i*-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins. You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of employees of company Looksery. Next *n* lines contain the description of the contact lists of the employees. The *i*-th of these lines contains a string of length *n*, consisting of digits zero and one, specifying the contact list of the *i*-th employee. If the *j*-th character of the *i*-th string equals 1, then the *j*-th employee is in the *i*-th employee's contact list, otherwise he isn't. It is guaranteed that the *i*-th character of the *i*-th line is always equal to 1. The last line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=*n*), where *a**i* represents the number of messages that the *i*-th employee should get according to Igor.
In the first line print a single integer *m* — the number of employees who should come to the party so that Igor loses the dispute. In the second line print *m* space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them.
[ "3\n101\n010\n001\n0 1 2\n", "1\n1\n1\n", "4\n1111\n0101\n1110\n0001\n1 0 1 0\n" ]
[ "1\n1 \n", "0\n\n", "4\n1 2 3 4 \n" ]
In the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number. In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it. In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3.
[ { "input": "3\n101\n010\n001\n0 1 2", "output": "1\n1 " }, { "input": "1\n1\n1", "output": "0" }, { "input": "4\n1111\n0101\n1110\n0001\n1 0 1 0", "output": "4\n1 2 3 4 " }, { "input": "2\n11\n01\n0 2", "output": "1\n1 " }, { "input": "5\n10110\n01110\n00101\n0001...
140
1,024,000
3
31,226
28
pSort
[ "dfs and similar", "dsu", "graphs" ]
B. pSort
2
256
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*|<==<=*d**i*, where *d**i* 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.
[ "5\n5 4 3 2 1\n1 1 1 1 1\n", "7\n4 3 5 1 2 7 6\n4 6 6 1 6 6 1\n", "7\n4 2 5 1 3 7 6\n4 6 6 1 6 6 1\n" ]
[ "YES\n", "NO\n", "YES\n" ]
none
[ { "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" }, { "input": "6\n3 2 1 4 6 5\n3 6 1 6 6 1", "output": "YES" }, { "input": "6\n3 ...
92
0
3.977
31,321
279
Point on Spiral
[ "brute force", "geometry", "implementation" ]
null
null
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0,<=0),<=(1,<=0)], [(1,<=0),<=(1,<=1)], [(1,<=1),<=(<=-<=1,<=1)], [(<=-<=1,<=1),<=(<=-<=1,<=<=-<=1)], [(<=-<=1,<=<=-<=1),<=(2,<=<=-<=1)], [(2,<=<=-<=1),<=(2,<=2)] and so on. Thus, this infinite spiral passes through each integer point of the plane. Valera the horse lives on the plane at coordinates (0,<=0). He wants to walk along the spiral to point (*x*,<=*y*). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0,<=0) to point (*x*,<=*y*).
The first line contains two space-separated integers *x* and *y* (|*x*|,<=|*y*|<=≤<=100).
Print a single integer, showing how many times Valera has to turn.
[ "0 0\n", "1 0\n", "0 1\n", "-1 -1\n" ]
[ "0\n", "0\n", "2\n", "3\n" ]
none
[ { "input": "0 0", "output": "0" }, { "input": "1 0", "output": "0" }, { "input": "0 1", "output": "2" }, { "input": "-1 -1", "output": "3" }, { "input": "10 10", "output": "37" }, { "input": "0 6", "output": "22" }, { "input": "-7 -13", ...
92
0
3
31,363
859
Circle of Numbers
[ "math" ]
null
null
*n* evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number *k*. Then you may repeatedly select a set of 2 or more points which are evenly spaced, and either increase all numbers at points in the set by *k* or decrease all numbers at points in the set by *k*. You would like to eventually end up with all numbers equal to 0. Is it possible? A set of 2 points is considered evenly spaced if they are diametrically opposed, and a set of 3 or more points is considered evenly spaced if they form a regular polygon.
The first line of input contains an integer *n* (3<=≤<=*n*<=≤<=100000), the number of points along the circle. The following line contains a string *s* with exactly *n* digits, indicating the numbers initially present at each of the points, in clockwise order.
Print "YES" (without quotes) if there is some sequence of operations that results in all numbers being 0, otherwise "NO" (without quotes). You can print each letter in any case (upper or lower).
[ "30\n000100000100000110000000001100\n", "6\n314159\n" ]
[ "YES\n", "NO\n" ]
If we label the points from 1 to *n*, then for the first test case we can set *k* = 1. Then we increase the numbers at points 7 and 22 by 1, then decrease the numbers at points 7, 17, and 27 by 1, then decrease the numbers at points 4, 10, 16, 22, and 28 by 1.
[ { "input": "30\n000100000100000110000000001100", "output": "YES" }, { "input": "6\n314159", "output": "NO" }, { "input": "3\n000", "output": "YES" }, { "input": "15\n522085220852208", "output": "YES" }, { "input": "300\n51849955123882532841766314023795544655059625...
30
4,608,000
0
31,400
958
Death Stars (easy)
[ "implementation" ]
null
null
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an *N*<=×<=*N* grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out.
The first line of the input contains one number *N* (1<=≤<=*N*<=≤<=10) – the dimension of each map. Next *N* lines each contain *N* characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next *N* lines each contain *N* characters, depicting the second map in the same format.
The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations.
[ "4\nXOOO\nXXOO\nOOOO\nXXXX\nXOOO\nXOOO\nXOXO\nXOXX\n", "2\nXX\nOO\nXO\nOX\n" ]
[ "Yes\n", "No\n" ]
In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise.
[ { "input": "4\nXOOO\nXXOO\nOOOO\nXXXX\nXOOO\nXOOO\nXOXO\nXOXX", "output": "Yes" }, { "input": "2\nXX\nOO\nXO\nOX", "output": "No" }, { "input": "1\nO\nO", "output": "Yes" }, { "input": "1\nX\nO", "output": "No" }, { "input": "2\nOX\nXX\nOX\nXX", "output": "Yes...
78
0
0
31,428
593
Strange Calculation and Cats
[ "dp", "matrices" ]
null
null
Gosha's universe is a table consisting of *n* rows and *m* columns. Both the rows and columns are numbered with consecutive integers starting with 1. We will use (*r*,<=*c*) to denote a cell located in the row *r* and column *c*. Gosha is often invited somewhere. Every time he gets an invitation, he first calculates the number of ways to get to this place, and only then he goes. Gosha's house is located in the cell (1,<=1). At any moment of time, Gosha moves from the cell he is currently located in to a cell adjacent to it (two cells are adjacent if they share a common side). Of course, the movement is possible only if such a cell exists, i.e. Gosha will not go beyond the boundaries of the table. Thus, from the cell (*r*,<=*c*) he is able to make a move to one of the cells (*r*<=-<=1,<=*c*), (*r*,<=*c*<=-<=1), (*r*<=+<=1,<=*c*), (*r*,<=*c*<=+<=1). Also, Ghosha can skip a move and stay in the current cell (*r*,<=*c*). Besides the love of strange calculations, Gosha is allergic to cats, so he never goes to the cell that has a cat in it. Gosha knows exactly where and when he will be invited and the schedule of cats travelling along the table. Formally, he has *q* records, the *i*-th of them has one of the following forms: - 1, *x**i*, *y**i*, *t**i* — Gosha is invited to come to cell (*x**i*,<=*y**i*) at the moment of time *t**i*. It is guaranteed that there is no cat inside cell (*x**i*,<=*y**i*) at this moment of time. - 2, *x**i*, *y**i*, *t**i* — at the moment *t**i* a cat appears in cell (*x**i*,<=*y**i*). It is guaranteed that no other cat is located in this cell (*x**i*,<=*y**i*) at that moment of time. - 3, *x**i*, *y**i*, *t**i* — at the moment *t**i* a cat leaves cell (*x**i*,<=*y**i*). It is guaranteed that there is cat located in the cell (*x**i*,<=*y**i*). Gosha plans to accept only one invitation, but he has not yet decided, which particular one. In order to make this decision, he asks you to calculate for each of the invitations *i* the number of ways to get to the cell (*x**i*,<=*y**i*) at the moment *t**i*. For every invitation, assume that Gosha he starts moving from cell (1,<=1) at the moment 1. Moving between two neighboring cells takes Gosha exactly one unit of tim. In particular, this means that Gosha can come into the cell only if a cat sitting in it leaves the moment when Gosha begins his movement from the neighboring cell, and if none of the cats comes to the cell at the time when Gosha is in it. Two ways to go from cell (1,<=1) to cell (*x*,<=*y*) at time *t* are considered distinct if for at least one moment of time from 1 to *t* Gosha's positions are distinct for the two ways at this moment. Note, that during this travel Gosha is allowed to visit both (1,<=1) and (*x*,<=*y*) multiple times. Since the number of ways can be quite large, print it modulo 109<=+<=7.
The first line of the input contains three positive integers *n*, *m* and *q* (1<=≤<=*n*·*m*<=≤<=20,<=1<=≤<=*q*<=≤<=10<=000) — the number of rows and columns in the table and the number of events respectively. Next *q* lines describe the events, each description contains four integers *tp**i*, *x**i*, *y**i* and *t**i* (1<=≤<=*tp*<=≤<=3,<=1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*,<=2<=≤<=*t*<=≤<=109) — the type of the event (1 if Gosha gets an invitation, 2 if a cat comes to the cell and 3 if a cat leaves the cell), the coordinates of the cell where the action takes place and the moment of time at which the action takes place respectively. It is guaranteed that the queries are given in the chronological order, i.e. *t**i*<=&lt;<=*t**i*<=+<=1.
For each invitation *i* (that is, *tp**i*<==<=1) calculate the number of ways to get to cell (*x**i*,<=*y**i*) at the moment of time *t**i*. Respond to the invitations chronologically, that is, in the order they appear in the input.
[ "1 3 3\n2 1 2 3\n3 1 2 5\n1 1 1 7\n", "3 3 3\n2 2 2 2\n1 3 3 5\n1 3 3 7\n", "4 5 5\n2 2 5 3\n2 2 4 6\n3 2 4 9\n1 4 4 13\n1 4 4 15\n" ]
[ "5\n", "2\n42\n", "490902\n10598759\n" ]
Explanation of the first sample. Each picture specifies the number of ways to arrive at the cell at the appropriate time. (X stands for a cell blocked at this particular moment of time)
[ { "input": "1 3 3\n2 1 2 3\n3 1 2 5\n1 1 1 7", "output": "5" }, { "input": "3 3 3\n2 2 2 2\n1 3 3 5\n1 3 3 7", "output": "2\n42" }, { "input": "4 5 5\n2 2 5 3\n2 2 4 6\n3 2 4 9\n1 4 4 13\n1 4 4 15", "output": "490902\n10598759" }, { "input": "1 1 1\n1 1 1 2", "output": "1...
4,000
1,945,600
0
31,437
474
Pillars
[ "binary search", "data structures", "dp", "sortings", "trees" ]
null
null
Marmot found a row with *n* pillars. The *i*-th pillar has the height of *h**i* meters. Starting from one pillar *i*1, Marmot wants to jump on the pillars *i*2, ..., *i**k*. (1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≤<=*n*). From a pillar *i* Marmot can jump on a pillar *j* only if *i*<=&lt;<=*j* and |*h**i*<=-<=*h**j*|<=≥<=*d*, where |*x*| is the absolute value of the number *x*. Now Marmot is asking you find out a jump sequence with maximal length and print it.
The first line contains two integers *n* and *d* (1<=≤<=*n*<=≤<=105, 0<=≤<=*d*<=≤<=109). The second line contains *n* numbers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=1015).
The first line should contain one integer *k*, the maximal length of a jump sequence. The second line should contain *k* integers *i*1,<=*i*2,<=...,<=*i**k* (1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≤<=*n*), representing the pillars' indices from the maximal length jump sequence. If there is more than one maximal length jump sequence, print any.
[ "5 2\n1 3 6 7 4\n", "10 3\n2 1 3 6 9 11 7 3 20 18\n" ]
[ "4\n1 2 3 5 \n", "6\n1 4 6 7 8 9 \n" ]
In the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5.
[]
46
0
0
31,441
912
Prime Gift
[ "binary search", "dfs and similar", "math", "meet-in-the-middle", "number theory", "two pointers" ]
null
null
Opposite to Grisha's nice behavior, Oleg, though he has an entire year at his disposal, didn't manage to learn how to solve number theory problems in the past year. That's why instead of Ded Moroz he was visited by his teammate Andrew, who solemnly presented him with a set of *n* distinct prime numbers alongside with a simple task: Oleg is to find the *k*-th smallest integer, such that all its prime divisors are in this set.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=16). The next line lists *n* distinct prime numbers *p*1,<=*p*2,<=...,<=*p**n* (2<=≤<=*p**i*<=≤<=100) in ascending order. The last line gives a single integer *k* (1<=≤<=*k*). It is guaranteed that the *k*-th smallest integer such that all its prime divisors are in this set does not exceed 1018.
Print a single line featuring the *k*-th smallest integer. It's guaranteed that the answer doesn't exceed 1018.
[ "3\n2 3 5\n7\n", "5\n3 7 11 13 31\n17\n" ]
[ "8\n", "93\n" ]
The list of numbers with all prime divisors inside {2, 3, 5} begins as follows: (1, 2, 3, 4, 5, 6, 8, ...) The seventh number in this list (1-indexed) is eight.
[ { "input": "3\n2 3 5\n7", "output": "8" }, { "input": "5\n3 7 11 13 31\n17", "output": "93" }, { "input": "2\n41 61\n66", "output": "550329031716248441" }, { "input": "1\n2\n55", "output": "18014398509481984" }, { "input": "7\n2 3 5 7 11 13 17\n2666471", "outp...
0
0
-1
31,448
435
Cardiogram
[ "implementation" ]
null
null
In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners: That is, a cardiogram is fully defined by a sequence of positive integers *a*1,<=*a*2,<=...,<=*a**n*. Your task is to paint a cardiogram by given sequence *a**i*.
The first line contains integer *n* (2<=≤<=*n*<=≤<=1000). The next line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000). It is guaranteed that the sum of all *a**i* doesn't exceed 1000.
Print *max* |*y**i*<=-<=*y**j*| lines (where *y**k* is the *y* coordinate of the *k*-th point of the polyline), in each line print characters. Each character must equal either «<=/<=» (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram. Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
[ "5\n3 1 2 5 1\n", "3\n1 5 1\n" ]
[ "/ \\ \n  / \\ /  \\ \n  /  \\ \n /  \\ \n \\ / \n", "/ \\ \n \\ \n \\ \n \\ \n \\ / \n" ]
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below. http://assets.codeforces.com/rounds/435/1.txt http://assets.codeforces.com/rounds/435/2.txt
[ { "input": "5\n3 1 2 5 1", "output": " /\\ \n /\\/ \\ \n / \\ \n/ \\ \n \\/" }, { "input": "3\n1 5 1", "output": "/\\ \n \\ \n \\ \n \\ \n \\/" }, { "input": "2\n1 1", "output": "/\\" }, { "input": "2\n2 1", "output...
124
5,324,800
3
31,460
903
Clear The Matrix
[ "bitmasks", "dp" ]
null
null
You are given a matrix *f* with 4 rows and *n* columns. Each element of the matrix is either an asterisk (*) or a dot (.). You may perform the following operation arbitrary number of times: choose a square submatrix of *f* with size *k*<=×<=*k* (where 1<=≤<=*k*<=≤<=4) and replace each element of the chosen submatrix with a dot. Choosing a submatrix of size *k*<=×<=*k* costs *a**k* coins. What is the minimum number of coins you have to pay to replace all asterisks with dots?
The first line contains one integer *n* (4<=≤<=*n*<=≤<=1000) — the number of columns in *f*. The second line contains 4 integers *a*1, *a*2, *a*3, *a*4 (1<=≤<=*a**i*<=≤<=1000) — the cost to replace the square submatrix of size 1<=×<=1, 2<=×<=2, 3<=×<=3 or 4<=×<=4, respectively. Then four lines follow, each containing *n* characters and denoting a row of matrix *f*. Each character is either a dot or an asterisk.
Print one integer — the minimum number of coins to replace all asterisks with dots.
[ "4\n1 10 8 20\n***.\n***.\n***.\n...*\n", "7\n2 1 8 2\n.***...\n.***..*\n.***...\n....*..\n", "4\n10 10 1 10\n***.\n*..*\n*..*\n.***\n" ]
[ "9\n", "3\n", "2\n" ]
In the first example you can spend 8 coins to replace the submatrix 3 × 3 in the top-left corner, and 1 coin to replace the 1 × 1 submatrix in the bottom-right corner. In the second example the best option is to replace the 4 × 4 submatrix containing columns 2 – 5, and the 2 × 2 submatrix consisting of rows 2 – 3 and columns 6 – 7. In the third example you can select submatrix 3 × 3 in the top-left corner and then submatrix 3 × 3 consisting of rows 2 – 4 and columns 2 – 4.
[ { "input": "4\n1 10 8 20\n***.\n***.\n***.\n...*", "output": "9" }, { "input": "7\n2 1 8 2\n.***...\n.***..*\n.***...\n....*..", "output": "3" }, { "input": "4\n10 10 1 10\n***.\n*..*\n*..*\n.***", "output": "2" }, { "input": "5\n4 3 4 4\n.....\n****.\n..***\n...**", "out...
61
0
0
31,468
48
Permutations
[ "greedy" ]
D. Permutations
1
256
A permutation is a sequence of integers from 1 to *n* of length *n* containing each number exactly once. For example, (1), (4,<=3,<=5,<=1,<=2), (3,<=2,<=1) are permutations, and (1,<=1), (4,<=3,<=1), (2,<=3,<=4) are not. There are many tasks on permutations. Today you are going to solve one of them. Let’s imagine that somebody took several permutations (perhaps, with a different number of elements), wrote them down consecutively as one array and then shuffled the resulting array. The task is to restore the initial permutations if it is possible.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105). The next line contains the mixed array of *n* integers, divided with a single space. The numbers in the array are from 1 to 105.
If this array can be split into several permutations so that every element of the array belongs to exactly one permutation, print in the first line the number of permutations. The second line should contain *n* numbers, corresponding to the elements of the given array. If the *i*-th element belongs to the first permutation, the *i*-th number should be 1, if it belongs to the second one, then its number should be 2 and so on. The order of the permutations’ numbering is free. If several solutions are possible, print any one of them. If there’s no solution, print in the first line <=-<=1.
[ "9\n1 2 3 1 2 1 4 2 5\n", "4\n4 3 2 1\n", "4\n1 2 2 3\n" ]
[ "3\n3 1 2 1 2 2 2 3 2\n", "1\n1 1 1 1 ", "-1\n" ]
In the first sample test the array is split into three permutations: (2, 1), (3, 2, 1, 4, 5), (1, 2). The first permutation is formed by the second and the fourth elements of the array, the second one — by the third, the fifth, the sixth, the seventh and the ninth elements, the third one — by the first and the eigth elements. Clearly, there are other splitting variants possible.
[ { "input": "9\n1 2 3 1 2 1 4 2 5", "output": "3\n1 1 1 2 2 3 1 3 1 " }, { "input": "4\n4 3 2 1", "output": "1\n1 1 1 1 " }, { "input": "4\n1 2 2 3", "output": "-1" }, { "input": "1\n1", "output": "1\n1 " }, { "input": "1\n2", "output": "-1" }, { "input...
390
9,420,800
3.787452
31,586
848
Shake It!
[ "combinatorics", "dp", "flows", "graphs" ]
null
null
A never-ending, fast-changing and dream-like world unfolds, as the secret door opens. A world is an unordered graph *G*, in whose vertex set *V*(*G*) there are two special vertices *s*(*G*) and *t*(*G*). An initial world has vertex set {*s*(*G*),<=*t*(*G*)} and an edge between them. A total of *n* changes took place in an initial world. In each change, a new vertex *w* is added into *V*(*G*), an existing edge (*u*,<=*v*) is chosen, and two edges (*u*,<=*w*) and (*v*,<=*w*) are added into *E*(*G*). Note that it's possible that some edges are chosen in more than one change. It's known that the capacity of the minimum *s*-*t* cut of the resulting graph is *m*, that is, at least *m* edges need to be removed in order to make *s*(*G*) and *t*(*G*) disconnected. Count the number of non-similar worlds that can be built under the constraints, modulo 109<=+<=7. We define two worlds similar, if they are isomorphic and there is isomorphism in which the *s* and *t* vertices are not relabelled. Formally, two worlds *G* and *H* are considered similar, if there is a bijection between their vertex sets , such that: - *f*(*s*(*G*))<==<=*s*(*H*); - *f*(*t*(*G*))<==<=*t*(*H*); - Two vertices *u* and *v* of *G* are adjacent in *G* if and only if *f*(*u*) and *f*(*v*) are adjacent in *H*.
The first and only line of input contains two space-separated integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=50) — the number of operations performed and the minimum cut, respectively.
Output one integer — the number of non-similar worlds that can be built, modulo 109<=+<=7.
[ "3 2\n", "4 4\n", "7 3\n", "31 8\n" ]
[ "6\n", "3\n", "1196\n", "64921457\n" ]
In the first example, the following 6 worlds are pairwise non-similar and satisfy the constraints, with *s*(*G*) marked in green, *t*(*G*) marked in blue, and one of their minimum cuts in light blue. In the second example, the following 3 worlds satisfy the constraints.
[ { "input": "3 2", "output": "6" }, { "input": "4 4", "output": "3" }, { "input": "7 3", "output": "1196" }, { "input": "31 8", "output": "64921457" }, { "input": "1 1", "output": "0" }, { "input": "10 2", "output": "141356" }, { "input": "3...
46
0
0
31,666
444
DZY Loves Physics
[ "greedy", "math" ]
null
null
DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: Once DZY got a graph *G*, now he wants to find a connected induced subgraph *G*' of the graph, such that the density of *G*' is as large as possible. An induced subgraph *G*'(*V*',<=*E*') of a graph *G*(*V*,<=*E*) is a graph that satisfies: - ; - edge if and only if , and edge ; - the value of an edge in *G*' is the same as the value of the corresponding edge in *G*, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.
The first line contains two space-separated integers *n* (1<=≤<=*n*<=≤<=500), . Integer *n* represents the number of nodes of the graph *G*, *m* represents the number of edges. The second line contains *n* space-separated integers *x**i* (1<=≤<=*x**i*<=≤<=106), where *x**i* represents the value of the *i*-th node. Consider the graph nodes are numbered from 1 to *n*. Each of the next *m* lines contains three space-separated integers *a**i*,<=*b**i*,<=*c**i* (1<=≤<=*a**i*<=&lt;<=*b**i*<=≤<=*n*; 1<=≤<=*c**i*<=≤<=103), denoting an edge between node *a**i* and *b**i* with value *c**i*. The graph won't contain multiple edges.
Output a real number denoting the answer, with an absolute or relative error of at most 10<=-<=9.
[ "1 0\n1\n", "2 1\n1 2\n1 2 1\n", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63\n" ]
[ "0.000000000000000\n", "3.000000000000000\n", "2.965517241379311\n" ]
In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
[ { "input": "1 0\n1", "output": "0.000000000000000" }, { "input": "2 1\n1 2\n1 2 1", "output": "3.000000000000000" }, { "input": "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63", "output": "2.965517241379311" }, { "input": "1 0\n734135", "output": "0.0...
373
307,200
3
31,728
47
Safe
[ "brute force" ]
D. Safe
5
256
Vasya tries to break in a safe. He knows that a code consists of *n* numbers, and every number is a 0 or a 1. Vasya has made *m* attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.
The first input line contains two integers *n* and *m* (6<=≤<=*n*<=≤<=35,<=1<=≤<=*m*<=≤<=10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow *m* lines, each containing space-separated *s**i* and *c**i* which correspondingly indicate Vasya’s attempt (a line containing *n* numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).
Print the single number which indicates how many possible code variants that do not contradict the *m* system responses are left.
[ "6 2\n000000 2\n010100 4\n", "6 3\n000000 2\n010100 4\n111100 0\n", "6 3\n000000 2\n010100 4\n111100 2\n" ]
[ "6\n", "0\n", "1\n" ]
none
[ { "input": "6 2\n000000 2\n010100 4", "output": "6" }, { "input": "6 3\n000000 2\n010100 4\n111100 0", "output": "0" }, { "input": "6 3\n000000 2\n010100 4\n111100 2", "output": "1" }, { "input": "6 1\n101011 2", "output": "15" }, { "input": "7 2\n1011111 2\n10011...
62
0
0
31,773