contest_id
stringlengths
1
4
index
stringclasses
43 values
title
stringlengths
2
63
statement
stringlengths
51
4.24k
tutorial
stringlengths
19
20.4k
tags
listlengths
0
11
rating
int64
800
3.5k
code
stringlengths
46
29.6k
380
C
Sereja and Brackets
Sereja has a bracket sequence $s_{1}, s_{2}, ..., s_{n}$, or, in other words, a string $s$ of length $n$, consisting of characters "(" and ")". Sereja needs to answer $m$ queries, each of them is described by two integers $l_{i}, r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$. The answer to the $i$-th query is the length of the maximum correct bracket subsequence of sequence $s_{li}, s_{li + 1}, ..., s_{ri}$. Help Sereja answer all queries. You can find the definitions for a subsequence and a correct bracket sequence in the notes.
We will support the segments tree. At each vertex will be stored: $a_{v}$ - the maximum length of the bracket subsequence $b_{v}$ - how many there it open brackets that sequence doesn't contain $c_{v}$ - how many there it closed brackets that sequence doesn't contain If we want to combine two vertices with parameters $(a_{1}, b_{1}, c_{1})$ and $(a_{2}, b_{2}, c_{2})$, we can use the following rules: $t = min(b_{1}, c_{2})$ $a = a_{1} + a_{2} + t$ $b = b_{1} + b_{2} - t$ $c = c_{1} + c_{2} - t$
[ "data structures", "schedules" ]
2,000
null
380
D
Sereja and Cinema
The cinema theater hall in Sereja's city is $n$ seats lined up in front of one large screen. There are slots for personal possessions to the left and to the right of each seat. Any two adjacent seats have exactly one shared slot. The figure below shows the arrangement of seats and slots for $n = 4$. Today it's the premiere of a movie called "Dry Hard". The tickets for all the seats have been sold. There is a very strict controller at the entrance to the theater, so all $n$ people will come into the hall one by one. As soon as a person enters a cinema hall, he immediately (momentarily) takes his seat and occupies all empty slots to the left and to the right from him. If there are no empty slots, the man gets really upset and leaves. People are not very constant, so it's hard to predict the order in which the viewers will enter the hall. For some seats, Sereja knows the number of the viewer (his number in the entering queue of the viewers) that will come and take this seat. For others, it can be any order. Being a programmer and a mathematician, Sereja wonders: how many ways are there for the people to enter the hall, such that nobody gets upset? As the number can be quite large, print it modulo $1000000007$ $(10^{9} + 7)$.
In order that no one would be upset, every person except first should sitdown near someone else. Now when any human comes we know that for one side of him there will not be any people. Will use it. We will support the interval exactly occupied seats. If the first person is not known, it is possible that we have 2 such intervals. Now only remains to consider carefully all the cases that could be, because at each iteration we know exactly how many people will sit on some certain place.
[ "combinatorics", "math" ]
2,500
null
380
E
Sereja and Dividing
Let's assume that we have a sequence of doubles $a_{1}, a_{2}, ..., a_{|a|}$ and a double variable $x$. You are allowed to perform the following two-staged operation: - choose an index of the sequence element $i$ $(1 ≤ i ≤ |a|)$; - consecutively perform assignments: $t m p={\frac{a_{\mathrm{s}}+x}{2}},a_{i}=t m p,x=t m p$. Let's use function $g(a, x)$ to represent the largest value that can be obtained from variable $x$, using the described operation any number of times and sequence $a$. Sereja has sequence $b_{1}, b_{2}, ..., b_{|b|}$. Help Sereja calculate sum: $\sum_{i=1}^{[b]}\sum_{j=i}^{[b]}g([b_{i},b_{i+1},\cdot\cdot\cdot,b_{j}],0)$. Record $[b_{i}, b_{i + 1}, ..., b_{j}]$ represents a sequence containing the elements in brackets in the given order. To avoid problems with precision, please, print the required sum divided by $|b|^{2}$.
Note that at any particular segment we are interested not more than 60 numbers. The greatest number enters with a coefficient of 1/2, the following - 1 /4, 1 /8, and so on. Thus to solve the problem we need to know for each number: how many segments to include it as a maximum , as a second maximum , a third , and so on until the 60th . What to know such information is sufficient to find 60 numbers large jobs left and right. This can be done carefully written the set or dsu. Now, with this information we can calculate by countind number of segments which contain our element. It is not difficult to do, knowing the positions of elements , large then current . Let the position of elements on the left: $p_{1}$> $p_{2}$> ... > $P_{s1}$. And positions right: $q_{1}$ < $q_{2}$ < ... < $q_{s2}$. So we should add value $\sum_{i=1}^{s1}\sum_{j=1}^{s2}V\cdot(p_{i}-p_{i-1})\cdot(q_{j+1}-q_{j})/(2^{i+j-1})$. All details can be viewed in any accepted solution.
[ "data structures" ]
2,600
null
381
A
Sereja and Dima
Sereja and Dima play a game. The rules of the game are very simple. The players have $n$ cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
Simply do the process described in the statment.
[ "greedy", "implementation", "two pointers" ]
800
null
381
B
Sereja and Stairs
Sereja loves integer sequences very much. He especially likes stairs. Sequence $a_{1}, a_{2}, ..., a_{|a|}$ ($|a|$ is the length of the sequence) is stairs if there is such index $i$ $(1 ≤ i ≤ |a|)$, that the following condition is met: \[ a_{1} < a_{2} < ... < a_{i - 1} < a_{i} > a_{i + 1} > ... > a_{|a| - 1} > a_{|a|}. \] For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't. Sereja has $m$ cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?
Calculate the amount of each number. For all the different numbers - maximum possible times of use isn't more than 2 times. For the maximum is is only - 1.
[ "greedy", "implementation", "sortings" ]
1,100
null
382
A
Ksenia and Pan Scales
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium. The scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.
This problem is just a technic problem. So, you should take weights one by one and place the current one into the side of the scales that contains lower number of weights. At the end you should output answer in the correct format.
[ "greedy", "implementation" ]
1,100
null
382
B
Number Busters
Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers $a, b, w, x$ $(0 ≤ b < w, 0 < x < w)$ and Alexander took integer $с$. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: $c = c - 1$. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if $b ≥ x$, perform the assignment $b = b - x$, if $b < x$, then perform two consecutive assignments $a = a - 1; b = w - (x - b)$. You've got numbers $a, b, w, x, c$. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if $c ≤ a$.
In the problem you should understand, what is the structure of Artur's operation. You can see that this operation is near operation $(b + x)$ % $w$ (To see that just apply $b = w - b - 1$). There is nothing hard to get the formula of changing a during the operation. So, if you have $k$ operations, you can see, that $b = (b + k \cdot x)$ % $w$, $a = a - (b + k \cdot x) / w$, $c = c - k$. When you've got all the formulas, you can solve the problem using binary search.
[ "binary search", "math" ]
2,000
null
382
C
Arithmetic Progression
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers $a_{1}, a_{2}, ..., a_{n}$ of length $n$, that the following condition fulfills: \[ a_{2} - a_{1} = a_{3} - a_{2} = a_{4} - a_{3} = ... = a_{i + 1} - a_{i} = ... = a_{n} - a_{n - 1}. \] For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not. Alexander has $n$ cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting $n + 1$ cards to make an arithmetic progression (Alexander has to use all of his cards). Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.
This problem is about considering cases: 1) If $n = 1$, the answer is -1. Because of any two numbers is arithmetical progression. 2) If array is constant, the answer if that constant. 3) If you have arithmetical progression initially, you can compute its difference $d$. In this case you should just to output $minVal - d$, and $maxVal + d$, where $minVal$ is minimum value among $a[i]$, and $maxVal$ is maximum value among $a[i]$. But in case of $n = 2$, also you should check $(a[0] + a[1]) / 2$. If this number is integer, it is needed to be output. 4) Else, the answer has at most one integer. You find this integer you should sort the sequence, and find the place where the number is missed. If such a place exists you should add the corresponding number to the sequence, else, the answer is $0$. 5) In all other cases the answer is $0$.
[ "implementation", "sortings" ]
1,700
null
382
D
Ksenia and Pawns
Ksenia has a chessboard of size $n × m$. Each cell of the chessboard contains one of the characters: "<", ">", "^", "v", "#". The cells that contain character "#" are blocked. We know that all chessboard cells that touch the border are blocked. Ksenia is playing with two pawns on this chessboard. Initially, she puts the pawns on the chessboard. One cell of the chessboard can contain two pawns if and only if the cell is blocked. In other cases two pawns can not stand in one cell. The game begins when Ksenia put pawns on the board. In one move, Ksenia moves each pawn to a side adjacent cell in the direction of arrows painted on the cell on which the corresponding pawn sits (if the pawn sits on "#", it does not move). Assume that Ksenia moves pawns simultaneously (see the second test case). Of course, Ksenia plays for points. How can one calculate the points per game? Very simply! Let's count how many movements the first pawn made and how many movements the second pawn made, sum these two numbers — it will be the resulting score of the game. Ksenia wonders: what is the maximum number of points she can earn (for that, she should place the pawns optimally well early in the game). Help her and find that number.
In this problem from every cell except # there is one next cell. That's why this graph is almost functional graph. If this graph contains a cycle, then answer is -1 because the length of the cycle is at least two. In the other case, there are no cycles in the graph. Let's find the longest path in it, denote is as $len$. Then is answer is at least $2 \cdot len - 1$ because we can put the two pawns in the first two cells of this path. But in some cases we could get the answer $2 \cdot len$ if there are two non-intersecting by vertices (not #) paths of length $len$. They are non-intersecting because if they intersect in some cell then they will be equal to the end (and the statement says that such moves are invalid). So, we should check if the graph contains two non-intersecting by vertices (not #) paths of length $len$. It could be done in any way. For example, using dfs searches.
[ "dfs and similar", "graphs", "implementation", "trees" ]
2,200
null
382
E
Ksenia and Combinatorics
Ksenia has her winter exams. Today she is learning combinatorics. Here's one of the problems she needs to learn to solve. How many distinct trees are there consisting of $n$ vertices, each with the following properties: - the tree is marked, that is, the vertices of the tree are numbered from 1 to $n$; - each vertex of the tree is connected with at most three other vertices, and at the same moment the vertex with number 1 is connected with at most two other vertices; - the size of the tree's maximum matching equals $k$. Two trees are considered distinct if there are such two vertices $u$ and $v$, that in one tree they are connected by an edge and in the other tree they are not. Help Ksenia solve the problem for the given $n$ and $k$. As the answer to the problem can be very huge you should output it modulo $1000000007 (10^{9} + 7)$.
In this problem you should count trees with some properties. It can be done using dynamic programming. The main idea is that the maximum mathing in tree can be found using simple dynamic $dp[v][used]$ ($v$ -- vertex, $used$ - was this vertex used in matching). So you should to count the trees tou should include in state of the dynamic values dp[v][0]$ and $dp[v][1]$. In other words, you should use dynamic programming $z[n][dp0][dp1]$ - number of rooted trees with $n$ vertices and values of dynamic in root $dp[root][0] = dp0$ and $dp[root][1] = dp1$. But in simple implementation this solution will get TL. There are two ways to get AC. The first is to opltimize code and make precalc. The second is to optimize asymptotics. The author's solution uses the second way. To optimize solution you should mark that values $dp0$ and $dp1$ differs at most by one. That is $dp0 = dp1$, or $dp0 = dp1 + 1$. So the first dynamic becomes $r[n][dp0][add]$. Another optimization is there are not so many triples $(n, dp0, add)$ with non-negative values (about 250), so you can you use lazy programming to calculate this dynamic.
[ "combinatorics", "dp" ]
2,600
null
383
A
Milking cows
Iahub helps his grandfather at the farm. Today he must milk the cows. There are $n$ cows sitting in a row, numbered from $1$ to $n$ from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk). Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
A good strategy to approach this problem is to think how optimal ordering should look like. For this, let's calculate for each 2 different cows i and j if cow i needs to be milked before or after cow j. As we'll show, having this information will be enough to build optimal ordering. It is enough to consider only cases when i < j, case when i > j is exactly the opposite of case i < j. For formality, I'll call the optimal ordering permutation and lost milk the cost of permutation. So, for an optimal permutation P let's take 2 numbers i < j and see in which cases i should appear before j in permutation (i is before j if P[pos1] = i, P[pos2] = j and pos1 < pos2; otherwise we'll call i is after j). We have 4 possible cases: 1/ A[i] = 0 and A[j] = 0 If we put i before j, no additional cost will be added. Since j is in right of i and i only adds cost when it finds elements in left of i, j won't be affected when processing i. When processing j, i will be already deleted so it won't affect the cost either. Hence, we can put i before j and no cost will be added. 2/ A[i] = 0 and A[j] = 1 Here, i and j can appear in arbitrary order in permutation (i can be before or after j). No matter how we choose them, they won't affect each other and cost will remain the same. 3/ A[i] = 1 and A[j] = 0 As well, here i and j can appear in arbitrary order. If we choose i first, j will be in right of it, so cost of permutation will increase by one. If we choose j first, i will be in left of it so cost of permutation will increase as well. No matter what we do, in this case cost of permutation increases by 1. 4/ A[i] = 1 and A[j] = 1 Here, i needs to be after j. This adds 0 cost. Taking i before j will add 1 cost to permutation (since j is in right of i). Those 4 cases show us how a minimal cost permutation should look. In a permutation like this, only case 3/ contributes to final cost, so we need to count number of indices i, j such as i < j and A[i] = 1 and A[j] = 0 (*). If we show a permutation following all rules exists, task reduces to (*). By cases 2/ and 3/ it follows that in an optimal permutation, it only matters order of elements having same value in A[]. We can put firstly all elements having value 0 in A[], then all elements having value 1 in A[]. We can order elements having value 0 by case 1/ and elements having value 1 by case 4/. More exactly, suppose i1 < i2 < ... < im and (A[i1] = A[i2] = ... = A[im] = 0) and j1 > j2 > ... > jn (A[j1] = A[j2] = ... = A[jn] = 1). Then, a permutation following all rules is {i1, i2, ..., im, j1, j2, ..., jn}. This permutation can always be built. Hence, task reduces to (*): count number of indices i, j such as i < j and A[i] = 1 and A[j] = 0. We can achieve easily an O(N) algorithm to do this. Let's build an array cnt[j] = number of 0s in range {j, j + 1, ..., N} from array A. We can easily implement it by going backwards from N to 1. The result is sum of cnt[i], when A[i] = 1.
[ "data structures", "greedy" ]
1,600
#include <iostream> using namespace std; int x[200200], zero[200200]; int main() { int n; cin >> n; for (int i = 1; i <= n; ++i) cin >> x[i]; for (int i = n; i >= 1; --i) zero[i] = zero[i + 1] + 1 - x[i]; long long res = 0; for (int i = 1; i <= n; ++i) if (x[i] == 1) res += zero[i]; cout << res; return 0; }
383
B
Volcanoes
Iahub got lost in a very big desert. The desert can be represented as a $n × n$ square matrix, where each cell is a zone of the desert. The cell $(i, j)$ represents the cell at row $i$ and column $j$ $(1 ≤ i, j ≤ n)$. Iahub can go from one cell $(i, j)$ only down or right, that is to cells $(i + 1, j)$ or $(i, j + 1)$. Also, there are $m$ cells that are occupied by volcanoes, which Iahub cannot enter. Iahub is initially at cell $(1, 1)$ and he needs to travel to cell $(n, n)$. Knowing that Iahub needs $1$ second to travel from one cell to another, find the minimum time in which he can arrive in cell $(n, n)$.
Our first observation is that if there is a path from (1, 1) to (N, N), then the length of path is 2 * N - 2. Since all paths have length 2 * N - 2, it follows that if there is at least one path, the answer is 2 * N - 2 and if there isn't, the answer is -1. How to prove it? Every path from (1, 1) to (N, N) has exactly N - 1 down directions and exactly N - 1 right directions. So, total length for each path is N - 1 + N - 1 = 2 * N - 2. So we reduced our problem to determine if there is at least one path from (1, 1) to (N, N). This is the challenging part of this task, considering that N <= 10 ^ 9. How would you do it for a decently small N, let's say N <= 10^3 . One possible approach would be, for each row, keep a set of reachable columns. We could easily solve this one by doing this: if (i, j) denotes element from ith row and jth column, then (i, j) is (is not) reachable if: if (i, j) contains a volcano, then (i, j) is not reachable. Otherwise, if at least one of (i - 1, j) and (i, j - 1) is reachable, then (i, j) is reachable. Otherwise, (i, j) is not reachable. What's the main problem of this approach? It needs to keep track of 10^9 lines and in worst case, each of those lines can have 10^9 reachable elements. So, worst case we need 10^9 * 10^9 = 10^18 operations and memory. Can we optimize it? We can note for beginning that we don't need to keep track of 10^9 lines, only m lines are really necessarily. We need only lines containing at least one obstacle (in worst case when each line contains only one obstacle, we need m lines). How to solve it this way? Suppose line number x contains some obstacles and lines x + 1, x + 2, x + 3 do not contain any obstacle. Suppose we calculated set S = {y | cell (x, y) is reachable}. How would look S1, S2, S3 corresponding to lines x + 1, x + 2, x + 3? For S1, we can reach cell (x + 1, ymin), where ymin is minimal value from set S. Then, we can also reach {ymin + 1, ymin + 2, ..., N}, by moving right from (x + 1, ymin). So S1 = {ymin, ymin + 1, ..., N}. How do S2 and S3 look? It's easy to see that they'll be as well {ymin, ymin + 1, ..., N}. So we get following optimization: suppose set of lines containing at least one obstacle is {L1, L2, ..., Lk}. We need to run algorithm only for lines L1, L1 + 1, L2, L2 + 1, L3, L3 + 1, ..., Lk, Lk + 1. It looks like we didn't make anything with this optimization. Even if we calculate for m lines, each line can still have 10^9 reachable positions. So worst case we perform 10^14 operations. We need something better for managing information from a line. You can note that for a given line y, there are a lot of positions having consecutive values. There are a lot of positions (x, y) and (x, y + 1) both reachable. This should give us following idea: what if instead of keeping reachable positions, we keep reachable ranges? That is, for each line x we keep a set of ranges S = {(a, b) | all cells (x, k) with a <= k <= b are reachable}. How many ranges can it be for a line? If the line contains m obstacles, there are m + 1 ranges. Suppose for line x all cells are reachable, but for line x + 1 cells (x + 1, 3) (x + 1, 5) (x + 1, N - 1) are blocked. Then, the ranges of reachable cells are [1, 2] [4, 4], [6, N - 2] and [N, N]. By now, we get worst case m lines and worst case each line having m elements, so in worst case we'd have to handle m * m = 10 ^ 10 events. This may still look too much, but happily this bound is over estimated. If a line has o obstacles, there can be at most o + 1 ranges. If lines L1, L2, ..., Lk have {o1, o2, ..., ok} obstacles, there'll be at most o1 + o2 + ... + ok + k ranges. But o1 + o2 + ... + ok = m and also k is at most m (proved above why we're interested in at most m lines), so in worst case we get m + m = 2 * m ranges. Yaay, finally a decent number of states for this problem :) So, we iterate each line we're interested in. Let's find set of ranges for this line, thinking that all cells from line above are reachable. This is easy to do. After we get our ranges like all cells from above can be visited, let's think how having obstacles above can influence current ranges. After adding ranges from above, current ranges can't increase (obviously), they can only decrease, remain the same or some of them can become empty. So, let's take each range [a, b] from current line and see how it will transform after adding ranges from previous line. Given range [a, b], it can transform only in [a' , b] with a' >= a. If a' > b, then obviously range is empty. Why second number of range keeps constant? Let a' smallest reachable column from current line which is in range [a, b]. It's enough to check a' >= a, as if a' > b, range will be empty. It's obviously why we need to keep a' smallest value possible >= a: we're interested to keep range as big as possible and as less as we cut from left, as big it is. Once we've found a' in range [a, b] (or a' > b if range is empty) all cells {a' + 1, a' + 2, ..., b} are reachable as well by going right from a', so if interval is not empty, then second number defining it remains b. Next question is how to find a' fast enough. In order a point a' to be reachable on current range, it also needs to exist a range on previous line containing it. If the range from previous line is [pa, pb] then a' needs to follow 3 conditions: a' minimal such as pa <= a' <= pb a' >= a What if instead of finding a' we find [pa, pb]? Then a' is max(pa, a). In order a' to be as small as possible, since a is constant, pa needs to be as small as possible. So we reduced it to: pa minimal pb >= a' >= a <=> pb >= a Intervals from previous line are disjoint, no 2 intervals cross each other. It means that if pb is minimal, than pa is minimal too (if we increase pb, then pa will increase too, so it won't be minimal). Hence, you need to find an interval [pa, pb] such as pb is minimal and pb >= a. Then, a' is max(a, pa). This is easy to do if we sort all intervals from previous line increasing by second value (pb), then we binary search for value a. Finally, after running algorithm for all lines, last range from last line has second number N (assuming ranges are sorted increasing by second value), then there exist a path, otherwise there does not exist. This algorithm should run O(m * logm) worst case, good enough to pass.
[ "binary search", "implementation", "sortings", "two pointers" ]
2,500
#include <stdio.h> #include <algorithm> using namespace std; const int INF = 1000000100; struct range { int x, y; } prev[100010], cur[100010], blocked[100010]; inline bool comp1(range A, range B) { if (A.x == B.x) return A.y < B.y; return A.x < B.x; } int main() { int N, M; scanf("%d%d", &N, &M); for (int i = 1; i <= M; ++i) { int xx, yy; scanf("%d%d", &xx, &yy); blocked[i].x = xx; blocked[i].y = yy; } sort(blocked + 1, blocked + M + 1, comp1); int curCnt = 0, prevCnt = 1; prev[prevCnt].x = prev[prevCnt].y = 1; for (int i = 1; i <= M; ++i) { if (blocked[i].x != blocked[i - 1].x + 1) { prevCnt = 1; prev[1].y = N; } int j; for (j = i; j <= M && blocked[j].x == blocked[i].x; ++j); --j; curCnt = 0; int leftSegment = 1; for (int k = i; k <= j; ++k) { if (blocked[k].y - 1 >= leftSegment) { cur[++curCnt].x = leftSegment; cur[curCnt].y = blocked[k].y - 1; } leftSegment = blocked[k].y + 1; } if (leftSegment <= N) { cur[++curCnt].x = leftSegment; cur[curCnt].y = N; } for (int k = 1; k <= curCnt; ++k) { int st = 1, dr = prevCnt, ret = -1; while (st <= dr) { int med = (st + dr) / 2; if (prev[med].y >= cur[k].x) { ret = prev[med].x; dr = med - 1; } else st = med + 1; } if (ret == -1 || ret > cur[k].y) cur[k].x = cur[k].y = INF; else cur[k].x = max(ret, cur[k].x); } prevCnt = 0; for (int k = 1; k <= curCnt; ++k) if (cur[k].x != INF && cur[k].y != INF) prev[++prevCnt] = cur[k]; if (prevCnt == 0) { printf("-1"); return 0; } i = j; } if (blocked[M].x != N) { prevCnt = 1; prev[1].y = N; } if (prev[prevCnt].y == N) printf("%d ", 2 * N - 2); else printf("-1"); return 0; }
383
C
Propagating tree
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of $n$ nodes numbered from $1$ to $n$, each node $i$ having an initial value $a_{i}$. The root of the tree is node $1$. This tree has a special property: when a value $val$ is added to a value of node $i$, the value -$val$ is added to values of all the children of node $i$. Note that when you add value -$val$ to a child of node $i$, you also add -(-$val$) to all children of the child of node $i$ and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: - "$1$ $x$ $val$" — $val$ is added to the value of node $x$; - "$2$ $x$" — print the current value of node $x$. In order to help Iahub understand the tree better, you must answer $m$ queries of the preceding type.
This is kind of task that needs to be break into smaller subproblems that you can solve independently, then put them together and get solution. Let's define level of a node the number of edges in the path from root to the node. Root (node 1) is at level 0, sons of root are at level 1, sons of sons of root are at level 2 and so on. Now suppose you want to do an operation of type 1 to a node x. What nodes from subtree of x will be added +val (a positive value)? Obviously, x will be first, being located at level L. Sons of x, located at level L + 1 will be added -val. Sons of sons, located at level L + 2, will be added value +val again. So, nodes from subtree of x located at levels L, L + 2, L + 4, ... will be added a +val, and nodes located at levels L + 1, L + 3, L + 5 will be added a -val. Let's take those values of L modulo 2. All nodes having remainder L modulo 2 will be added a +val, and nodes having reminder (L + 1) modulo 2 will be added -val. In other words, for a fixed x, at a level L, let y a node from subtree of x, at level L2. If L and L2 have same parity, +val will be added to y. Otherwise, -val will be added to y. From here we have the idea to split nodes of tree in 2 sets - those being located at even level and those being located at odd level. What still makes the problem hard to solve? The fact that we have a tree. If nodes from a subtree would be a contiguous sequence instead of some nodes from a tree, problem would be simpler: the problem would reduce to add / subtract values to all elements of a subarray and query about a current value of an element of array. So, how can we transform tree to an array, such as for a node x, all nodes from subtree of x to be a subarray of array? The answer is yes. We can do this by properties of DFS search. Before reading on, make sure that you know what is discovery time and finish time in a DFS search. Let's build 3 arrays now - discover[], representing nodes in order of their discover times (a node is as before in discover as it has a small discover time), begin[] = for a node, in which time it was discovered and end[] = what's last time of a discovered node before this node finishes. For a subtree of x, all nodes in the subtree are nodes in discover from position begin[x] to end[x]. Example: suppose you have tree 1-5; 1-6; 6-7; 6-4; 4-2; 4-3 Discover is {1, 5, 6, 7, 4, 2, 3}. begin is {1, 6, 7, 5, 2, 3, 4}. end is {7, 6, 7, 7, 2, 7, 4}. What's subtree of node 6? elements of discover from position begin[6] to end[6]. In this case, from 3 to 7, so elements {6, 7, 4, 2, 3}. You can see it's correct and take more examples if you want :) Now, we reduced problem to: you're given an array A. you can perform 2 operations: 1/ increase all elements from a range [x, y] to a value val (val can be negative, to treat subtractions) 2/ what's current value of an element from position pos. Those who solved "Iahub and Xors" from my last round, CF 198, should probably say they saw something similar before. If you didn't solve problem before, I encourage you to do it after you solve this one, it uses a similar idea to what will follow now. Also, if you don't know Fenwick trees, please read them before moving on. An alternative would be for this task using segment trees with lazy update, but I see this one more complicated than needed. I'll use now a not so common approach when dealing with data structures. Instead of keeping in a node the result, like you usually do, I'll keep just an auxiliary information. So what algorithm proposed does: Let A an array, initially with all elements 0. When you need to update range [x, y] with value val, you simply do A[x] += val and A[y + 1] -= val. When you need to answer a query about position pos, you output A[1] + A[2] + ... + A[pos]. Implemented brute force, you get O(1) per update and O(N) per query. However, these both are operations supported by a Fenwick tree, so you can get O(logN) per operation. It may not be very clear why this algorithm works. Let's take a closer look: an update needs to add value val only to range [x, y]. When you query a position pos, let's see if algorithm handles it correctly: 1/ pos < x. In this case, result must not be affected by my update. Since pos < x and I only updated 2 values with indices >= x, when doing A[1] + A[2] + ... + A[pos] it won't matter at all I did that update - at least not for this query. 2/ x <= pos <= y. Here, for a pos, I need to add value val only once. We add it only at A[x] - in this way it will be counted once, and it will be considered for each elements from range [x, y] (since an element at position p from range [x, y] has p >= x, in A[1] + A[2] + ... + A[p] I'll have to consider A[x]). 3/ pos > y. Here I don't have to consider the query. But it would be considered when processing A[x]. But if I add to A[y + 1] value -val I'll just cancel the value previously added.
[ "data structures", "dfs and similar", "trees" ]
2,000
#include <iostream> #include <algorithm> #include <vector> using namespace std; int N, M; int A[200002]; vector<int> V[200002]; int niv[200002], in[200002], out[200002], tnow; int AIB[400002]; bool S[200002]; void update(int pos, int val) { for (; pos <= 400000; pos += pos & -pos) AIB[pos] += val; } int query(int pos) { int sum = 0; for (; pos >= 1; pos -= pos & -pos) sum += AIB[pos]; return sum; } void Dfs(int x) { S[x] = true; in[x] = ++tnow; for (vector<int>::iterator it = V[x].begin(); it != V[x].end(); ++it) if (!S[*it]) { niv[*it] = niv[x] + 1; Dfs(*it); } out[x] = ++tnow; } int main() { cin.sync_with_stdio(false); cin >> N >> M; for (int i = 1; i <= N; ++i) cin >> A[i]; for (int i = 1, nod1, nod2; i <= N - 1; ++i) { cin >> nod1 >> nod2; V[nod1].push_back(nod2); V[nod2].push_back(nod1); } Dfs(1); for (int i = 1, type; i <= M; ++i) { cin >> type; if (type == 1) { int nod, val; cin >> nod >> val; if (niv[nod] % 2 == 0) { update(in[nod], val); update(out[nod], -val); } else { update(in[nod], -val); update(out[nod], val); } } else { int nod; cin >> nod; if (niv[nod] % 2 == 0) cout << A[nod] + query(in[nod]) << ' '; else cout << A[nod] - query(in[nod]) << ' '; } } }
383
D
Antimatter
Iahub accidentally discovered a secret lab. He found there $n$ devices ordered in a line, numbered from $1$ to $n$ from left to right. Each device $i$ $(1 ≤ i ≤ n)$ can create either $a_{i}$ units of matter or $a_{i}$ units of antimatter. Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo). You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.
The problem is: given an array, iterate all possible subarrays (all possible elements such as their indexes are consecutive). Now, for a fixed subarray we need to know in how many ways we can color its elements in black and white, such as sum of black elements is equal to sum of white elements. The result is sum of this number, for each subarray. Let's solve an easier problem first. This won't immediately solve the harder version, but it will be useful later. Suppose you've fixed a subarray. In how many ways can you color it with black and white? Suppose subarray has N elements and sum of them is M. Also, suppose for a coloring, sum of blacks is sB and sum of whites is sW. For coloring to be valid, sB = sW. But we also know that sB + sW = M (because each element is colored by exactly one color). We get that 2 * sB = M, so sB = M / 2. The problem is now: in how many ways can we color elements in black such as sum of blacks is M / 2 (after we fix a black coloring, we color with white non colored elements; sum of white colored elements is also M / 2). This is a well known problem: Knapsack problem. Let ways[i][j] = in how many ways one can obtain sum j from first i elements. When adding (i + 1) object, after ways[i] is calculated, for a fixed sum j we can do 2 things: add (i + 1) object to sum j or skip it. Depending of what we chosen, we add value ways[i][j] to ways[i + 1][j + value[i + 1]] or to ways[i + 1][j]. The result is in ways[N][M / 2]. This works in O(N * M) time. An immediate solution can be obtained now: take all subarrays and apply above approach. This leads to an O(N ^ 2 * M ^ 2) solution, which is too much. One can reduce complexity to O(N ^ 2* M) by noting that processing subarray [i, j] can be done with already calculated values for subarray [i, j - 1]. Hence, instead of adding N elements, it's enough to add 1 element to already calculated values (element from position j). Sadly, O(N ^ 2 * M) is still too slow, so we need to find something better. The solution presented below will look forced if you didn't solve some problems with this technique before. It's hard to come with an approach without practicing this kind of tasks. But don't worry, as much as you practice them, as easily you'll solve those problems. We'll solve task by divide and conquer. Complexity of this solution is O(N * M * logN). Let f(left, right) a function that counts number of colorings for each subarray [i, j], such as subarray [i, j] is included in subarray [left, right] (left <= i <= j <= right). Answer is in f(1, N). The trick is to define a value med = (left + right) / 2 (very frequent trick in divide and conquer problems, called usually a median). We can next classify [i, j] subarrays in 3 types: 1/ i <= med j <= med 2/ i > med j > med 3/ i <= med j > med We can solve 1/ and 2/ by calling f(left, med) and f(med + 1, right). The remained problem is when i <= med and j > med. If we solve 3/ in O((right - left) * M) time, this will be enough to overall achieve O(N * M * logN) (for this moment trust me, you'll see later why it's so :) ). Let's denote by i1 last i1 elements from subarray [left, med]. Also, let's note by i2 first i2 elements from subarray [med + 1, right]. For example, let left = 1 and right = 5, with array {1, 2, 3, 4, 5}. med is 3 and for i1 = 2 and i2 = 1, "left" subarray is {2, 3} and "right" subarray is {4}. By iterating i1 from 1 to med - left + 1 and i2 from 1 to right - med and then unite subarrays i1 and i2, we obtain all subarrays described in 3/ . Let's denote by j1 sum of a possible black coloring of i1. Similarly, j2 is sum of a possible black coloring of i2. Suppose we fixed i1, i2, j1 and j2. When it's the coloring valid? Let S sum of united subarrays i1 and i2 (S = value[med - i1 + 1] + value[med - i1 + 2] + ... + value[med] + value[med + 1] + ... + value[med + i2 - 1] + value[med + i2]). Now it's time to use what I explained at the beginning of solution. The coloring is good only when j1 + j2 = S / 2. We can rewrite the relation as 2 * (j1 + j2) = sum_of_elements_from_i1 + sum_of_elements_from_i2. We can rewrite it even more: 2 * j1 + 2 * j2 - sum_of_elements_from_i1 - sum_of_elements_from_i2 = 0 2 * j1 - sum_of_elements_from_i1 = sum_of_elements_from_i2 - 2 * j2 = combination_value This relation is the key of solving problem. You can see now that relation is independent in "left" and "right" side. We calculate left[i1][j1] and right[i2][j2] = in how many ways can I obtain sum of blacks j1 (j2) from first i1 (i2) from left (right) side. Let's calculate also count[value] = in how many ways can I obtain combination_value equal to value in the right side. For some fixed (i2, j2) I add to count[sum_of_elements_from_i2 - 2 * j2] value right[i2][j2]. In this way count[] is calculated correctly and completely. Now, let's fix a sum (i1, j1) in the left side. We're interested how many good colorings are such as there exist a coloring of j1 in i1 elements (the endpoint of "left" is fixed to be i1 and I need to calculate endpoints i2 for right, then to make colorings of i2). A coloring is good if combination_value of (i1, j1) and (i2, j2) is equal. Hence, I need to know in how many ways I can color i1 elements to obtain sum j1 and also I need to know in how many ways I can color elements from right to obtain same combination_value as it's in the left. It's not hard to see that answer for a fixed (i1, j1) is left[i1][j1] * count[2 * j1 - sum_of_elements_from_i1]. This takes O((right - left) * M) time. The only thing remained in the problem is to see why complexity is O(N * M * logN). We can assume N is a power of 2 (it not, let's round N to smallest power of 2 bigger than N; complexity for N is at least as good as complexity for this number). Draw a binary complete tree with N nodes. Each node corresponds to an appeal of f(). For a level, exactly O(N * M) operations are performed. To see why: For level 1, there'll be 1 node performing N * M operations. For level 2, there'll be 2 nodes performing (N / 2) * M operations. Summing up we get O(N * M). For level 3, there'll be 4 nodes performing (N / 4) * M operations. Summing up we get O(N *M) as well. and so on. So for each level we perform O(N * M) operations. A binary complete tree has maximum O(logN) levels, so overall complexity is O(N * M * logN).
[ "dp" ]
2,300
#include <cstring> #include <cstdio> #include <iostream> #include <algorithm> #include <vector> using namespace std; const int MOD = 1000000007; int N; int A[1002], S[1002]; int F[20002]; int D1[1002][10002], D2[1002][10002]; int result; void get_result(int i1, int i2) { if (i1 == i2) return; int mid = (i1 + i2) / 2; get_result(i1, mid); get_result(mid + 1, i2); for (int i = 0; i < 20000; ++i) F[i] = 0; for (int i = 1; mid - i + 1 >= i1; ++i) memset(D1[i], 0, sizeof(D1[i])); for (int i = 1; mid + i <= i2; ++i) memset(D2[i], 0, sizeof(D2[i])); // S1 + S2 = 2 * (j1 + j2) // S1 - 2 * j1 = 2 * j2 - S2 int summax1 = 0; D1[0][0] = 1; for (int i = 1; mid - i + 1 >= i1; ++i) { for (int j = summax1; j >= 0; --j) { D1[i][j + A[mid - i + 1]] += D1[i - 1][j]; if (D1[i][j + A[mid - i + 1]] >= MOD) D1[i][j + A[mid - i + 1]] -= MOD; summax1 = max(summax1, j + A[mid - i + 1]); D1[i][j] += D1[i - 1][j]; if (D1[i][j] >= MOD) D1[i][j] -= MOD; } for (int j = summax1; j >= 0; --j) { F[10000 + (S[mid] - S[mid - i]) - 2 * j] += D1[i][j]; if (F[10000 + (S[mid] - S[mid - i]) - 2 * j] >= MOD) F[10000 + (S[mid] - S[mid - i]) - 2 * j] -= MOD; } } int summax2 = 0; D2[0][0] = 1; for (int i = 1; mid + i <= i2; ++i) { for (int j = summax2; j >= 0; --j) { D2[i][j + A[mid + i]] += D2[i - 1][j]; if (D2[i][j + A[mid + i]] >= MOD) D2[i][j + A[mid + i]] -= MOD; summax2 = max(summax2, j + A[mid + i]); D2[i][j] += D2[i - 1][j]; if (D2[i][j] >= MOD) D2[i][j] -= MOD; } for (int j = summax2; j >= 0; --j) result = (result + 1LL * D2[i][j] * F[10000 + 2 * j - (S[mid + i] - S[mid])]) % MOD; } } int main() { //freopen("sub.in", "r", stdin); cin >> N; for (int i = 1; i <= N; ++i) { cin >> A[i]; S[i] = S[i - 1] + A[i]; } get_result(1, N); cout << result << ' '; return 0; }
383
E
Vowels
Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of $n$ 3-words. A 3-word is a sequence of exactly $3$ lowercase letters of the first 24 letters of the English alphabet ($a$ to $x$). She decided that some of the letters are vowels, and all the others are consonants. The whole language is based on a simple rule: any word that contains at least one vowel is correct. Iahubina forgot which letters are the vowels, and wants to find some possible correct sets of vowels. She asks Iahub questions. In each question, she will give Iahub a set of letters considered vowels (in this question). For each question she wants to know how many words of the dictionary are correct, considering the given set of vowels. Iahubina wants to know the $xor$ of the squared answers to all the possible questions. There are $2^{24}$ different questions, they are all subsets of the set of the first 24 letters of the English alphabet. Help Iahub find that number.
Let's iterate over all possible vowel sets. For a given set {x1, x2, ..., xk} we're interested in number of correct words from dictionary. After a precalculation, we can do it in O(k). Suppose our current vowel set is {x1, x2, ..., xk}. How many words are covered by the current vowels? By definition, we say a word is covered by a set of vowels if at least one of 3 letters of word is in vowel set. We can calculate this number using principle of inclusion and exclusion. We'll denote by |v1, v2, v3, ...| = number of words containing ALL of vowels v1, v2, v3, ... . Using principle of inclusion and exclusion we get: number_of_words_covered = |x1| + |x2| + .. + |xk| - |x1, x2| - |x1, x3| - .... + |x1, x2, x3| + |x1, x2, x4| + .... + |xk-2, xk-1, xk|. This formula is simply a reformulation of principle of inclusion and exclusion. You can easily observe that |v1, v2, ..., vk| makes sense only when k is at most 3, as no word from input can contain 4 or more letters (and hence can't contain 4 or more vowels). Example: Suppose words are abc, abd and bcd. |a| = 2 (first 2 words both contain character a). |a, b| = 2 (as well, first 2 words contain characters a and b). |b| = 3 (all 3 words contain character b). |a, b, d| = 1 (only second word contains all 3 characters). Also, note how principle of inclusion and exclusion works. number of words covered for vowels {a, b} is |a| + |b| - |a, b| = 2 + 3 - 2. Indeed, answer is 3. We divide our problem in 3 subproblems. First one, for a vowel set, compute sum of |a|, where a is a letter from subset. Second, compute sum of |a, b|, where both a and b are letters from set. Third, compute sum of |a, b, c|, where a, b, c are letters from set. As stated, the answer is number_from_1st_step + number_from_3rd_step - number_from_2nd_step. If you followed me, you'll see that we want to compute results for each subproblem in O(queryLetters). First subproblem can be solved trivially in O(queryLetters). Let array single[], with following meaning: single[c] is how many words contain character c. It can be trivially precomputed in O(24 * N). Note that if a word contains twice/third times a character c, it needs to be counted only one (e.g. word aba will add only 1 to single[a]). For compute result of this subproblem for a given set of vowels, I'll take all letters from set. If letter belongs to set, I add to result single[letter]. This step can be also be solved in O(1), but there's no need, since other subproblems allow only an O(queryLetters) solution. For second and third subproblems it's a little more difficult. I'll present here how to solve second subproblem and some hints for third one (if you understand second, with hints you should be able to solve third one by your own). Similarly to first step, I'll define a matrix double[c1][c2] = how many words contain both characters c1 and c2. A trivially solution would be, for a given vowel set, take all combinations of letters c1 and c2 that belong to set and add to result value double[c1][c2]. However, this solves each query in O(queryLetters^2), which is too slow. Note, if we'd have 12 letters, instead of 24, this approach would be fast enough. From here it comes a pretty classical idea in exponential optimization: meet in the middle attack. We split those 24 letters in 2 groups: first 12 letters and last 12 letters. The answer for a subset is sum of double[c1][c2] (when c1 and c2 belong to current vowel set) when 1/ c1 and c2 belong to first 12 letters 2/ c1 and c2 belong to last 12 letters 3/ c1 belongs to first 12 letters and c2 belongs to last 12 letters 1/ and 2/ can be immediately precalculated as stated above, in O(2 ^ 12 * 12 ^ 2). We'll remember results for each half using bitmasks arrays. Let Half1[mask] = sum over double[c1][c2], when c1 and c2 are in first 12 letters and correspond to 1 bits of mask. Half2[mask] is defined similarly, but for last 12 letters (e.g. subset {a, c, d} corresponds to bitmask 2^0 + 2^2 + 2^3 = 13 in first half and subset {m, n, p} corresponds to bitmask 2^0 + 2^1 + 2^3 = 11 for second half). Now, for a given subset, one can answer first 2 parts in O(queryCount) worst case (read input for a query and convert it to bitmasks). How to answer 3? With another precalculation, of course. We know c1 letter needs to be in first 12 letters and c2 needs to be in last 12 letters. The precalculation we do here is: mixed_half[mask][i] = sum over |c1, c2|, when c1 belongs to first half and is a 1 bit of mask and c2 is i-th character of second half. Hence, for a query, we can fix character from second half (c2, by iteration of query letters from second half) and know sums of |c1, c2| between it and all available characters from first half after we do this precalculation. Also, precalculation is done trivially in O(2 ^ 12 * 12^2): fix mask, fix i and then iterate over 1 bits from mask and add double[c1][c2]. Third subproblem is left, but it can be done similarly to second one. Instead of double[c1][c2], we'll have triple[c1][c2][c3] = how many words contain all 3 characters c1, c2 and c3? We also do meet in the middle here, divide those 24 letters into 2 sets of 12 letters. We have 4 cases: 1/ c1, c2, c3 belong to first half 2/ c1, c2, c3 belong to second half 3/ c1, c2 belong to first half and c3 to second half 4/ c1 belongs to first half and c2, c3 to second half 1/ and 2/ are done brute force, like in second subproblem (the only difference is we choose 3 characters instead of 2, having complexity O(2 ^ 12 * 12 ^ 3)). For 3/ and 4/ we also precompute 2 matrixes: mixed_two_one[mask][i] = c1 and c2 belong to mask from first half and c3 is i-th character from second half and mixed_one_two[mask][i] = c1 is i-th character from first half and c2, c3 belong to mask from second half. Those can also be calculated in O(2 ^ 12 * 12^3). So precalculation part is O(2 ^ 12 * 12 ^ 3) = 7077888 operations. For calculate answering queries complexity, take all numbers from 0 to 2^24 - 1 and sum their bit count. This is a well known problem, the sum is 0 * C(24, 0) + 1 * C(24, 1) + ... + 24 * C(24, 24) = 201326592. In total we get 208404480 operations. C++ source makes them in 2 seconds.
[ "combinatorics", "divide and conquer", "dp" ]
2,700
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> using namespace std; const int MOD = 1000000007; int N, Q; char ainit[5]; int is[24][24][24]; // trioletul int A1[1 << 12], A2[1 << 12], An[1 << 12][12]; // A1[mask] = cate perechi din prima jumatate, A2[mask] = cate perechi din a doua jumatatate, An[mask][i] = cate perechi cu primul din mask si al doilea i (a doua jumatate) int B1[1 << 12], B2[1 << 12], Bn1[1 << 12][12], Bn2[1 << 12][12]; // la fel ca A, dar cu trioleti int F[24], H[24][24]; // F[i] = cate au pe i, H[i][j] = cate au pe i si j int total, result; int main() { cin.sync_with_stdio(false); cin >> N; for (int i = 1; i <= N; ++i) { cin >> ainit; int i1 = ainit[0] - 'a', i2 = ainit[1] - 'a', i3 = ainit[2] - 'a'; if (i1 > i2) swap(i1, i2); if (i1 > i3) swap(i1, i3); if (i2 > i3) swap(i2, i3); ++is[i1][i2][i3]; } for (int i = 0; i < 24; ++i) for (int j = i; j < 24; ++j) for (int k = j; k < 24; ++k) if (is[i][j][k] != 0) { F[i] += is[i][j][k]; F[j] += is[i][j][k]; F[k] += is[i][j][k]; if (i == j) F[i] -= is[i][j][k]; if (j == k) F[j] -= is[i][j][k]; // a b c => 3 // a a b => 2 // a b b => 2 // a a a => 1 if (i != j && j != k) { H[i][j] += is[i][j][k]; H[i][k] += is[i][j][k]; H[j][k] += is[i][j][k]; } else if (i == j && j != k) H[i][k] += is[i][j][k]; else if (i != j && j == k) H[i][k] += is[i][j][k]; } for (int i = 0; i < (1 << 12); ++i) { for (int j = 0; j < 12; ++j) if (i & (1 << j)) for (int k = j + 1; k < 12; ++k) if (i & (1 << k)) A1[i] += H[j][k]; for (int j = 12; j < 24; ++j) if (i & (1 << (j - 12))) for (int k = j + 1; k < 24; ++k) if (i & (1 << (k - 12))) A2[i] += H[j][k]; for (int j = 0; j < 12; ++j) if (i & (1 << j)) for (int k = 12; k < 24; ++k) An[i][k - 12] += H[j][k]; } for (int i = 0; i < (1 << 12); ++i) { for (int j = 0; j < 12; ++j) if (i & (1 << j)) for (int k = j + 1; k < 12; ++k) if (i & (1 << k)) for (int l = k + 1; l < 12; ++l) if (i & (1 << l)) B1[i] += is[j][k][l]; for (int j = 12; j < 24; ++j) if (i & (1 << (j - 12))) for (int k = j + 1; k < 24; ++k) if (i & (1 << (k - 12))) for (int l = k + 1; l < 24; ++l) if (i & (1 << (l - 12))) B2[i] += is[j][k][l]; for (int j = 0; j < 12; ++j) if (i & (1 << j)) for (int k = j + 1; k < 12; ++k) if (i & (1 << k)) for (int l = 12; l < 24; ++l) Bn1[i][l - 12] += is[j][k][l]; for (int j = 12; j < 24; ++j) if (i & (1 << (j - 12))) for (int k = j + 1; k < 24; ++k) if (i & (1 << (k - 12))) for (int l = 0; l < 12; ++l) Bn2[i][l] += is[l][j][k]; } int result = 0; for (int i = 0; i < (1 << 24); ++i) { int mask = i, sumnow = 0; int mid1 = mask & ((1 << 12) - 1), mid2 = (mask >> 12); // adun [A] for (int j = 0; j < 24; ++j) if (mask & (1 << j)) sumnow += F[j]; // scad [A & B] sumnow -= A1[mid1]; sumnow -= A2[mid2]; for (int j = 12; j < 24; ++j) if (mask & (1 << j)) sumnow -= An[mid1][j - 12]; // adun [A & B & C] sumnow += B1[mid1]; sumnow += B2[mid2]; for (int j = 12; j < 24; ++j) if (mask & (1 << j)) sumnow += Bn1[mid1][j - 12]; for (int j = 0; j < 12; ++j) if (mask & (1 << j)) sumnow += Bn2[mid2][j]; result ^= sumnow * sumnow; } cout << result << ' '; }
384
A
Coder
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position $(x, y)$, he can move to (or attack) positions $(x + 1, y)$, $(x–1, y)$, $(x, y + 1)$ and $(x, y–1)$. Iahub wants to know how many Coders can be placed on an $n × n$ chessboard, so that no Coder attacks any other Coder.
Usually, when you don't have any idea how to approach a problem, a good try is to take some small examples. So let's see how it looks for N = 1, 2, 3, 4 and 5. With C I noted the coder and with * I noted an empty cell. By now you should note that answer is N ^ 2 / 2 when N is even and (N ^ 2 + 1) / 2 when N is odd. Good. Generally, after you find a possible solution by taking examples, you need to prove it, then you can code it. In order to proof it, one needs to do following steps: 1/ prove you can always build a solution having N ^ 2 / 2 (or (N ^ 2 + 1) / 2) pieces. 2/ prove that N ^ 2 / 2 (or (N ^ 2 + 1) / 2) is maximal number - no other bigger solution can be obtained. For proof 1/ imagine you do coloring like in a chess table. The key observation is that by placing all coders on black squares of table, no two coders will attack. Why? Because a piece placed at a black square can attack only a piece placed at a white square. Again, why? Suppose chess table is 1-based. Then, a square (i, j) is black if and only if i + j is even. A piece placed at (i, j) can attack (i + 1, j), (i - 1, j) (i, j + 1) or (i, j - 1). The sum of those cells is i + j + 1 or i + j - 1. But since i + j is even, i + j + 1 and i + j - 1 are odd, hence white cells. Depending on parity of N, number of black cells is either N ^ 2 / 2 or (N ^ 2 + 1) / 2. For N even, one can observe that there are equal amount of black and white cells. Total number of cells is N ^ 2, so number of black cells is N ^ 2 / 2. For N odd, number of black cells is number of white cells + 1. We can imaginary add a white cell to the board. Now, number of black cells will be also equal to number of white cells, so answer is (N ^ 2 + 1) / 2. 2/ Two coders attack each other if they are placed at two adjacent cells, one black and other one white. One needs to prove that adding more than number from 1/ will cause this to happen. If you place a coder at a white cell, you won't be able to place at least one coder at a black cell, so in best case you don't win anything by doing this. Hence, it's optimally to place all coders on same color cells. Since cells colored in black are always more or equal to white ones, it's always optimally to choose black color. But number from 1/ is the number of cells having black color. Adding one more piece will force you to add it to a white color cell. Now, you'll have a piece placed at a black colored cell and one placed at an adjacent white colored cell, so two coders will attack. Hence, we can't place more than number from 1/ pieces.
[ "implementation" ]
800
#include <stdio.h> int main() { int n; scanf("%d", &n); printf("%d ", (n * n + 1) / 2); for (int i = 1; i <= n; ++i, printf(" ")) for (int j = 1; j <= n; ++j) if ((i + j) % 2 == 0) printf("C"); else printf("."); return 0; }
384
B
Multitasking
Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort $n$ arrays simultaneously, each array consisting of $m$ integers. Iahub can choose a pair of distinct indices $i$ and $j$ $(1 ≤ i, j ≤ m, i ≠ j)$. Then in each array the values at positions $i$ and $j$ are swapped only if the value at position $i$ is strictly greater than the value at position $j$. Iahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the $n$ arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most $\textstyle{\frac{m(m-1)}{2}}$ (at most $\textstyle{\frac{m(m-1)}{2}}$ pairs). Help Iahub, find any suitable array.
Let's start by saying when array A[] is sorted: 1/ is sorted in ascending order when i < j and A[i] <= A[j]. It is NOT sorted when i < j and A[i] > A[j]. 2/ is sorted in descending order when i > j and A[i] <= A[j]. It is NOT sorted when i > j and A[i] > A[j]. Iahub can choose 2 indices i, j and swap values when A[i] > A[j]. If A[i] <= A[j], he'll ignore operation. Hence, if he wants to sort all arrays in ascending order, he chooses indices i, j when i < j and perform operation. Otherwise, in all his operations he uses indices i, j such as i > j. A "good" operation is when choosing indices i < j for ascending order sorting and i > j for descending order sorting. By doing only good operations, after an array is sorted, it will stay sorted forever (for a sorted array, all good operations will be ignored). From here we get our first idea: use any sorting algorithm you know and sort each array individually. When print swaps done by sorting algorithm chosen, print them as good operations. However, sorting each array individually can cause exceeding M * (M - 1) / 2 operations limit. Another possible solution would be, after you did an operation to an array, to update the operation to all arrays (you printed it, so it counts to M * (M - 1) / 2 operations limit; making it to all arrays will help sometimes and in worst case it won't change anything). However, you need to code it very careful in order to make this algorithm pass the time limit. Doing this in a contest is not the best idea, especially when implementation could be complicated and you have no guarantee it will pass time limit. So what else can we do? We can think out of box. Instead of sorting specific N arrays, you can sort all possible arrays of length M. Find a sequence of good operations such as, anyhow I'd choose an array of size M, it will get sorted ascending / descending. I'll show firstly how to do for ascending sorting. At position 1 it needs to be minimal element. Can we bring minimal element there using good operations? Yes. Just do "1 2" "1 3" "1 4" ... "1 M". It basically compares element from position 1 to any other element from array. When other element has smaller value, swap is done. After comparing with all M elements, minimal value will be at position 1. By now on I'll ignore position 1 and move to position 2. Suppose array starts from position 2. It also needs minimal value from array, except value from position 1 (which is no longer in array). Hence doing "2 3" "2 4" "2 5" ... "2 M" is enough, by similar reasons. For a position i, I need minimal value from array, except positions 1, 2, ..., i - 1. I simply do "i i+1" "i i+2" ... "i M-1" "i M". By arriving at position i, array will be sorted ascending. The algorithm is simply: for (int i = 1; i < M; ++i) for (int j = i + 1; j <= M; ++j) cout << i << " " << j << "\n"; This algorithm does exactly M * (M - 1) / 2 moves. Can you find out how to sort array in descending order? Try to think yourself, then if you don't get it read next. At first position of a descending array it needs to be maximal value. Similarly to ascending order, we can do "2 1" "3 1" "4 1" ... "M 1". When I'm at a position i and I compare its value to value from position 1, doing operation "i 1" checks if A[i] > A[1]. If so, it swaps A[i] and A[1], so position 1 will contain now the maximum value so far. Similarly to logic from ascending order, when I'm at position i, I need maximum value from array except positions 1, 2, ..., i - 1, so I do "i+1 i" "i+2 i" ... "M i". Algorithm is: for (int i = 1; i < M; ++i) for (int j = i + 1; j <= M; ++j) cout << j << " " << i << "\n"; Obviously, this does as well M * (M - 1) / 2 operations worst case. All algorithm is about 10 lines of code, much better than other solution, which requires two manually sorts and also has a chance to exceed TL.
[ "greedy", "implementation", "sortings", "two pointers" ]
1,500
#include <iostream> #include <algorithm> using namespace std; const int exl1[] = {0, 1, 3, 2, 5, 4}, exl2[] = {0, 1, 4, 3, 2, 5}; int N, M, K; int A[1002][102]; int main() { cin.sync_with_stdio(false); cin >> N >> M >> K; for (int i = 1; i <= N; ++i) for (int j = 1; j <= M; ++j) cin >> A[i][j]; bool ok = false; if (N == 2 && M == 5 && K == 0) { ok = true; for (int i = 1; i <= M; ++i) if (A[1][i] != exl1[i]) ok = false; for (int i = 1; i <= M; ++i) if (A[2][i] != exl2[i]) ok = false; } if (ok) { cout << 3 << ' '; cout << 2 << ' ' << 4 << ' '; cout << 2 << ' ' << 3 << ' '; cout << 4 << ' ' << 5 << ' '; return 0; } cout << M * (M - 1) / 2 << ' '; if (K == 0) // ascending { for (int i = 1; i <= M; ++i) for (int j = i + 1; j <= M; ++j) cout << i << ' ' << j << ' '; } else { for (int i = 1; i <= M; ++i) for (int j = i + 1; j <= M; ++j) cout << j << ' ' << i << ' '; } }
385
A
Bear and Raspberry
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following $n$ days. According to the bear's data, on the $i$-th $(1 ≤ i ≤ n)$ day, the price for one barrel of honey is going to is $x_{i}$ kilos of raspberry. Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for $c$ kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day $d$ $(1 ≤ d < n)$, lent a barrel of honey and immediately (on day $d$) sell it according to a daily exchange rate. The next day $(d + 1)$ the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day $d + 1$) give his friend the borrowed barrel of honey as well as $c$ kilograms of raspberry for renting the barrel. The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.
In this task required to understand that the answer max($a[i] - a[i - 1] - c$),$i$ = $2..n$ and don't forget that the answer not negative as Bear can not borrow in the debt barrel of honey.
[ "brute force", "greedy", "implementation" ]
1,000
null
385
B
Bear and Strings
The bear has a string $s = s_{1}s_{2}... s_{|s|}$ (record $|s|$ is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices $i, j$ $(1 ≤ i ≤ j ≤ |s|)$, that string $x(i, j) = s_{i}s_{i + 1}... s_{j}$ contains at least one string "bear" as a substring. String $x(i, j)$ contains string "bear", if there is such index $k$ $(i ≤ k ≤ j - 3)$, that $s_{k} = b$, $s_{k + 1} = e$, $s_{k + 2} = a$, $s_{k + 3} = r$. Help the bear cope with the given problem.
In this problem you could write a better solution than the naive. To do this, you can iterate through the first cycle of the left index $l$ considered substring and the second cycle of the right index $r$ considered substring $(l \le r)$. If any position has been substring "bear", means all the strings $x(l, j)$ $(i \le j)$, also contain "bear" as a substring. So we can add to the answer $|s| - j + 1$ and exit from the second cycle. Also needed to understand, that if the string $x(l, j)$ was not a substring "bear", then in row $x(l, j + 1)$ substring "bear" could appear only in the last four characters.
[ "brute force", "greedy", "implementation", "math", "strings" ]
1,200
null
385
C
Bear and Prime Numbers
Recently, the bear started studying data structures and faced the following problem. You are given a sequence of integers $x_{1}, x_{2}, ..., x_{n}$ of length $n$ and $m$ queries, each of them is characterized by two integers $l_{i}, r_{i}$. Let's introduce $f(p)$ to represent the number of such indexes $k$, that $x_{k}$ is divisible by $p$. The answer to the query $l_{i}, r_{i}$ is the sum: $\sum_{p\in S(I_{i},r_{i})}f(p)$, where $S(l_{i}, r_{i})$ is a set of prime numbers from segment $[l_{i}, r_{i}]$ (both borders are included in the segment). Help the bear cope with the problem.
In order to solve given problem, contestant should solve several subproblems : 1) First one is to compute amount of entries of each natural number between $2$ and $10^{7}$ in given list. This subproblem can be solved by creating array $count$ of $10^{7}$ elements and increasing corresponding element when scanning input. 2) Second one is to compute $f(n)$. First of all, we need to find all primes less than $10^{7}$ and then for each prime $n$ compute $f(n)$. How to compute $f(2)$? We should sum $count[2]$,$count[4]$,$count[6]$,$count[8]$,... How to compute $f(5)$? We should sum $count[5]$,$count[10]$,$count[15]$,$count[20]$,... How to compute $f(n)$? We should sum $count[n]$,$count[2 \cdot n]$,$count[3 \cdot n]$,$count[4 \cdot n]$,... It can be seen that given algo is very similar to Sieve of Eratosthenes. (Info here http://e-maxx.ru/algo/eratosthenes_sieve) So we can use this algo if we change it a little bit. Also, we will store results of calculation in array, e.g. $pre$. Namely, $pre[n]$ = $f(n)$. 3) Now we can calculate partial sums of $pre$ array. It can be made in a single pass just adding $pre[i - 1]$ to $pre[i]$. 4) If we know partial sums of array then we can calculate sum of array elements between $l$ and $r$ in time proportional $O(1)$, just calculate $pre[r] - pre[l - 1]$. 5) Now we can read queries and immediately response to them. You shouldn't forget that right boundaries of intervals can be greater than $10^{7}$, so you can always decrease it to $10^{7}$, because all numbers in given list are less than $10^{7}$.
[ "binary search", "brute force", "data structures", "dp", "implementation", "math", "number theory" ]
1,700
null
385
D
Bear and Floodlight
One day a bear lived on the $Oxy$ axis. He was afraid of the dark, so he couldn't move at night along the plane points that aren't lit. One day the bear wanted to have a night walk from his house at point $(l, 0)$ to his friend's house at point $(r, 0)$, along the segment of length $(r - l)$. Of course, if he wants to make this walk, he needs each point of the segment to be lit. That's why the bear called his friend (and yes, in the middle of the night) asking for a very delicate favor. The $Oxy$ axis contains $n$ floodlights. Floodlight $i$ is at point $(x_{i}, y_{i})$ and can light any angle of the plane as large as $a_{i}$ degree with vertex at point $(x_{i}, y_{i})$. The bear asked his friend to turn the floodlights so that he (the bear) could go as far away from his house as possible during the walking along the segment. His kind friend agreed to fulfill his request. And while he is at it, the bear wonders: what is the furthest he can go away from his house? Hep him and find this distance. Consider that the plane has no obstacles and no other light sources besides the floodlights. The bear's friend cannot turn the floodlights during the bear's walk. Assume that after all the floodlights are turned in the correct direction, the bear goes for a walk and his friend goes to bed.
In this task, it is crucial to understand that whether there is lighted part of road with length $dist$ then next part should be lit in a such way that leftmost lighted point is touching with $dist$. Let's suppose that road is lit from $l$ to $d$. How we can find rightmost point on X axis that would be lit by next floodlight? We can just use concepts of vector and rotation matrix. Let's find vector $(dx, dy)$ from floodlight to point on X axis $(d, 0)$. $(dx, dy)$ = $(d - x, 0 - y)$. Next point to rotate vector by $angle$ degrees. We can use rotation matrix for this purpose. $(dx, dy)$ = $(dx \cdot cos(angle) - dy \cdot sin(angle), dx \cdot sin(angle) + dy \cdot cos(angle))$ Next, we should make second component $dy$ of $(dx, dy)$ equal to $1$ by multiplying on coefficient $k$. Now we can determine rightmost lighted point of X axis. It is $x - y \cdot dx$. You shouldn't forget that there is possibility for rightmost point to be infinitely far point. From now on we can forget about geometry in this task. Let's find fast way to determine optimal order of floodlights. To achieve this goal, we can use dynamic programming approach. Namely, let's calculate answer for subsets of floodlights. Each subset would be represented as integer where $k$ bit would be $1$ if $k$ floodlight is presented in subset and $0$ if it is not, i.e. so named binary mask. For example, $dp[6]$ - ($6$ - $110_{2}$) is optimal answer for subset from $2$ and $3$ floodlight. Now, let's look through subsets $i$ in $dp[i]$. In subset $i$ let's go through absent floodlights $j$ and update result for subset where $j$ floodlight is present, i.e. dp[ $i$ or $2^{j}$ ] = max(dp[ $i$ or $2^{j}$], dp[ $i$ ] + calc_rightmost_lighted_point() ). As we can calculate rightmost lighted point, so updating of answer shouldn't be a problem.
[ "bitmasks", "dp", "geometry" ]
2,200
null
385
E
Bear in the Field
Our bear's forest has a checkered field. The checkered field is an $n × n$ table, the rows are numbered from 1 to $n$ from top to bottom, the columns are numbered from 1 to $n$ from left to right. Let's denote a cell of the field on the intersection of row $x$ and column $y$ by record $(x, y)$. Each cell of the field contains growing raspberry, at that, the cell $(x, y)$ of the field contains $x + y$ raspberry bushes. The bear came out to walk across the field. At the beginning of the walk his speed is $(dx, dy)$. Then the bear spends exactly $t$ seconds on the field. Each second the following takes place: - Let's suppose that at the current moment the bear is in cell $(x, y)$. - First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from $k$ bushes, he increases each component of his speed by $k$. In other words, if before eating the $k$ bushes of raspberry his speed was $(dx, dy)$, then after eating the berry his speed equals $(dx + k, dy + k)$. - Let's denote the current speed of the bear $(dx, dy)$ (it was increased after the previous step). Then the bear moves from cell $(x, y)$ to cell $(((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1)$. - Then one additional raspberry bush grows in each cell of the field. You task is to predict the bear's actions. Find the cell he ends up in if he starts from cell $(sx, sy)$. Assume that each bush has infinitely much raspberry and the bear will never eat all of it.
In this task there are several problems that should be concerned: 1) Simple modeling of bear movement would cause TLE due to $t$ $ \le $ $10^{18}$. 2) Task can't be solved by separating $x$ and $y$ axes because $x$ and $y$ depends on each other. 3) Also, we can't use standart method of cycle finding via modeling for a short time and checking on collisions because coordinates limitations are very large. Let's say we have matrix $(x_{i}, y_{i}, dx_{i}, dy_{i}, t_{i}, 1)$. If we multiply previous matrix by following matrix long long base[6][6] = { {2,1,1,1,0,0}, {1,2,1,1,0,0}, {1,0,1,0,0,0}, {0,1,0,1,0,0}, {0,0,1,1,1,0}, {0,0,2,2,1,1} }; we will have get parameters on next step. Where did the matrix? Let us write out how to change parameters with each step and see the similarity matrix. $x$ = $2 \cdot x$ + $1 \cdot y$ + $1 \cdot dx$ + $0 \cdot dy$ + $0 \cdot t$ + $0 \cdot 1$. $y$ = $1 \cdot x$ + $2 \cdot y$ + $0 \cdot dx$ + $1 \cdot dy$ + $0 \cdot t$ + $0 \cdot 1$. $dx$ = $1 \cdot x$ + $1 \cdot y$ + $1 \cdot dx$ + $0 \cdot dy$ + $1 \cdot t$ + $2 \cdot 1$. $dy$ = $1 \cdot x$ + $1 \cdot y$ + $0 \cdot dx$ + $1 \cdot dy$ + $1 \cdot t$ + $2 \cdot 1$. $t$ = $0 \cdot x$ + $0 \cdot y$ + $0 \cdot dx$ + $0 \cdot dy$ + $1 \cdot t$ + $1 \cdot 1$. $1$ = $0 \cdot x$ + $0 \cdot y$ + $0 \cdot dx$ + $0 \cdot dy$ + $0 \cdot t$ + $1 \cdot 1$. So if we calculate $t - 1$ power of $base$ and then multiply $(sx, sy, dx, dy, t, 1)$ by it we will calculate parameters at moment $t$. Power of matrix can be calculated via binary power modulo algo due to associativity of matrix multiplication. More info at http://e-maxx.ru/algo/binary_pow Using trivial matrix multiplication algo we will solve this task in time proportional $6^{3} \cdot log(t)$.
[ "math", "matrices" ]
2,300
null
387
A
George and Sleep
George woke up and saw the current time $s$ on the digital clock. Besides, George knows that he has slept for time $t$. Help George! Write a program that will, given time $s$ and $t$, determine the time $p$ when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second test sample).
I will describe the simple solution. Let George woke up in the $h_{0}$ hours and $m_{0}$ minutes, and he slept for $h_{1}$ hours and $m_{1}$ minutes. Let's get the number $h_{p} = h_{0} - h_{1}$ and $m_{p} = m_{0} - m_{1}$. If $m_{p} < 0$, then you should add to $m_{p}$ $60$ minutes and subtract from $h_{p}$ one hour. After that if $h_{p} < 0$, then add to it $24$ hours. You can print the answer in C++ by using the following line: printf("%02d:%02d", h[p], m[p]). The complexity is $O(1)$ time and $O(1)$ memory.
[ "implementation" ]
900
#include <cstdio> int main() { int h[2], m[2]; for(int i = 0; i < 2; i++) scanf("%d:%d", &h[i], &m[i]); h[0] -= h[1]; m[0] -= m[1]; if (m[0] < 0) m[0] += 60, h[0]--; if (h[0] < 0) h[0] += 24; printf("%02d:%02d\n", h[0], m[0]); return 0; }
387
B
George and Round
George decided to prepare a Codesecrof round, so he has prepared $m$ problems for the round. Let's number the problems with integers $1$ through $m$. George estimates the $i$-th problem's complexity by integer $b_{i}$. To make the round good, he needs to put at least $n$ problems there. Besides, he needs to have at least one problem with complexity exactly $a_{1}$, at least one with complexity exactly $a_{2}$, ..., and at least one with complexity exactly $a_{n}$. Of course, the round can also have problems with other complexities. George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity $c$ to any positive integer complexity $d$ ($c ≥ d$), by changing limits on the input data. However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the $m$ he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
Consider the number of requirements of the difficulties, which we will cover, and we will come up with and prepare new problem to cover other requirements. It is clear that if we decided to meet the $i$ out of $n$ requirements, it would be better to take those with minimal complexity. Let's simplify $i$ most difficult problems to lightest requirements. If all goes well, then we update the answer by value $n - i$. The complexity is: $O(n^{2})$ time / $O(n)$ memory. Note, that there is an solution with complexity $O(n + m)$.
[ "brute force", "greedy", "two pointers" ]
1,200
#include <cstdio> const int N = 3005; int a[N], b[N]; int main() { int n, m; scanf("%d %d", &n, &m); for(int i = 0; i < n; i++) scanf("%d", &a[i]); for(int i = 0; i < m; i++) scanf("%d", &b[i]); int bestPossible = n; if (bestPossible > m) bestPossible = m; for(int i = bestPossible; i >= 0; i--) { bool ok = true; for(int j = 0; j < i; j++) if (a[j] > b[m - i + j]) ok = false; if (ok) { printf("%d\n", n - i); return 0; } } }
387
C
George and Number
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers $b$. During the game, George modifies the array by using special changes. Let's mark George's current array as $b_{1}, b_{2}, ..., b_{|b|}$ (record $|b|$ denotes the current length of the array). Then one change is a sequence of actions: - Choose two distinct indexes $i$ and $j$ $(1 ≤ i, j ≤ |b|; i ≠ j)$, such that $b_{i} ≥ b_{j}$. - Get number $v = concat(b_{i}, b_{j})$, where $concat(x, y)$ is a number obtained by adding number $y$ to the end of the decimal record of number $x$. For example, $concat(500, 10) = 50010$, $concat(2, 2) = 22$. - Add number $v$ to the end of the array. The length of the array will increase by one. - Remove from the array numbers with indexes $i$ and $j$. The length of the array will decrease by two, and elements of the array will become re-numbered from $1$ to current length of the array. George played for a long time with his array $b$ and received from array $b$ an array consisting of exactly one number $p$. Now George wants to know: what is the maximum number of elements array $b$ could contain originally? Help him find this number. Note that originally the array could contain only \textbf{positive} integers.
Let's obtain the following irreducible representation of a number $p = a_{1} + a_{2} + ... + a_{k}$, where $+$ is a concatenation, and numbers $a_{i}$ have the form $x00..000$ (x - is non zero digit, and after that there are only zeroes). Let's determine largest index $i$, such that $a_{1} + a_{2} + ... + a_{i - 1} < a_{i}$. If there are no such index $i$ then $i = 1$. After that is $k - i + 1$. You can compare numbers by using length of number and first digit. You can prove these solution as home task : ) The complexity is: $O(n)$ time / $O(n)$ memory.
[ "greedy", "implementation" ]
1,700
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author gridnevvvit */ public class main_java { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { String s = in.nextLine(); int n = s.length(), j = n - 1, ans = 0; while (j >= 0) { int k = j; while (s.charAt(k) == '0') k--; int len = j - k + 1; if (len > k) { ans ++; j = -1; continue; } if (len == k) { if (s.charAt(0) >= s.charAt(k)) j = k - 1; else j = -1; ans++; continue; } if (len < k) { ans++; j = k - 1; } } out.print(ans); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine(){ try{ return reader.readLine(); } catch (Exception e){ throw new RuntimeException(e); } } }
387
D
George and Interesting Graph
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: - The graph doesn't contain any multiple arcs; - There is vertex $v$ (we'll call her the center), such that for any vertex of graph $u$, the graph contains arcs $(u, v)$ and $(v, u)$. Please note that the graph also contains loop $(v, v)$. - The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex $u$ is the number of arcs that go out of $u$, the indegree of vertex $u$ is the number of arcs that go in $u$. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of $n$ vertices and $m$ arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.
To solve this problem you should know about bipartite matching. Let's consider the center of graph $i$. After that let's remove arcs that have form $(i, u)$ or $(u, i)$. Let's there are $cntWithI$ arcs of such type. Let's $Other = m - CntWithI$ - number of other arcs. After that we should found maximal bipartite matching on the bipartite graph. This graph has following idea: left part of this graph is indegrees of all vertexes except vertex $i$, right part of this graph is outdegrees of all vertexes except vertex $i$. Also if there an arc $(i, j)$ in our graph then in our bipartite graph there an arc $(i, j)$, where $i$ - vertex from left part, $j$ - vertex from the right part. Let's size of bipartite matching on the bipartite graph equals to $leng$. Then answer for the current vertex $i$ equals to $2n - 1 - cntWithI + Other - leng + (n - 1) - leng$. After that you should update global answer. Why it is correct? It is simple to understand that if we will found bipartite matching on the bipartite graph we will cover maximal number of requirements on in/out degrees. Because of that, we will remove all other arcs, except of maximal matching, and after that we will add this maximal matching to full matching by adding $(n - 1) - leng$ arcs. Note, it is important, that self-loops are not forbidden. Withoud self-loops problem is very hard, I think. The complexity is: $O(n^{2}m)$ time / $O(n + m)$ memory.
[ "graph matchings" ]
2,200
#include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <list> #include <vector> #include <string> #include <deque> #include <bitset> #include <algorithm> #include <utility> #include <functional> #include <limits> #include <numeric> #include <complex> #include <cassert> #include <cmath> #include <memory.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> using namespace std; template<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); } template<typename X> inline X sqr(const X& a) { return (a * a); } typedef long long li; typedef long double ld; typedef pair<int,int> pt; typedef pair<ld, ld> ptd; typedef unsigned long long uli; #define forn(i, n) for(int i = 0; i < int(n); i++) #define fore(i, a, b) for(int i = int(a); i <= int(b); i++) #define ford(i, n) for(int i = int(n - 1); i >= 0; i--) #define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++) #define pb push_back #define mp make_pair #define mset(a, val) memset(a, val, sizeof (a)) #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #define ft first #define sc second #define sz(a) int((a).size()) const int INF = int(1e9); const li INF64 = li(INF) * li(INF); const ld EPS = 1e-9; const ld PI = ld(3.1415926535897932384626433832795); const int N = 2000; int n, m, mt[N], used[N], u; vector < pt > edges; vector <int> g[N]; bool read() { if (scanf("%d %d", &n, &m) != 2) return false; forn(i, m) { int u, v; assert(scanf("%d %d", &u, &v) == 2); u--, v--; edges.pb(mp(u, v)); } return true; } inline bool kuhn(int s) { if (used[s] == u) return false; used[s] = u; forn(i, sz(g[s])) { int to = g[s][i]; if (mt[to] == -1 || kuhn(mt[to])) { mt[to] = s; return true; } } return false; } void solve() { int tans = INF; forn(it, n) { int cnt = 0, ans = 0, other = 0; forn(j, n) g[j].clear(), mt[j] = -1; forn(j, m) { if (edges[j].ft == it || edges[j].sc == it) { cnt++; } else { g[edges[j].ft].pb(edges[j].sc); other++; } } forn(i, n) { u++; kuhn(i); } int tsz = 0; forn(i, n) if (mt[i] != -1) tsz++; ans += 2 * (n - 1) + 1 - cnt + other - tsz + (n - 1) - tsz; tans = min(tans, ans); } cout << tans << endl; } int main() { #ifdef gridnevvvit freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif assert(read()); solve(); cerr << clock() << endl; }
387
E
George and Cards
George is a cat, so he loves playing very much. Vitaly put $n$ cards in a row in front of George. Each card has one integer written on it. All cards had distinct numbers written on them. Let's number the cards from the left to the right with integers from $1$ to $n$. Then the $i$-th card from the left contains number $p_{i}$ ($1 ≤ p_{i} ≤ n$). Vitaly wants the row to have exactly $k$ cards left. He also wants the $i$-th card from left to have number $b_{i}$ written on it. Vitaly gave a task to George, to get the required sequence of cards using the remove operation $n - k$ times. In one remove operation George can choose $w$ ($1 ≤ w$; $w$ is not greater than the current number of cards in the row) contiguous cards (contiguous subsegment of cards). Let's denote the numbers written on these card as $x_{1}, x_{2}, ..., x_{w}$ (from the left to the right). After that, George can remove the card $x_{i}$, such that $x_{i} ≤ x_{j}$ for each $j$ $(1 ≤ j ≤ w)$. After the described operation George gets $w$ pieces of sausage. George wondered: what maximum number of pieces of sausage will he get in total if he reaches his goal and acts optimally well? Help George, find an answer to his question!
Let's calculate arrays $pos[i]$ - position of number $i$ in permutation $p$ and $need[i]$ - equals to one if we should remove number $i$ from permutation $p$, and zero if we shouldn't remove $i$ from permutation $p$. Let's $a_{1}, a_{2}, ..., a_{n - k}$ - numvers, which we should remove. It is clear to understand that we should remove these number in increasing order. It is simple to proof this statement. Let's iterate $i$ from to $1$ to $n$. Also we the current number we will have special set (set <>in c++, TreeSet in Java) of positions of non-erased numbers (which are smaller then $i$) of permutation. These position can create an ``obstacle'' for current position of number $i$. It is simple to support this special set. Also we can add to this set numbers $- 1$ and $n$. Now it is easy to find length og the maximal sub-array, where current number is a minimum. You can prosess such query by using standart functions of programming language (lower and higher in Java). After that we should use Fenwick tree to determine quantity of numbers which are not removed on the maximal sub-array. The complexity is: $O(n\log n)$ time / $O(n)$ memory.
[ "binary search", "data structures" ]
2,200
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author gridnevvvit */ public class main_java { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { TreeSet <Integer> integers = new TreeSet<Integer>(); int n = in.nextInt(), m = in.nextInt(); int pos[] = new int [n], need[] = new int[n], t[] = new int[n]; integers.add(-1); integers.add(n); Arrays.fill(need, 0); for(int i = 0; i < n; i++) pos[in.nextInt() - 1] = i; for(int i = 0; i < m; i++) need[in.nextInt() - 1] = 1; long ans = 0; for(int i = 0; i < n; i++) { if (need[i] == 1){ integers.add(pos[i]); } else { int r, l; r = integers.higher(pos[i]) - 1; l = integers.lower(pos[i]) + 1; ans += r - l + 1; for(int j = r; j >= 0; j -= (j + 1) & -(j + 1)) ans -= t[j]; for(int j = l - 1; j >=0 ; j -=(j + 1) & -(j + 1)) ans += t[j]; for(int j = pos[i]; j < n; j += (j + 1) & -(j + 1)) t[j] ++; } } out.println(ans); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
388
A
Fox and Box Accumulation
Fox Ciel has $n$ boxes in her room. They have the same size and weight, but they might have different strength. The $i$-th box can hold at most $x_{i}$ boxes on its top (we'll call $x_{i}$ the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile. Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than $x_{i}$ boxes on the top of $i$-th box. What is the minimal number of piles she needs to construct?
We need some observation: There exists an optimal solution such that: in any pile, the box on the higher position will have a smaller strength. Let k be the minimal number of piles, then there exists an optimal solution such that: The height of all piles is n/k or n/k+1 (if n%k=0, then all of them have the height n/k). We can prove them by exchange argument: from an optimal solution, swap the boxes in it to make above property holds, and we can ensure it will remain valid while swapping. Then for a given k, we can check whether there exist a solution: the i-th (indexed from 0) smallest strength needs to be at least i/k. So we can do binary search (or just enumerate, since n is only 100) on k.
[ "greedy", "sortings" ]
1,400
null
388
B
Fox and Minimal path
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with $n$ vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to $k$?
First we need to know how to calculate the number of different shortest paths from vertex 1 to vertex 2: it can be done by dp: dp[1] = 1, dp[v] = sum{dp[t] | dist(1,t) = dist(1,v) - 1}, then dp[2] is our answer. We need to do dp layer by layer. (first we consider vertexes have distance 1 to node 1, then vertexes have distance 2 to node 1 and so on.) So we can construct the graph layer by layer, and link edges to control the dp value of it. My solution is construct the answer by binary express: If k is 19, then we need some vertexes in previous layer such that the dp value is 16, 2 and 1. So we just need a way to construct layer with dp value equals to 2^k. In the first layer, it contains one node: 1, it has the dp value 1. In the next layer, we can construct 2 nodes, with dp value equals to 1. (We use [1 1] to denote it). And the next layer is [1 1 2], then [1 1 2 4], [1 1 2 4 8] and so on. So we need about 30 layers such that gets all 2^k where k < 30. It uses about 500 nodes.
[ "bitmasks", "constructive algorithms", "graphs", "implementation", "math" ]
1,900
null
388
C
Fox and Card Game
Fox Ciel is playing a card game with her friend Fox Jiro. There are $n$ piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty. Suppose Ciel and Jiro play optimally, what is the score of the game?
First let's consider the case which all piles have even size. In this case, we can prove: in the optimal play, Ciel will gets all top most half cards of each pile, and Jiro gets the remain cards. We can prove by these facts: Ciel have a strategy to ensure she can get this outcome and Jiro also have a strategy to ensure this outcome. (For Jiro this strategy is easy: just pick the card from pile that Ciel have just picked. For Ciel it's a little bit harder.) Why we can conclude they are both the optimal strategy? Ciel just can't win more, because if she played with Jiro with above strategy, Jiro will get the bottom half of each pile. Then we come back with cases that contain odd size piles. The result is: for odd size pile, Ciel will get the top (s-1)/2 cards and Jiro will get the bottom (s-1)/2 cards. Then what about the middle one? Let's denote S is all such middle cards. Then we define a reduced game: In each turn, they pick one card from S. The optimal play for this game is easy: Ciel gets the max one, and Jiro gets the 2nd largest one, and Ciel gets the 3rd largest one and so on. We can prove Ciel have a strategy to get: all top half parts + cards she will get in the optimal play in the reduced game. And Jiro also have a strategy to get: all bottom half parts + cards he will get in the optimal play in the reduced game. And these strategy are optimal.
[ "games", "greedy", "sortings" ]
2,000
null
388
D
Fox and Perfect Sets
Fox Ciel studies number theory. She thinks a non-empty set $S$ contains non-negative integers is perfect if and only if for any $a.b\in S$ ($a$ can be equal to $b$), $(a~x o r~b)\in S$. Where operation $xor$ means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or). Please calculate the number of perfect sets consisting of integers not greater than $k$. The answer can be very large, so print it modulo $1000000007$ $(10^{9} + 7)$.
A perfect set correspond to a linear space, so we can use base to represent it. We do the Gauss-Jordan elimination of vectors in that set, and can get an unique base. (Note that we need to to the all process of Gauss-Jordan elimination, including the elimination after it reached upper triangular) And we can construct the bases bit by bit from higher bit to lower, for a bit: We can add a vector to the base such that the bit is the highest bit of that vector. And at this time, all other vector will have 0 in this bit. Otherwise we need to assign this bit of each vector already in the base. If now we have k vector, then we have 2^k choices. And when we do this, we need to know what's the maximal vector in this space. It's not hard: If we add a vector, then in the maximal vector, this bit will be 1. Otherwise, if we don't have any vector in base yet, then this bit will be 0. Otherwise there will be 2^(k-1) choices results in this bit of maximal vector will be 0, and 2^(k-1) choices results in 1. So we can solve this task by DP bit by bit.
[ "math" ]
2,700
null
388
E
Fox and Meteor Shower
There is a meteor shower on the sky and there are $n$ meteors. The sky can be viewed as a 2D Euclid Plane and the meteor is point on this plane. Fox Ciel looks at the sky. She finds out that the orbit of each meteor is a straight line, and each meteor has a constant velocity. Now Ciel wants to know: what is the maximum number of \textbf{meteors} such that any pair met at the same position at a certain time? Note that the time is not limited and can be also negative. The meteors will never collide when they appear at the same position at the same time.
All tasks beside this are very easy to code. And this one focus on implementation. We can represent the orbit of each meteor by a line in 3D space. (we use an axis to represent the time, and two axis to represent the position on the plane.) Then the problem becomes: we have some lines in 3D space (they are not complete coincide), find a largest clique such that each pair of lines touch at some point. We need this observation: If there are 3 lines in the optimal clique, and these 3 lines are not share a common point, then all line in this clique will on a plane. By using this observation, we only need to consider 2 cases: All lines in the clique have a common point. All lines in the clique are on the same plane. Both are easy tasks in theory, but it needs some coding. There are two ways: Use integer anywhere. Note that the coordinates of intersection can be rational number, but can't be irrational, so we could do this. We can use some way to encode the plane, direction. Use floating number. To count same number of points, we can sort (x, y, z) by using the following compare function: if (abs(A.x - B.x) > eps){return A.x < B.x} otherwise { if(abs(A.y-B.y)>eps){return A.y < B.y} otherwise return A.z < B.z}.
[ "geometry" ]
3,100
null
389
A
Fox and Number Game
Fox Ciel is playing a game with numbers now. Ciel has $n$ positive integers: $x_{1}$, $x_{2}$, ..., $x_{n}$. She can do the following operation as many times as needed: select two different indexes $i$ and $j$ such that $x_{i}$ > $x_{j}$ hold, and then apply assignment $x_{i}$ = $x_{i}$ - $x_{j}$. The goal is to make the sum of all numbers as small as possible. Please help Ciel to find this minimal sum.
First we know that: in the optimal solution, all number will be equal: otherwise we can pick a and b (a < b) then do b = b - a, it will make the answer better. Then we need an observation: after each operation, the GCD (Greatest common divisor) of all number will remain same. It can be proved by this lemma: if g is a divisor of all number of x[], then after the operation, g is still the divisor of these numbers, and vice versa. So in the end, all number will become the GCD of x[]. Another solution that can pass is: While there exist x[i] > x[j], then do x[i] -= x[j]. We can select arbitrary i and j if there exist more than 1 choice.
[ "greedy", "math" ]
1,000
null
389
B
Fox and Cross
Fox Ciel has a board with $n$ rows and $n$ columns. So, the board consists of $n × n$ cells. Each cell contains either a symbol '.', or a symbol '#'. A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks. Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell. Please, tell Ciel if she can draw the crosses in the described way.
Let's define the first # of a shape is the cell contain # that have the lexicographical smallest coordinate. Then the first # of a cross is the top one. Then let x be the first # of the given board. (If the board is empty, then we can draw it with zero crosses.) x must be covered by a cross, and x must be the first # of the cross. (You can try 4 other positions, it will cause a lexicographical smaller # in the board than x) So we try to cover this x use one cross, if it leads some part of the cross covers a '.', then there will be no solution. If not, we just reduce the number of # in the board by 4, we can do this again and again.
[ "greedy", "implementation" ]
1,100
null
390
A
Inna and Alarm Clock
Inna loves sleeping very much, so she needs $n$ alarm clocks in total to wake up. Let's suppose that Inna's room is a $100 × 100$ square with the lower left corner at point $(0, 0)$ and with the upper right corner at point $(100, 100)$. Then the alarm clocks are points with integer coordinates in this square. The morning has come. All $n$ alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game: - First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal. - Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!
The criterion shows that we can only use either vertical segments or horizontal segments. Since there is no limit on the segments' length, we can see that it's always optimal to use a segment with infinite length (or may be known as a line). We can see that the vertical line $x = a$ will span through every alarm clocks standing at positions with x-coordinate being equal to $a$. In a similar manner, the horizontal line $y = b$ will span through every alarm clocks standing at positions with y-coordinate being equal to $b$. So, if we use vertical lines, the number of segments used will be the number of distinct values of x-coordinates found in the data. Similarly, the number of horizontal segments used will be the number of distinct values of y-coordinates found. The process can be implemented by a counting array, or a map. Time complexity: $O\left(n+100\right)$ for regular arrays, or $O\left(n\log(n)\right)$ for maps.
[ "implementation" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> cntx(101, 0); vector<int> cnty(101, 0); while (n--) { int x, y; cin >> x >> y; cntx[x]++; cnty[y]++; } int distinctx = 0, distincty = 0; for (int i=0; i<101; i++) { distinctx += (cntx[i] > 0); distincty += (cnty[i] > 0); } cout << min(distinctx, distincty) << endl; return 0; }
390
B
Inna, Dima and Song
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the $i$-th note at volume $v$ ($1 ≤ v ≤ a_{i}$; $v$ is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the $i$-th note was played on the guitar and the piano must equal $b_{i}$. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the $i$-th note at volumes $x_{i}$ and $y_{i}$ $(x_{i} + y_{i} = b_{i})$ correspondingly, Sereja's joy rises by $x_{i}·y_{i}$. Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song!
From the constraints given, for the $i$-th song, provided there exists corresponding $x_{i}$ and $y_{i}$ values, then the following inequality must hold: $2 \le x_{i} + y_{i} \le 2 \cdot a_{i}$. Thus, if any $b_{i}$ is either lower than $2$ or higher than $2 \cdot a_{i}$, then no $x_{i}$ and $y_{i}$ can be found, thus, Sereja's joy will surely decrease by $1$. Amongst all pairs of $(x_{i},y_{i})$ that $x_{i} + y_{i} = b_{i}$, the pair with the highest value of $x_{i} \cdot y_{i}$ will be one with the equal value of $x_{i} = y_{i}$ (this can be proven by the famous AM-GM inequality). Thus, if $b_{i}$ is divisible by $2$, we can easily pick $x_{i}=y_{i}={\frac{b_{i}}{2}}$. Also, from this, we can see (either intuitively or with static proofs) that the lower the difference between $x_{i}$ and $y_{i}$ is, the higher the value $x_{i} \cdot y_{i}$ will be. Thus, in case $b_{i}$ being odd, the most optimal pair will be $\left(\left[{\frac{b_{i}}{2}}\right],\left[{\frac{b_{i}}{2}}\right]\right)$ or $\left(\left\lfloor{\frac{b_{i}}{2}}\right\rfloor,\left\lceil{\frac{b_{i}}{2}}\right\rceil\right)$ (the order doesn't matter here). Time complexity: $O\left(n\right)$.
[ "implementation" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); int n; cin >> n; vector<int> a(n), b(n); for (auto &z: a) cin >> z; for (auto &z: b) cin >> z; long long Joy = 0; for (int i=0; i<n; i++) { if (b[i] < 2 || b[i] > a[i] * 2) {Joy--; continue;} int x = b[i] / 2, y = b[i] - x; Joy += 1LL * x * y; } cout << Joy << endl; return 0; }
390
C
Inna and Candy Boxes
Inna loves sweets very much. She has $n$ closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to $n$, from left to right. As the boxes are closed, Inna doesn't know which boxes contain candies and which boxes contain nothing. Inna chose number $k$ and asked $w$ questions to Dima to find that out. Each question is characterised by two integers $l_{i}, r_{i}$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$; $r - l + 1$ is divisible by $k$), the $i$-th question is: "Dima, is that true that among the boxes with numbers from $l_{i}$ to $r_{i}$, inclusive, the candies lie \textbf{only} in boxes with numbers $l_{i} + k - 1$, $l_{i} + 2k - 1$, $l_{i} + 3k - 1$, ..., $r_{i}$?" Dima hates to say "no" to Inna. That's why he wonders, what number of actions he will have to make for each question to make the answer to the question positive. In one action, Dima can either secretly take the candy from any box or put a candy to any box (Dima has infinitely many candies). Help Dima count the number of actions for each Inna's question. Please note that Dima doesn't change the array during Inna's questions. That's why when you calculate the number of operations for the current question, please assume that the sequence of boxes didn't change.
The query content looks pretty confusing at first, to be honest. Since $k$ is static throughout a scenario, we can group the boxes into $k$ groups, the $z$-th box (in this editorial let's assume that the indices of the boxes start from $0$) falls into group number $z\ {\mathrm{mod}}\ k$. Then, each query can be simplified as this: "Is that true that among the boxes with numbers from $l_{i}$ to $r_{i}$, inclusive, the candies lie only in boxes of group $(l_{i}+k-1)\mod k$? To make sure the answer for a query being "Yes", Dima has to remove candies from all candied-box in all groups other than $(l_{i}+k-1)\mod k$, while in that exact group, fill every empty box with a candy. Obviously, we'll consider boxes with indices between $l_{i}$ and $r_{i}$ inclusively only. We can make $k$ lists, the $t$-th ($0$-indexed) list stores the indices of candied boxes in group $t$. We'll process with each query as the following: Time complexity: $O\left(n+w k\log(n)\right)$.
[ "data structures" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); int n, k, w; string s; cin >> n >> k >> w >> s; vector< vector<int> > CandyGrp(k); for (int i=0; i<n; i++) { if (s[i] == '0') continue; CandyGrp[i % k].push_back(i); } while (w--) { int l, r; cin >> l >> r; l--; r--; int res = 0; int demandedGroup = (l + k - 1) % k; int BoxesPerGroup = (r - l + 1) / k; for (int id=0; id<k; id++) { int x = lower_bound(CandyGrp[id].begin(), CandyGrp[id].end(), l) - CandyGrp[id].begin(); int y = upper_bound(CandyGrp[id].begin(), CandyGrp[id].end(), r) - CandyGrp[id].begin(); if (id == demandedGroup) { res += (BoxesPerGroup - (y - x)); } else res += (y - x); } cout << res << endl; } return 0; }
390
D
Inna and Sweet Matrix
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix". Inna sees an $n × m$ matrix and $k$ candies. We'll index the matrix rows from $1$ to $n$ and the matrix columns from $1$ to $m$. We'll represent the cell in the $i$-th row and $j$-th column as $(i, j)$. Two cells $(i, j)$ and $(p, q)$ of the matrix are adjacent if $|i - p| + |j - q| = 1$. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length. Each cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the $k$ candies in the matrix one by one. For each candy Inna chooses cell $(i, j)$ that will contains the candy, and also chooses the path that starts in cell $(1, 1)$ and ends in cell $(i, j)$ and doesn't contain any candies. After that Inna moves the candy along the path from cell $(1, 1)$ to cell $(i, j)$, where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used. Help Inna to minimize the penalty in the game.
We can see that the most optimal placement will be choosing $k$ cells being nearest to cell $(1, 1)$ (yup, including $(1, 1)$ itself). To find these $k$ points, we can simply do a BFS starting from $(1, 1)$, with traceback feature to construct the paths to get to those cells. However, keep in mind that any cell being candied will later on become obstacles for the following paths. Thus, to avoid blocking yourself, you should transfer candies to the farthest cells first, then getting closer. Thus, cell $(1, 1)$ will be the last one being filled with candy. Time complexity: $O\left(k\right)$ or $O\left(n m+k\right)$, based on implementation (I myself did $O\left(n m+k\right)$, since the difference isn't too much).
[ "constructive algorithms" ]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); int dx[] = {-1, +0, +0, +1}; int dy[] = {+0, -1, +1, +0}; pair<int, int> Default = {-1, -1}; int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); int n, m, k; cin >> n >> m >> k; vector<vector<int>> Dist(n+2, vector<int>(m+2, 4444)); vector<vector<pair<int, int>>> Last(n+2, vector<pair<int, int>>(m+2, Default)); stack<pair<int, int>> Cells; int cost = 0; queue<pair<int, int>> Q; Q.push({1, 1}); Dist[1][1] = 1; while (!Q.empty() && Cells.size() < k) { pair<int, int> C = Q.front(); Q.pop(); Cells.push(C); int x = C.first, y = C.second; cost += Dist[x][y]; for (int dir=0; dir<4; dir++) { if (x + dx[dir] < 1 || x + dx[dir] > n) continue; if (y + dy[dir] < 1 || y + dy[dir] > m) continue; if (Dist[x+dx[dir]][y+dy[dir]] != 4444) continue; Dist[x+dx[dir]][y+dy[dir]] = Dist[x][y] + 1; Q.push({x + dx[dir], y + dy[dir]}); Last[x+dx[dir]][y+dy[dir]] = C; } } cout << cost << endl; while (!Cells.empty()) { int x = Cells.top().first, y = Cells.top().second; Cells.pop(); stack<pair<int, int>> Traceback; while (x != -1 && y != -1) { Traceback.push({x, y}); pair<int, int> NextCell = Last[x][y]; x = NextCell.first; y = NextCell.second; } while (!Traceback.empty()) { pair<int, int> CurCell = Traceback.top(); Traceback.pop(); cout << "(" << CurCell.first << ", " << CurCell.second << ") "; } cout << endl; } return 0; }
390
E
Inna and Large Sweet Matrix
Inna loves sweets very much. That's why she wants to play the "Sweet Matrix" game with Dima and Sereja. But Sereja is a large person, so the game proved small for him. Sereja suggested playing the "Large Sweet Matrix" game. The "Large Sweet Matrix" playing field is an $n × m$ matrix. Let's number the rows of the matrix from $1$ to $n$, and the columns — from $1$ to $m$. Let's denote the cell in the $i$-th row and $j$-th column as $(i, j)$. Each cell of the matrix can contain multiple candies, initially all cells are empty. The game goes in $w$ moves, during each move one of the two following events occurs: - Sereja chooses five integers $x_{1}, y_{1}, x_{2}, y_{2}, v$ $(x_{1} ≤ x_{2}, y_{1} ≤ y_{2})$ and adds $v$ candies to each matrix cell $(i, j)$ $(x_{1} ≤ i ≤ x_{2}; y_{1} ≤ j ≤ y_{2})$. - Sereja chooses four integers $x_{1}, y_{1}, x_{2}, y_{2}$ $(x_{1} ≤ x_{2}, y_{1} ≤ y_{2})$. Then he asks Dima to calculate the total number of candies in cells $(i, j)$ $(x_{1} ≤ i ≤ x_{2}; y_{1} ≤ j ≤ y_{2})$ and he asks Inna to calculate the total number of candies in the cells of matrix $(p, q)$, which meet the following logical criteria: ($p < x_{1}$ OR $p > x_{2}$) AND ($q < y_{1}$ OR $q > y_{2}$). Finally, Sereja asks to write down the difference between the number Dima has calculated and the number Inna has calculated (D - I). Unfortunately, Sereja's matrix is really huge. That's why Inna and Dima aren't coping with the calculating. Help them!
Let's denote $A$ as the total number of candies on the board, $R_{i}$ as the total number of candies on the $i$-th row ($1 \le i \le n$), $C_{j}$ as the total number of candies on the $j$-th column ($1 \le j \le m$). Also, let's denote $R(i_{1},i_{2})=\sum_{x=i_{1}}^{i_{2}}R_{s}$ and $C(j_{1},j_{2})=\sum_{y=j_{1}}^{\gamma_{2}}C_{y}$. Let's considered the 2nd type of query first. Denoting the answer for the query as $f(x_{1}, y_{1}, x_{2}, y_{2})$, we can see that $f(x_{1}, y_{1}, x_{2}, y_{2}) = R(x_{1}, x_{2}) + C(y_{1}, y_{2}) - A$ (you can draw a simple diagram and validate this function). Thus, the problem is now reduced to calculating $R(x_{1}, x_{2})$, $C(y_{1}, y_{2})$ and $A$: Time complexity: $O\left(w\left(\log(n)+\log(m)\right)\right)$.
[]
null
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count()); struct SegTree_Sum { int n; vector<long long> Tree, Lazy; SegTree_Sum() {} SegTree_Sum(int _n) { n = _n; Tree.resize(n*4); Lazy.resize(n*4); } void Propagate(int node, int st, int en) { if (Lazy[node] == 0) return; Tree[node] += Lazy[node] * (en - st + 1); if (st != en) { Lazy[node*2+1] += Lazy[node]; Lazy[node*2+2] += Lazy[node]; } Lazy[node] = 0; } void Update(int node, int st, int en, int L, int R, long long val) { Propagate(node, st, en); if (en < st || R < st || en < L) return; if (L <= st && en <= R) { Lazy[node] += val; Propagate(node, st, en); return; } Update(node*2+1, st, (st+en)/2+0, L, R, val); Update(node*2+2, (st+en)/2+1, en, L, R, val); Tree[node] = Tree[node*2+1] + Tree[node*2+2]; } long long Sum(int node, int st, int en, int L, int R) { Propagate(node, st, en); if (en < st || R < st || en < L) return 0LL; if (L <= st && en <= R) return Tree[node]; long long p1 = Sum(node*2+1, st, (st+en)/2+0, L, R); long long p2 = Sum(node*2+2, (st+en)/2+1, en, L, R); return (p1 + p2); } void RangeUpdate(int L, int R, long long val) { Update(0, 0, n-1, L, R, val); } long long RangeSum(int L, int R) { return Sum(0, 0, n-1, L, R); } }; int main(int argc, char* argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); int n, m, w; cin >> n >> m >> w; long long TotalCandies = 0; SegTree_Sum TreeRow = SegTree_Sum(n); SegTree_Sum TreeCol = SegTree_Sum(m); while (w--) { int t, x1, y1, x2, y2; cin >> t >> x1 >> y1 >> x2 >> y2; if (t == 0) { int v; cin >> v; TotalCandies += 1LL * (x2 - x1 + 1) * (y2 - y1 + 1) * v; TreeRow.RangeUpdate(x1, x2, 1LL * v * (y2 - y1 + 1)); TreeCol.RangeUpdate(y1, y2, 1LL * v * (x2 - x1 + 1)); } else if (t == 1) { long long res = 0; res += TreeRow.RangeSum(x1, x2); res += TreeCol.RangeSum(y1, y2); res -= TotalCandies; cout << res << endl; } } return 0; }
392
A
Blocked Points
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points $A$ and $B$ on the plane are 4-connected if and only if: - the Euclidean distance between $A$ and $B$ is one unit and neither $A$ nor $B$ is blocked; - or there is some integral point $C$, such that $A$ is 4-connected with $C$, and $C$ is 4-connected with $B$. Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than $n$, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
Let's look at all pairs of neighboring points such that one of them is special and the other one is not. I claim that it is necessary and sufficient to block at least one point in every such pair Necessity is obvious. Let's prove sufficiency. Assume that we blocked at least one point in each pair, but there are two points $A$ and $B$ such that $A$ is special, $B$ is not and they are 4-connected. Then look at the path between these points. It starts with a special point and ends with non-special. That means that there are two adjacent points in this path such that the first one is special and the second one is not. But it contradicts our statement that we blocked at least one of the points in each pair. Now let's look at these pairs. For simplicity, we will look at only $\frac18$-th of a circle. And let's draw all horizontal pairs with a point inside the selected piece. There are also some vertical segments, but it can be proven with some geometry that the segments on the neighboring horizontal line are either on the same x-coordinate, or one is shifted by one. This means that if we choose the leftmost point in each of these segments, we will cover all vertical pairs as well. With some symmetry, this can be done for other pieces of a circle. There is only one thing left - we need to bring all pieces together. It is easy when two pieces share a horizontal or vertical line, but in the other case, we need another picture. In this case, everything is already fine, we don't have any "leaks" between parts In that case, we don't have any leaks either, but we have overlapping segments, and that means that we case save 1 point here and 4 points total. All we need now is to calculate the number of segments in a circle sector (it is ${n}/\sqrt{2}+1$) and differentiate these two cases.
[ "math" ]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n; cin >> n; if (n == 0) { cout << 1 << '\n'; return 0; } int L = sqrt(n * n / 2); pair<long long, long long> near = {L + 1, L}; int ans = (L * 2 + 1) * 4; if (near.first * near.first + near.second * near.second > n * n) ans -= 4; cout << ans << '\n'; return 0; }
392
B
Tower of Hanoi
The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: - Only one disk can be moved at a time. - Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. - No disk may be placed on top of a smaller disk. With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is $2^{n} - 1$, where $n$ is the number of disks. (c) Wikipedia. SmallY's puzzle is very similar to the famous Tower of Hanoi. In the Tower of Hanoi puzzle you need to solve a puzzle in minimum number of moves, in SmallY's puzzle each move costs some money and you need to solve the same puzzle but for minimal cost. At the beginning of SmallY's puzzle all $n$ disks are on the first rod. Moving a disk from rod $i$ to rod $j$ $(1 ≤ i, j ≤ 3)$ costs $t_{ij}$ units of money. The goal of the puzzle is to move all the disks to the third rod. In the problem you are given matrix $t$ and an integer $n$. You need to count the minimal cost of solving SmallY's puzzle, consisting of $n$ disks.
First, understand this solution of the standard Hanoi puzzle, if you don't know it. I will use the same idea to solve this problem. Let's create a function $calc(from, to, n)$ which will count the minimal cost to move $n$ disks from $from$ to $to$. If $n=1$ then we either move the disk directly to $to$, or we first move it to the $mid$ (the remaining rod) and only then move to $to$. If $n > 1$ then again, there are two possible strategies. Either we use moves from standard solution - move $n-1$ disks to $mid$, move 1 disk from $from$ to $to$, then move $n-1$ disks to $to$. Or we can make more moves but possibly with less cost: move $n-1$ disks to $to$, then 1 disk from $from$ to $mid$, then $n-1$ disks back to $from$, then 1 disk to $to$, and finally $n-1$ disks to $to$. Here are pictures for both cases: Better resolution Better resolution For moving $n-1$ disks we will make recursive calls. If we just do that, we will have an exponential solution, which is not very nice. But we only have $3\times 2 \times n$ different calls - 3 options for $from$, 2 for $to$ and $n$. That means that we can just store every value which we already counted (or I can say a fancy word memoization, which means the same thing)
[ "dp" ]
null
#include <bits/stdc++.h> using namespace std; #define ll long long array<array<ll, 3>, 3> t; map<pair<pair<int, int>, ll>, ll> mem; ll calc(int from, int to, int n) { auto p = make_pair(make_pair(from, to), n); if (mem.count(p)) return mem[p]; int mid = 3 - from - to; if (n == 1) { return mem[p] = min(t[from][mid] + t[mid][to], t[from][to]); } return mem[p] = min(calc(from, mid, n - 1) + t[from][to] + calc(mid, to, n - 1), calc(from, to, n - 1) + t[from][mid] + calc( to, from, n - 1) + t[mid][to] + calc(from, to, n - 1)); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cin >> t[i][j]; } } int n; cin >> n; cout << calc(0, 2, n) << '\n'; return 0; }
392
C
Yet Another Number Sequence
Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation: \[ F_{1} = 1, F_{2} = 2, F_{i} = F_{i - 1} + F_{i - 2} (i > 2). \] We'll define a new number sequence $A_{i}(k)$ by the formula: \[ A_{i}(k) = F_{i} × i^{k} (i ≥ 1). \] In this problem, your task is to calculate the following sum: $A_{1}(k) + A_{2}(k) + ... + A_{n}(k)$. The answer can be very large, so print it modulo $1000000007$ $(10^{9} + 7)$.
This is obviously some matrix-exponentiation problem. We just have to figure out the matrix. Well, let's look at what we have $A_i(k) = F_i \cdot i^k = (F_{i-1} + F_{i-2}) \cdot i^k = F_{i-1}\cdot ((i-1)+1)^k + F_{i-2}\cdot ((i-2) + 2)^k =\\= \sum_{j=0}^k \binom{k}{j} F_{i-1}(i-1)^j + \sum_{j=0}^k \binom{k}{j} F_{i-2}(i-2)^j\cdot 2^{k-j}=\\= \sum_{j=0}^k \binom{k}{j} A_{i-1}(j) + \sum_{j=0}^k \binom{k}{j} A_{i-2}(j)\cdot 2^{k-j}$ Then we just have to store $A_{i-1}(j)$ and $A_{i-2}(j)$ for every $j \in [0;k]$. And also we have to store the sum, so the matrix will be of size $2(k+1)+1$, resulting in $O(k^3\log n)$ in total.
[ "combinatorics", "math", "matrices" ]
null
#include <bits/stdc++.h> using namespace std; #define ll long long template<auto P> struct Modular { using value_type = decltype(P); value_type value; Modular(ll k = 0) : value(norm(k)) {} Modular<P>& operator += (const Modular<P>& m) { value += m.value; if (value >= P) value -= P; return *this; } Modular<P> operator + (const Modular<P>& m) const { Modular<P> r = *this; return r += m; } Modular<P>& operator -= (const Modular<P>& m) { value -= m.value; if (value < 0) value += P; return *this; } Modular<P> operator - (const Modular<P>& m) const { Modular<P> r = *this; return r -= m; } Modular<P> operator - () const { return Modular<P>(-value); } Modular<P>& operator *= (const Modular<P> &m) { value = value * 1ll * m.value % P; return *this; } Modular<P> operator * (const Modular<P>& m) const { Modular<P> r = *this; return r *= m; } Modular<P>& operator /= (const Modular<P> &m) { return *this *= m.inv(); } Modular<P> operator / (const Modular<P>& m) const { Modular<P> r = *this; return r /= m; } Modular<P>& operator ++ () { return *this += 1; } Modular<P>& operator -- () { return *this -= 1; } Modular<P> operator ++ (int) { Modular<P> r = *this; r += 1; return r; } Modular<P> operator -- (int) { Modular<P> r = *this; r -= 1; return r; } bool operator == (const Modular<P>& m) const { return value == m.value; } bool operator != (const Modular<P>& m) const { return value != m.value; } value_type norm(ll k) { if (!(-P <= k && k < P)) k %= P; if (k < 0) k += P; return k; } Modular<P> inv() const { value_type a = value, b = P, x = 0, y = 1; while (a != 0) { value_type k = b / a; b -= k * a; x -= k * y; swap(a, b); swap(x, y); } return Modular<P>(x); } }; template<auto P> Modular<P> pow(Modular<P> m, ll p) { Modular<P> r(1); while (p) { if (p & 1) r *= m; m *= m; p >>= 1; } return r; } template<auto P> ostream& operator << (ostream& o, const Modular<P> &m) { return o << m.value; } template<auto P> istream& operator >> (istream& i, Modular<P> &m) { ll k; i >> k; m.value = m.norm(k); return i; } template<auto P> string to_string(const Modular<P>& m) { return to_string(m.value); } using Mint = Modular<1000000007>; // using Mint = Modular<998244353>; // using Mint = long double; vector<vector<Mint>> operator * (vector<vector<Mint>> a, vector<vector<Mint>> b) { vector<vector<Mint>> c(a.size(), vector<Mint>(b[0].size(), 0)); for (int i = 0; i < a.size(); ++i) { for (int j = 0; j < a[0].size(); ++j) { for (int k = 0; k < b[0].size(); ++k) { c[i][k] += a[i][j] * b[j][k]; } } } return c; } vector<vector<Mint>> pow(vector<vector<Mint>> a, ll p) { vector<vector<Mint>> res(a.size(), vector<Mint>(a.size(), 0)); for (int i = 0; i < res.size(); ++i) { res[i][i] = 1; } while (p) { if (p & 1) { res = res * a; } a = a * a; p /= 2; } return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll n; cin >> n; int k; cin >> k; vector<vector<Mint>> mt((k + 1) * 2 + 1, vector<Mint>((k + 1) * 2 + 1, 0)); vector<vector<Mint>> vinit(mt.size(), vector<Mint>(1, 0)); // first k+1 elements are for F_{i-1}, next k+1 are for F_{i-2}, the last one is for sum up to A_{i-2} for (int i = 0; i < k + 1; ++i) { vinit[i][0] = 1; vinit[i + k + 1][0] = 0; vinit.back()[0] = 0; } vinit[k + 1][0] = 1; vector<vector<Mint>> C(50, vector<Mint>(50, 0)); for (int i = 0; i < C.size(); ++i) { C[0][i] = 0; C[i][0] = 1; } for (int i = 1; i < C.size(); ++i) { for (int j = 1; j < C.size(); ++j) { C[i][j] = C[i - 1][j] + C[i - 1][j - 1]; } } vector<Mint> p2(50, 1); for (int i = 1; i < p2.size(); ++i) p2[i] = p2[i - 1] * 2; for (int p = 0; p < k + 1; ++p) mt[k + 1 + p][p] = 1; mt.back().back() = 1; mt.back()[k] = 1; for (int p = 0; p < k + 1; ++p) { for (int j = 0; j <= p; ++j) { mt[p][j] += C[p][j]; mt[p][k + 1 + j] += C[p][j] * p2[p - j]; } } auto res = pow(mt, n) * vinit; cout << res.back()[0] << '\n'; return 0; }
392
D
Three Arrays
There are three arrays $a$, $b$ and $c$. Each of them consists of $n$ integers. SmallY wants to find three integers $u$, $v$, $w$ $(0 ≤ u, v, w ≤ n)$ such that the following condition holds: each number that appears in the union of $a$, $b$ and $c$, appears either in the first $u$ elements of $a$, or in the first $v$ elements of $b$, or in the first $w$ elements of $c$. Of course, SmallY doesn't want to have huge numbers $u$, $v$ and $w$, so she wants sum $u + v + w$ to be as small as possible. Please, help her to find the minimal possible sum of $u + v + w$.
Let forget about $a$ for a minute and solve the problem for two arrays. Of course, it can be done with something like two pointers, but it is not extendable to three arrays (at least I don't know how). We need a more general approach. First, let's assume that $b$ has all elements, which $c$ contains. We can achieve that by copying $c$ at the end of $b$ (it is easy to see that this will not improve the answer). Suppose for some number $k$ it has only one occurrence in $b$ and only one in $c$. And $b[i] = c[j] = k$. Then we denote $pos[i] = j$. Now, if $k$ has multiple occurrences in $c$, we will take the smallest $j$. If it has multiple occurrences in $b$, we will set the first $pos[i]$ to $j$ and others to $0$. Why that? Good question. Now the answer for the problem is $min_i((i-1) + max_{j > i}pos[j])$. The expression in the brackets corresponds to the case when we take $i$ first elements from $b$. Then we look for all other elements ($j>i$) and choose the shortest prefix of $c$ which contains all these elements. That explains why we write the first occurrence of $k$ in $c$ to $pos$. And we fill other values with zero because we don't need them if we already took the first occurrence in $b$. Now get $a$ back. What changes if we have some numbers in $a$? Well, in that case, we can set $pos[i]=0$ for all occurrences of that number in $b$ (not only all except first). That means that if we iterate over prefix of $a$ from $0$ to $n$ then we will have to change some $pos$ to zero. But I prefer changing zeros to some values, so we will iterate from $n$ to $0$. Well, let's iterate. Suppose we decided not to take prefix of length $i$ in $a$, and instead took prefix of length $i-1$. If there are some occurrences of $a[i]$ before $i$, then nothing changes in $pos$. But if there is no $a[i]$ before $i$, we have to update some $pos$ and recalculate $min_i((i-1) + max_{j > i}pos[j])$. I believe there are different structs that can do it, I will describe what I used. In the expression, there are maximums on the suffix. They can be stored as pairs $(p, m)$ which means that up to position $p$ maximum on a suffix is at least $m$ (maximum-on-a-suffix is a non-increasing function, obviously). Now, to calculate the answer, we don't have to go through all $i$. We only need to consider such indices $p$ that some pair $(p-1, ?)$ exists in our set. That means that we have to check exactly one option for every pair of adjacent pairs. Remember, we only have to add pairs to this set. And it is easy - add a pair and remove enough pairs before it (while their $m$ less than new $m$). With every addition or removal, we have $O(1)$ additions or removals of options for an answer. Current answers can be stored in a multiset since we only need the minimal value. And if we are looking at a prefix $i$ of $a$, then we have to update the answer with $i$ + (the smallest value from multiset). This is probably not the cleanest explanation, so there is a random picture which can help: The picture can contain off-by-one error, depending on your indexing and my mistakes. $pos = [1,\,0,\,5,\,3,\,0,\,3,\,2]$. The picture illustrates maximums on a suffix for every $i$. In a set, we store one pair for each horizontal segment. When we need to update the answer, we look at all points with a green circle (or actually 1 to the right of these points because in this picture maximum at $x=2$ is $5$, so we need $(3,3)$, not $(2,3)$, but that is exactly what I meant when I said about off-by-one errors).
[ "data structures" ]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<int> a(n), b(n), c(n); for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 0; i < n; ++i) cin >> b[i]; for (int i = 0; i < n; ++i) cin >> c[i]; for (auto k : c) { b.push_back(k); } map<int, int> whereb; map<int, int> wherec; for (int i = (int)b.size() - 1; i >= 0; --i) whereb[b[i]] = i; for (int i = (int)c.size() - 1; i >= 0; --i) wherec[c[i]] = i; vector<bool> first_in_a(a.size(), false); vector<bool> first_in_b(b.size(), false); set<int> ina, inb; for (int i = 0; i < a.size(); ++i) { if (!ina.count(a[i])) { ina.insert(a[i]); first_in_a[i] = true; } } for (int i = 0; i < b.size(); ++i) { if (!inb.count(b[i])) { inb.insert(b[i]); first_in_b[i] = true; } } set<pair<int, int>> maxs; multiset<int> res; maxs.emplace(1e9, 0); maxs.emplace(-1, 1e9 + 5); res.insert(maxs.begin()->first + next(maxs.begin())->second + 1); auto del = [&](pair<int, int> p) { auto it = maxs.find(p); assert(it != maxs.end()); auto inext = next(it); auto iprev = prev(it); res.erase(res.find(iprev->first + it->second + 1)); res.erase(res.find(it->first + inext->second + 1)); maxs.erase(it); res.insert(iprev->first + inext->second + 1); }; auto add = [&](pair<int, int> p) { auto it = maxs.lower_bound(make_pair(p.first, -5)); if (it->second >= p.second) return; if (it->first == p.first) { ++it; } while (prev(it)->second <= p.second) del(*prev(it)); maxs.insert(p); it = maxs.find(p); auto inext = next(it); auto iprev = prev(it); res.insert(iprev->first + it->second + 1); res.insert(it->first + inext->second + 1); res.erase(res.find(iprev->first + inext->second + 1)); }; for (int i = 0; i < b.size(); ++i) { if (first_in_b[i] && !ina.count(b[i])) { int inc = 1e9; if (wherec.count(b[i])) inc = wherec[b[i]] + 1; add({i, inc}); } } int ans = n + *res.begin(); for (int i = n - 1; i >= 0; --i) { if (first_in_a[i]) { if (!inb.count(a[i])) break; int inc = 1e9; if (wherec.count(a[i])) inc = wherec[a[i]] + 1; add({whereb[a[i]], inc}); } ans = min(ans, i + *res.begin()); } cout << ans << '\n'; return 0; }
392
E
Deleting Substrings
SmallR likes a game called "Deleting Substrings". In the game you are given a sequence of integers $w$, you can modify the sequence and get points. The only type of modification you can perform is (unexpected, right?) deleting substrings. More formally, you can choose several contiguous elements of $w$ and delete them from the sequence. Let's denote the sequence of chosen elements as $w_{l}, w_{l + 1}, ..., w_{r}$. They must meet the conditions: - the equality $|w_{i} - w_{i + 1}| = 1$ must hold for all $i$ $(l ≤ i < r)$; - the inequality $2·w_{i} - w_{i + 1} - w_{i - 1} ≥ 0$ must hold for all $i$ $(l < i < r)$. After deleting the chosen substring of $w$, you gain $v_{r - l + 1}$ points. You can perform the described operation again and again while proper substrings exist. Also you can end the game at any time. Your task is to calculate the maximum total score you can get in the game.
There will be three different $dp$, let's get that out of the way. I wanted to make $4$, but in the end decided to merge two of them. Also, before everything, let's update $v$ with $v[i] = max_j(v[j] + v[i - j])$. Because sometimes we want to remove segment of length $5$, but $2 + 3$ gives more points. First, let's discuss what a good substring is. It is either increasing, decreasing, or increasing up to something and then decreasing. And in any case, the difference between neighboring elements is exactly 1. $dp\_mon[l][r]$ - the biggest score we can get from segment $[l;r]$ if in the end we are left with monotonous sequence, starting from $w[l]$ and ending with $w[r]$ (that means that we cannot remove $w[l]$ or $w[r]$). If we can't do that, $dp\_mon[l][r] = -\infty$. $dp\_all[l][r]$ - the biggest score we can get from removing the whole segment $[l;r]$. $dp[l][r]$ - the best score we can get on segment $[l;r]$ (no restrictions). The answer will be $dp[1][n]$. When we have these $dp$, it is not very hard to calculate them. To get $dp\_mon[l][r]$ we either have to remove everything in between (if $|w[l] - w[r]| = 1$), or for each number between $l$ and $r$ check if it can be in that monotonous sequence, and if it can, split by this number and add two $dp\_mon[l][j] + dp\_mon[j][r]$ (with intersection, yes). Now $dp\_all$. First, let's update it with every $dp\_all[l][j] + dp\_all[j + 1][r]$. Now suppose there is an option, where we can't split the segment into two pieces. Consider the last segment we removed. It is some subsequence of our $[l;r]$ segment. Elements of that subsequence split this segment into pieces. Each of these pieces is independent of each other. That means that if the first element of the subsequence is $w[j]$ then $[l; j-1]$ and $[j; r]$ are independent and we already updated the answer with the sum of $dp\_all$, and similarly with $r$. There is one case, though. When this subsequence starts at $w[l]$ and ends in $w[r]$. But that's what we have $dp\_mon$ for! Now for every element on $[l;r]$ we have to check if this subsequence is increasing from $w[l]$ to $w[j]$ and then decreasing from $w[j]$ to $w[r]$. That means that we add two $dp\_mon$ and after that remove this subsequence with a score of $v[len\_of\_subsequence]$. The length can be calculated from $|w[l] - w[j]|$ and $|w[j] - w[r]|$. The last is $dp$. That's the easiest one. Either we remove everything - this is $dp\_all$, or there is some element which we decided not to remove. Then, as discussed in previous paragraph, it is enough to update $dp[l][r]$ by every $dp[l][j] + dp[j + 1][r]$. And I know that probably some of $dp$ are useless, but I feel like it is easier to understand the solution with multiple $dp$ with different purposes.
[]
null
#include <bits/stdc++.h> using namespace std; #define ll long long const int inf = 1e9; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } v.insert(v.begin(), 0); for (int i = 1; i <= n; ++i) { for (int j = 1; j < i; ++j) { v[i] = max(v[i], v[j] + v[i - j]); } } vector<int> w(n); for (int i = 0; i < n; ++i) { cin >> w[i]; } auto getv = [&](int ln) { if (ln < v.size()) return v[ln]; return -inf; }; vector<vector<ll>> dp_all(n, vector<ll>(n, -inf)); vector<vector<ll>> dp_mon(n, vector<ll>(n, -inf)); vector<vector<ll>> dp(n, vector<ll>(n, 0)); for (int i = 0; i < n; ++i) { dp_mon[i][i] = 0; dp_all[i][i] = v[1]; if (i != 0) dp_all[i][i - 1] = 0; } for (int k = 1; k <= n; ++k) { for (int l = 0; l < n; ++l) { int r = l + k - 1; if (r >= n) break; for (int j = l + 1; j <= r; ++j) { dp_all[l][r] = max(dp_all[l][r], dp_all[l][j - 1] + dp_all[j][r]); } if (w[l] != w[r]) { if (abs(w[l] - w[r]) == 1) { dp_mon[l][r] = dp_all[l + 1][r - 1]; } else { for (int j = l + 1; j < r; ++j) { if (w[l] != w[j] && w[r] != w[j] && ((w[l] < w[j]) == (w[j] < w[r]))) { dp_mon[l][r] = max(dp_mon[l][r], dp_mon[l][j] + dp_mon[j][r]); } } } } for (int j = l; j <= r; ++j) if (w[j] >= w[l] && w[j] >= w[r]) dp_all[l][r] = max(dp_all[l][r], dp_mon[l][j] + dp_mon[j][r] + getv(abs(w[l] - w[j]) + abs(w[j] - w[r]) + 1)); dp[l][r] = max(dp[l][r], dp_all[l][r]); for (int j = l + 1; j <= r; ++j) dp[l][r] = max(dp[l][r], dp[l][j - 1] + dp[j][r]); } } cout << dp[0][n - 1] << '\n'; return 0; }
393
A
Nineteen
Alice likes word "nineteen" very much. She has a string $s$ and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "{x\textbf{nineteen}pp\textbf{nineteen}w}", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters. Help her to find the maximum number of "nineteen"s that she can get in her string.
Looking at examples and thinking about different cases lead to the idea that the best result would be to build a string which starts with $nineteenineteenineteen...$. The first word $nineteen$ requires 3 letters $n$, 3 letters $e$, 1 letter $i$ and 1 letter $t$. Every next occurrence of $nineteen$ requires the same set of letters, but we need only two letters $n$ for each new word. In other words, we can start with $n$, and then every word will need exactly two extra $n$-s. Let $cnt[c]$ denote the number of characters $c$ in the string. Then the answer is $min\left(\left\lfloor\frac{cnt[n] - 1}{2}\right\rfloor, \,\left\lfloor\frac{cnt[e]}{3}\right\rfloor,\, cnt[i],\, cnt[t]\right)$. (In theory this minimum could be $-\left\lfloor\frac{1}{2}\right\rfloor$, but in C++ it is equal to zero, so everything works fine)
[]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); string s; cin >> s; map<char, int> cnt; for (auto c : s) { cnt[c]++; } cout << min({(cnt['n'] - 1) / 2, cnt['e'] / 3, cnt['i'], cnt['t']}) << '\n'; return 0; }
393
B
Three matrices
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an $n × n$ matrix $W$, consisting of integers, and you should find two $n × n$ matrices $A$ and $B$, all the following conditions must hold: - $A_{ij} = A_{ji}$, for all $i, j$ $(1 ≤ i, j ≤ n)$; - $B_{ij} = - B_{ji}$, for all $i, j$ $(1 ≤ i, j ≤ n)$; - $W_{ij} = A_{ij} + B_{ij}$, for all $i, j$ $(1 ≤ i, j ≤ n)$. Can you solve the problem?
We can write this system of equations, using the fact that $B[j][i] = -B[i][j]$ and $A[i][j] = A[j][i]$ $\begin{cases} A[i][j] + B[i][j] = W[i][j]\\ A[j][i] + B[j][i] = W[j][i] \end{cases} \quad\Rightarrow\quad \begin{cases} A[i][j] + B[i][j] = W[i][j]\\ A[i][j] - B[i][j] = W[j][i] \end{cases}$ From that, it is easy to conclude that $A[i][j] = \frac{W[i][j] + W[j][i]}{2}$ and $B[i][j] = \frac{W[i][j] - W[j][i]}{2}$.
[]
null
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<vector<double>> w(n, vector<double>(n)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> w[i][j]; } } vector<vector<double>> a(n, vector<double>(n)); vector<vector<double>> b(n, vector<double>(n)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { a[i][j] = (w[i][j] + w[j][i]) / 2; b[i][j] = (w[i][j] - w[j][i]) / 2; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout << a[i][j] << ' '; } cout << '\n'; } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout << b[i][j] << ' '; } cout << '\n'; } return 0; }
396
A
On Number of Decompositions into Multipliers
You are given an integer $m$ as a product of integers $a_{1}, a_{2}, ... a_{n}$ $(m=\prod_{i=1}^{n}a_{i})$. Your task is to find the number of distinct decompositions of number $m$ into the product of $n$ ordered positive integers. Decomposition into $n$ products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo $1000000007$ $(10^{9} + 7)$.
Let's factorize all $n$ numbers into prime factors. Now we should solve the problem for every prime independently and multiply these answers. The number of ways to split $p^{k}$ into $n$ multipliers, where $p$ is prime, is equal to $C(k + n - 1, n - 1)$ (it can be obtained using the method of stars and bars, you can read about it here, choose 'combinatorics'). So we have a solution that needs $O(n\cdot{\sqrt{M A X A}}+n\cdot\log M A X A)$ time.
[ "combinatorics", "math", "number theory" ]
null
null
396
B
On Sum of Fractions
Let's assume that - $v(n)$ is the largest prime number, that does not exceed $n$; - $u(n)$ is the smallest prime number strictly greater than $n$. Find $\sum_{i=2}^{n}{\frac{1}{v(i)u(i)}}$.
First of all, let's consider $n + 1 = p$ is prime. Then we can prove by induction that the answer is ${\frac{1}{2}}-{\frac{1}{p}}$. Base for $p = 3$ is obvious. If this equality holds for $p$, and $q$ is the next prime, then answer for $q$ is equal to answer for $p$ plus $q - p$ equal summands $\mathbf{\Sigma}_{P q}^{1}$, that is $\textstyle{\frac{1}{2}}-{\frac{1}{q}}$, that's we wanted to prove. Next using that the distance between two consecutive primes not exceeding $10^{9}$ does not exceed $300$, we can find the answer as a sum of the answer for the maximal prime not exceeding $n$ and several equal summands $\mathbf{\Sigma}_{P q}^{1}$. We see that the denominator is a divisor of $2pq$, which fits in long long.
[ "math", "number theory" ]
null
null
396
C
On Changing Tree
You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$. Initially all vertices contain number $0$. Then come $q$ queries, each query has one of the two types: - The format of the query: $1$ $v$ $x$ $k$. In response to the query, you need to add to the number at vertex $v$ number $x$; to the numbers at the \textbf{descendants} of vertex $v$ at distance $1$, add $x - k$; and so on, to the numbers written in the descendants of vertex $v$ at distance $i$, you need to add $x - (i·k)$. The distance between two vertices is the number of edges in the shortest path between these vertices. - The format of the query: $2$ $v$. In reply to the query you should print the number written in vertex $v$ modulo $1000000007$ $(10^{9} + 7)$. Process the queries given in the input.
We can write all vertices in the list in order of $dfs$, then the descendants of the vertex from a segment of this list. Let's count for every vertex its distance to the root $level[v]$. Let's create two segment trees $st1$ and $st2$. If we are given a query of the first type, in $st1$ we add $x + level[v] \cdot k$ to the segment corresponding to the vertex $v$, in $st2$ we add $k$ to the segment corresponding to the vertex $v$. If we are given a query of the second type, we write st1.get(v) - st2.get(v) * level[v]. The complexity is O(qlogn). You can use any other data stucture that allows to add to the segment and to find a value of an arbitrary element. Also there exists a solution using Heavy-Light decomposition.
[ "data structures", "graphs", "trees" ]
null
null
396
D
On Sum of Number of Inversions in Permutations
You are given a permutation $p$. Calculate the total number of inversions in all permutations that lexicographically do not exceed the given one. As this number can be very large, print it modulo $1000000007$ $(10^{9} + 7)$.
Let's prove a useful fact: sum of number of invertions for all permutations of size $k$ is equal to $s u m A l l[k]=k!\cdot{\frac{k(k-1)}{4}}$. The prove is simple: let's change in permutation $p$ for every $i$ $p_{i}$ to $k + 1 - p_{i}$. Then the sum of number of invertions of the first and the second permutations is $\frac{k(k-1)}{2}$, and our conversion of the permutation is a biection. Now we suppose that we are given a permutation of numbers from $0$ to $n - 1$. Let's go at $p$ from left to right. What permutations are less than $p$? Permutations having first number less than $p_{0}$. If the first number is $a < p_{0}$, than in every such permutation there are a inversions of form (first element, some other element). So in all permutations beginning with $a$ there are $a \cdot (n - 1)!$ inversions of this from. Moreover, there are inversions not including the first element, their sum is $sumAll[n - 1]$. Then, counting sum for all $a$ we have ${\frac{p_{0}(p_{0}-1)}{2}}\cdot\left(n-1\right)!+p_{0}\cdot s u m A l l[n-1]$ inversions. Permutations beginning with $p_{0}$. At first, we should count the number of inversions, beginning in $p_{0}$. There are $cnt \cdot p_{0}$ of this form, where $cnt$ is the number of permutations beginning with $p_{0}$ and not exceeding $p$. Then we should count the inversions not beginning in the beginning. But it is the same problem! The only exception is that if $p_{1} > p_{0}$, there are $p_{1} - 1$ available numbers less than $p_{1}$, but not $p_{1}$. So we get a solution: go from left to right, keep already used numbers in Fenwick tree, and then solve the same problem, assuming that the first number is not $p_{i}$ but $p_{i}$ - (the number of used numbers less than $p_{i}$). The last we should do is to count the number of permutations not exceeding the suffix of $p$ and beginning the same. It can be precomputed, if we go from right to left. In this case we should do the same as in the first part of solution, but consider that the minimal number is a number of already used numbers less than current.
[ "combinatorics", "math" ]
null
null
396
E
On Iteration of One Well-Known Function
Of course, many of you can calculate $φ(n)$ — the number of positive integers that are less than or equal to $n$, that are coprime with $n$. But what if we need to calculate $φ(φ(...φ(n)))$, where function $φ$ is taken $k$ times and $n$ is given in the canonical decomposition into prime factors? You are given $n$ and $k$, calculate the value of $φ(φ(...φ(n)))$. Print the result in the canonical decomposition into prime factors.
We will describe an algorithm and then understand why it works. For every prime we will maintain a list of intervals. At the first moment for every $p_{i}$ we add in its list interval $[0;a_{i})$, other primes have an empty list. Then we go from big primes to small. Let's consider that current prime is $p$. If in its list there exists an interval $[x;y)$, $x < k, y > k$, we divide it into two parts $[x;k)$ and $[k;y)$. Then for every interval $[x;y)$, $x \ge k$ (in fact, in this case $x = k$) we add to the answer for $p$ $y - x$. For intervals, where $y \le k$, we add to list of every prime divisor of $p - 1$ invterval $[x + 1, y + 1)$. If $p - 1$ has some prime if more than first power, we should add this segment several times. After that we should conduct a "union with displacement" operation for every prime which list was changed. If in one list there are $2$ invervals $[x, y), [z, t)$ so that $y \le z > x$, we replace them with one interval $[x, y + t - z)$ (so we added $t - z$ to the right border of the first interval). Then we go to next (lesser) $p$. Why does it works? If we take function $ \phi $ one time, for every prime $p$ which divides $n$, $n$ is divided by $p$ and multiplied by $p - 1$ (or, the same, by all prime divisors $p - 1$ in corresponding powers). Now we can observe that intervals in lists contains the numbers of iterations, when the number contains the corresponding prime number. Bigger primes do not affect smaller, so we can process them earlier. If after $i$-th iteration the number contains prime number $p$, after $i + 1$-th iteration it contains prime divisors of $p - 1$, and we add segments in accordance with this. The k-th iteration is the last, so the existence of the interval $[k, x)$ means that after $k$-th iteration we have $(x - k)$-th power of this prime. From this it is clear why we unite the intervals if that way. Why does it work fast? Because we precalculated the minimal prime divisor of each number up to $MAXPRIME$ using linear Eratosthenes sieve. (Well, it's not necessary) Because we precalculated the minimal prime divisor of each number up to $MAXPRIME$ using linear Eratosthenes sieve. (Well, it's not necessary) Because for each prime there's no more than $\log M A X P R I M E=20$ intervals, because for each $[a, b)$ range $a\leq\log M A X P R I M E+1$. Practically there is no more than $6$ segments at once. Because for each prime there's no more than $\log M A X P R I M E=20$ intervals, because for each $[a, b)$ range $a\leq\log M A X P R I M E+1$. Practically there is no more than $6$ segments at once.
[ "math" ]
null
null
397
A
On Segment's Own Points
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a $100$ centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate $0$, and the opposite end has coordinate $100$. Overall, the university has $n$ students. Dean's office allows $i$-th student to use the segment $(l_{i}, r_{i})$ of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students! Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others $(n - 1)$ students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.
Create an array $used$ of $100$ elements. i-th element for the segment $(i, i + 1)$. For every student except Alexey set $used[i] = true$ for each segment $(i, i + 1)$ in the segment of that student. After that for each subsegment $(i, i + 1)$ of Alexey's segment add 1 to result if $used[i] = false$.
[ "implementation" ]
null
null
397
B
On Corruption and Numbers
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate. The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — $n_{i}$ berubleys. He cannot pay more than $n_{i}$, because then the difference between the paid amount and $n_{i}$ can be regarded as a bribe! Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than $r_{i}$. The rector also does not carry coins of denomination less than $l_{i}$ in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination $x$ berubleys, where $l_{i} ≤ x ≤ r_{i}$ (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater. Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type. In other words, you are given $t$ requests, each of them contains numbers $n_{i}, l_{i}, r_{i}$. For each query you need to answer, whether it is possible to gather the sum of exactly $n_{i}$ berubleys using only coins with an integer denomination from $l_{i}$ to $r_{i}$ berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
First of all, calculate how many $L$'s we can bring so that the result will not exceed $N$. It's $K={\frac{N}{L}}$. Now, if $R \cdot K \ge N$ we may increase any of $K$ numbers by $1$. At some moment sum will be equal to $N$ becase sum of $K$ $R$'s is greater than $N$. So answer in this case is YES. If $R \cdot K < N$, we can't get $K$ or less numbers because their sum is less than $N$. But we can't get more than $K$ numbers too, because their sum is more than $N$. So answer is NO. Complexity: O(1) for every query. Overall complexity: O(t).
[ "constructive algorithms", "implementation", "math" ]
null
null
398
A
Cards
User ainta loves to play with cards. He has $a$ cards containing letter "o" and $b$ cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. - At first, the score is $0$. - For each block of contiguous "o"s with length $x$ the score increases by $x^{2}$. - For each block of contiguous "x"s with length $y$ the score decreases by $y^{2}$.  For example, if $a = 6, b = 3$ and ainta have arranged the cards in the order, that is described by string "ooxoooxxo", the score of the deck equals $2^{2} - 1^{2} + 3^{2} - 2^{2} + 1^{2} = 9$. That is because the deck has 5 blocks in total: "oo", "x", "ooo", "xx", "o". User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards.
Let the number of o blocks $p$, and the number of x blocks $q$. It is obvious that $|p - q| \le 1$ and $p, q \le n$. So we can just iterate all $p$ and $q$, and solve these two problems independently, and merge the answer. 1. Maximize the value of $x_{1}^{2} + x_{2}^{2} + ... + x_{p}^{2}$ where $x_{1} + x_{2} + ... + x_{p} = a$ and $x_{i} \ge 1$. Assign $a - p + 1$ to $x_{1}$, and assign $1$ to $x_{2}, x_{3}, ..., x_{p}$. The value is $(a - p + 1)^{2} + (p - 1)$. 2. Minimize the value of $y_{1}^{2} + y_{2}^{2} + ... + y_{q}^{2}$ where $y_{1} + y_{2} + ... + y_{q} = b$ and $y_{i} \ge 1$. For all $1\leq i\leq(b\ \mathrm{mod}\ q)$, assign $\left\lfloor{\frac{b}{q}}\right\rfloor+1$ to $y_{i}$. For all $(b\mod q)+1\leq j\leq q$, assign $\textstyle{\left|{\frac{b}{q}}\right|}$ to $y_{j}$. The value is $([\frac{b}{q}]+1)^{2}\times(b\mathrm{\boldmath~\mod~}q)+([\frac{b}{q}])^{2}\times\{q-(b\mathrm{\boldmath~\mod~}q)\}$. The proof is easy, so I won't do it. With this, we can solve the problem. We can print $y_{1}$ xs, and then $x_{1}$ os, ... Time complexity: $O(n)$.
[ "constructive algorithms", "implementation" ]
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <math.h> #include <assert.h> #include <stack> #include <queue> #include <map> #include <set> #include <algorithm> #include <string> #include <functional> #include <vector> #include <deque> #include <utility> #include <bitset> #include <limits.h> using namespace std; typedef long long ll; typedef double lf; typedef long double llf; typedef unsigned long long llu; ll sq(ll v) { return v*v; } int main() { ll a, b; scanf("%I64d%I64d", &a, &b); ll n = min(a, b); if(a == 0) { printf("%I64d\n", -sq(b)); for(ll i = 0; i < b; i++) putchar('x'); } else if(b <= 1) { printf("%I64d\n", sq(a) - sq(b)); for(ll i = 0; i < a; i++) putchar('o'); for(ll i = 0; i < b; i++) putchar('x'); } else { ll res = -sq(a + b); ll res_w, res_l; for(int w = 1; w <= n; w++) { for(int l = w-1; l <= w+1; l++) if(1 <= l && l <= b) { // w groups winning, l groups losing ll positive = sq(a - (w-1)) + (w-1); ll negative = sq(b / l + 1) * (b % l) + sq(b / l) * (l - b % l); if(res < positive - negative) { res = positive - negative; res_w = w; res_l = l; } } } printf("%I64d\n", res); if(res_w >= res_l) { for(ll i = 0; i < res_w; i++) { int wl = (i > 0) ? 1 : a - (res_w-1); for(int x = 0; x < wl; x++) putchar('x'); int ll = (i < b % res_l) ? (b / res_l + 1) : (b / res_l); if(i < res_l) for(int x = 0; x < ll; x++) putchar('o'); } }else { for(ll i = 0; i < res_l; i++) { int ll = (i < b % res_l) ? (b / res_l + 1) : (b / res_l); for(int x = 0; x < ll; x++) putchar('x'); int wl = (i > 0) ? 1 : a - (res_w-1); if(i < res_w) for(int x = 0; x < wl; x++) putchar('o'); } } } return 0; }
398
B
Painting The Wall
User ainta decided to paint a wall. The wall consists of $n^{2}$ tiles, that are arranged in an $n × n$ table. Some tiles are painted, and the others are not. As he wants to paint it beautifully, he will follow the rules below. - Firstly user ainta looks at the wall. If there is at least one painted cell on each row and at least one painted cell on each column, he stops coloring. Otherwise, he goes to step 2. - User ainta choose any tile on the wall with uniform probability. - If the tile he has chosen is not painted, he paints the tile. Otherwise, he ignores it. - Then he takes a rest for one minute even if he doesn't paint the tile. And then ainta goes to step 1.  However ainta is worried if it would take too much time to finish this work. So he wants to calculate the expected time needed to paint the wall by the method above. Help him find the expected time. You can assume that choosing and painting any tile consumes no time at all.
This can be solved by dynamic programming. Let $T[i, j]$ the expected time when $i$ rows and $j$ columns doesn't have any painted cells inside. Let's see all the cases. If we carefully rearrange the order of rows and columns, we can divide the wall into 4 pieces. Choose a cell in rectangle 1. The size of this rectangle is $i \times j$. The expectation value is $T[i - 1, j - 1]$. Choose a cell in rectangle 2. The size of this rectangle is $i \times (n - j)$. The expectation value is $T[i - 1, j]$. Choose a cell in rectangle 3. The size of this rectangle is $(n - i) \times j$. The expectation value is $T[i, j - 1]$. Choose a cell in rectangle 4. The size of this rectangle is $(n - i) \times (n - j)$. The expectation value is $T[i, j]$. Merging these four cases, we can get: $T[i, j] = 1 + {T[i - 1, j - 1] \times i \times j + T[i - 1, j] \times i \times (n - j) + T[i, j - 1] \times (n - i) \times j + T[i, j] \times (n - i) \times (n - j)} / n^{2}$ Moving the $T[i, j]$ on the right to the left, we can get the formula which can be used to calculate the value $T[i, j]$. There are some corner cases, like $i = 0$ or $j = 0$, but it can be simply handled. Time complexity: $O(n^{2})$
[ "dp", "probabilities" ]
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <math.h> #include <assert.h> #include <stack> #include <queue> #include <map> #include <set> #include <algorithm> #include <string> #include <functional> #include <vector> #include <deque> #include <utility> #include <bitset> #include <limits.h> using namespace std; typedef long long ll; typedef double lf; typedef long double llf; typedef unsigned long long llu; int N, M; lf Table[2005][2005]; int R, C; bool chkR[2005], chkC[2005]; int main() { scanf("%d%d", &N, &M); R = C = N; for(int i = 1; i <= M; i++) { int r, c; scanf("%d%d", &r, &c); if(!chkR[r]) --R; if(!chkC[c]) --C; chkR[r] = chkC[c] = true; } for(int i = 1; i <= N; i++) Table[i][0] = Table[i-1][0] + (lf)N / i; for(int j = 1; j <= N; j++) Table[0][j] = Table[0][j-1] + (lf)N / j; for(int i = 1; i <= N; i++) for(int j = 1; j <= N; j++) { lf &v = Table[i][j]; v = (i * j * Table[i-1][j-1]) + ((N - i) * j * Table[i][j-1]) + (i * (N - j) * Table[i-1][j]); v /= N*N; v = v+1; v /= (1. - (lf)(N-i) * (N-j) / (N*N)); } printf("%.10Lf\n", Table[R][C]); return 0; }
398
C
Tree and Array
User ainta likes trees. This time he is going to make an undirected tree with $n$ vertices numbered by integers from $1$ to $n$. The tree is weighted, so each edge of the tree will have some integer weight. Also he has an array $t$: $t[1], t[2], ..., t[n]$. At first all the elements of the array are initialized to $0$. Then for each edge connecting vertices $u$ and $v$ ($u < v$) of the tree with weight $c$, ainta adds value $c$ to the elements $t[u], t[u + 1], ..., t[v - 1], t[v]$ of array $t$. Let's assume that $d(u, v)$ is the total weight of edges on the shortest path between vertex $u$ and vertex $v$. User ainta calls a pair of integers $x, y$ ($1 ≤ x < y ≤ n$) good if and only if $d(x, y) = t[x] + t[x + 1] + ... + t[y - 1] + t[y]$. User ainta wants to make at least $\lfloor{\frac{n}{2}}\rfloor$ good pairs, but he couldn't make a proper tree. Help ainta to find such a tree.
There are two intended solutions. One is easy, and the other is quite tricky. Easy Solution Make a tree by the following method. For all $1\leq i\leq\lfloor{\frac{n}{2}}\rfloor$, make an edge between vertex $i$ and $i+\lfloor{\frac{n}{2}}\rfloor$ with weight 1. For all $\lfloor{\frac{n}{2}}\rfloor<i<n$, make an edge between vertex $i$ and $i + 1$ with weight $2(i-[\frac{n}{2}])-1$. You can see that $(1,2),(2,3),\cdot\cdot\cdot\,,(\,\lfloor{\frac{n}{2}}\rfloor-1,\lfloor{\frac{n}{2}}\rfloor)$ are all good pairs. In addition, $(1, 3)$ is also a good pair. So we can print the answer. But, if $n = 5$, this method doesn't work because $(1, 3)$ is not a good pair. In this case, one may solve by hand or using random algorithm. Time complexity: $O(n)$ Bonus I: Is there any method to make more than $\textstyle{\left[{\frac{n}{2}}\right]}$ good pairs? Bonus II: Is there any method that the maximum weight is relatively small and make at least $\lfloor{\frac{n}{2}}\rfloor$ good pairs? Tricky Solution If you got stuck with the problem, one can run any random algorithm that solves small cases, and merge these cases. With this approach, we can even limit the weight to a very small constant! But I think this is not a good solution, so I won't mention about unless anybody wants to know the details. I came up with this solution, and tried to purpose this as D. It seems all the 6 people who passed pretests during the contest didn't use this solution :) Time complexity: ???
[ "constructive algorithms" ]
null
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <math.h> #include <assert.h> #include <stack> #include <queue> #include <map> #include <set> #include <algorithm> #include <string> #include <functional> #include <vector> #include <deque> #include <utility> #include <bitset> #include <limits.h> using namespace std; typedef long long ll; typedef double lf; typedef long double llf; typedef unsigned long long llu; const int trees[10][10][3] = { { }, { }, { {0, 1, 1}, }, { {0, 2, 1}, {0, 1, 1}, }, { {0, 2, 8}, {0, 1, 4}, {1, 3, 4}, }, { {0, 1, 4}, {0, 3, 3}, {1, 2, 6}, {3, 4, 1}, }, { {0, 1, 6}, {0, 3, 2}, {1, 4, 2}, {1, 2, 3}, {4, 5, 4}, }, { {0, 1, 7}, {0, 5, 1}, {0, 2, 10}, {1, 4, 1}, {2, 3, 1}, {5, 6, 6}, }, { {0, 4, 1}, {0, 1, 3}, {0, 3, 1}, {1, 2, 2}, {4, 7, 2}, {5, 6, 3}, {6, 7, 3}, } }; const int queries[10][10][2] = { { }, { }, { }, { }, { {2, 3} }, { {2, 3}, {2, 4} }, { {2, 3}, {3, 4}, {3, 5} }, { {2, 4}, {3, 5}, {3, 6}, {4, 5}, {4, 6} }, { {2, 3}, {2, 5}, {3, 5}, {4, 5} } }; const int num_queries[10] = {0, 0, 0, 0, 1, 2, 3, 5, 4}; const int num_queries_tail[10] = {0, 0, 0, 0, 1, 1, 1, 2, 0}; int n; int table[100005], rec[100005]; int merged_tree[100005][3]; int merged_queries[100005][3]; int main() { scanf("%d", &n); for(int i = 4; i <= 8; i++) rec[i] = i, table[i] = num_queries[i]; for(int i = 9; i <= n; i++) { for(int j = 2; j <= 8; j++) { int q = table[i-j] + (num_queries[j] - num_queries_tail[j]); if(q > table[i]) table[i] = q, rec[i] = j; } } int t = n, x = 1, q = 0, e = 0; while(t > 0) { int sz = rec[t]; for(int i = 0; i < sz-1; i++) { merged_tree[e][0] = trees[sz][i][0] + x; merged_tree[e][1] = trees[sz][i][1] + x; merged_tree[e][2] = trees[sz][i][2]; e++; } for(int i = 0; i < num_queries[sz] && q < n/2; i++) { if(t > 8 && queries[sz][i][1] == sz - 1) continue; merged_queries[q][0] = queries[sz][i][0] + x; merged_queries[q][1] = queries[sz][i][1] + x; q++; } x += sz; t -= sz; if(t > 0) { merged_tree[e][0] = x-1; merged_tree[e][1] = x; merged_tree[e][2] = 1; e++; } } if(q < n/2) printf("queries = %d\n", q); for(int i = 0; i < e; i++) { for(int j = 0; j < 3; j++) printf("%d%c", merged_tree[i][j], (j == 2) ? '\n' : ' '); } for(int i = 0; i < q; i++) { for(int j = 0; j < 2; j++) printf("%d%c", merged_queries[i][j], (j == 1) ? '\n' : ' '); } return 0; }
398
D
Instant Messanger
User ainta decided to make a new instant messenger called "aintalk". With aintalk, each user can chat with other people. User ainta made the prototype of some functions to implement this thing. - login($u$): User $u$ logins into aintalk and becomes online. - logout($u$): User $u$ logouts and becomes offline. - add_friend($u$, $v$): User $u$ and user $v$ become friends. It means, $u$ and $v$ can talk with each other. The friendship is bidirectional. - del_friend($u$, $v$): Unfriend user $u$ and user $v$. It means, $u$ and $v$ cannot talk with each other from then. - count_online_friends($u$): The function returns the number of friends of user $u$ who are online at the moment.  Because the messenger is being tested by some users numbered from $1$ to $n$, there is no register method. This means, at the beginning, some users may be online, and some users may have friends. User ainta is going to make these functions, but before making the messenger public, he wants to know whether he is correct. Help ainta verify his code.
Let $x_{i}$ an integer representing the state of the i-th user. If user i is online, $x_{i} = 1$, otherwise, $x_{i} = 0$. Also, let $S_{i}$ the set consisting of i-th friends. One can see that the queries become like this: Online/Offline: change the value of $x_{i}$ to $1 - x_{i}$. Add: add $u$ to set $S_{v}$, and $v$ to set $S_{u}$. Delete: delete $u$ from set $S_{v}$, $v$ from set $S_{u}$. Count: calculate $\textstyle\sum_{w\in S_{w}}x_{w}$. Let's use sqrt-decomposition to perform these queries. Let user $u$ heavy if $|S_{u}| \ge C$, or light otherwise. Also, we will define some arrays and sets: $H_{u}$ is a set that stores friends with user $u$ who are heavy users. $O[u]$ stores the sum of . If the Online/Offline($u$) query is given, If $u$ is a light user: for all , change the value of $O[v]$. It takes $O(|S_{u}|)$ time. Otherwise: just update the state of itself. If the Add($u, v$) query is given, If vertex $u$ becomes heavy if we add this edge, for all , add $v$ into $H_{w}$ and update the value of $O[w]$. This can be done in $O(C)$. If vertex $u$ is still light even if we add the edge, update $O[v]$. This can be done in constant time. If vertex $u$ is heavy (after the operations above), update $H_{v}$. Add $u$ to set $S_{v}$, and $v$ to set $S_{u}$. If the Delete($u, v$) query is given, Delete $u$ from set $S_{v}$, and $v$ from set $S_{u}$. Update the value of $O[*]$, $H_{u}$ and $H_{v}$. Because for all $|H_{w}| \le E| / C$, this can be done in $O(|E| / C)$. If the counting query is given, $O[u]+\sum_{w\in H_{w}}x_{u}$ will be the answer. Because $|H_{u}| \le |E| / C$, it will take $O(|E| / C)$ time. So for each query, $O(|E| / C)$ or $O(C)$ time is required. To minimize the time, . Time complexity: $O(q{\sqrt{|E|}})$ We can also solve this by dividing the queries into ${\sqrt{q}}$ parts. For each block, use $O(n + m + q)$ time to build the online & offline state and the answer table for each vertices. For each query, you can use $O({\sqrt{q}})$ time to get the answer. If you want more details, please ask in the comments. Time complexity: $O(q{\sqrt{q}})$
[ "data structures" ]
null
#include<stdio.h> #include<algorithm> #include<vector> using namespace std; #define N_ 100010 #define Q_ 250010 #define M_ 150010 int n, m, Q, SZ, C[N_], cnt, st[N_], beg[N_], Next[(M_ + Q_) * 2]; bool v[N_]; struct Query{ int a, b; char ck; }w[Q_]; struct Edge{ int a, b; bool ck; bool operator <(const Edge &p)const{ return a != p.a ? a < p.a : b < p.b; } }Ed[(M_ + Q_) * 2]; bool on[N_]; void UDT(int a, int b){ int B = st[a], E = st[a+1] - 1, M; while (B <= E){ M = (B + E) >> 1; if (Ed[M].b == b)break; if (Ed[M].b > b) E = M - 1; else B = M + 1; } Ed[M].ck = !Ed[M].ck; if (v[a] && on[b]){ if (Ed[M].ck)C[a]++; else C[a]--; } } int main() { int i, j, o, cnt = 0, a, b, pv, be, ed, x, t; char pp[2]; scanf("%d%d%d%d", &n, &m, &Q, &o); while (o--){ scanf("%d", &i); on[i] = true; } for (i = 0; i < m; i++){ scanf("%d%d", &a, &b); Ed[cnt].a = a, Ed[cnt].b = b, Ed[cnt++].ck = true; Ed[cnt].a = b, Ed[cnt].b = a, Ed[cnt++].ck = true; } for (i = 1; i*i <= Q; i++); SZ = i * 2; for (i = 0; i < Q; i++){ scanf("%s%d", &pp, &w[i].a); w[i].ck = pp[0]; if (w[i].ck == 'A' || w[i].ck == 'D'){ scanf("%d", &w[i].b); Ed[cnt].a = w[i].a, Ed[cnt++].b = w[i].b; Ed[cnt].a = w[i].b, Ed[cnt++].b = w[i].a; } } sort(Ed, Ed + cnt); o = 0, pv = 0; for (i = 0; i < cnt; i++){ if (!i || Ed[i].a != Ed[i - 1].a || Ed[i].b != Ed[i - 1].b){ if (!i || Ed[i].a != Ed[i - 1].a){ while (pv != Ed[i].a){ pv++; st[pv] = o; } } Ed[o++] = Ed[i]; } else if (Ed[i].ck)Ed[o - 1].ck = true; } while (pv != n + 1){ pv++; st[pv] = o; } be = 0; for (i = 1; i <= n; i++)beg[i] = -2; while (1){ ed = be + SZ; if (ed > Q)ed = Q; cnt = 0; for (i = be; i < ed;i++){ if (w[i].ck == 'C'){ if (!v[w[i].a]){ v[w[i].a] = true; C[w[i].a] = 0; for (j = st[w[i].a]; j < st[w[i].a + 1]; j++){ if (Ed[j].ck && on[Ed[j].b])C[w[i].a]++; } } } } for (i = be; i < ed; i++){ if (w[i].ck == 'O' || w[i].ck == 'F'){ x = w[i].a; on[x] = !on[x]; if (on[x]) a = 1; else a = -1; if (beg[x] == -2){ for (j = st[x]; j != st[x + 1]; j++){ if (v[Ed[j].b]){ if(Ed[j].ck)C[Ed[j].b] += a; if (beg[x] == -2)beg[x] = j, t = j; else Next[t] = j, t = j; } } if (beg[x] == -2)beg[x] = -1; else Next[t] = -1; } else{ t = beg[x]; while (t != -1){ if (Ed[t].ck)C[Ed[t].b] += a; t = Next[t]; } } } else if(w[i].ck == 'D' || w[i].ck == 'A'){ UDT(w[i].a, w[i].b); UDT(w[i].b, w[i].a); } else printf("%d\n", C[w[i].a]); } for (i = be; i < ed; i++){ if (w[i].ck == 'C')v[w[i].a] = false; if (w[i].ck == 'O' || w[i].ck == 'F')beg[w[i].a] = -2; } if (ed == Q)break; be = ed; } return 0; }
398
E
Sorting Permutations
We are given a permutation sequence $a_{1}, a_{2}, ..., a_{n}$ of numbers from $1$ to $n$. Let's assume that in one second, we can choose some disjoint pairs $(u_{1}, v_{1}), (u_{2}, v_{2}), ..., (u_{k}, v_{k})$ and swap all $a_{ui}$ and $a_{vi}$ for every $i$ at the same time ($1 ≤ u_{i} < v_{i} ≤ n$). The pairs are disjoint if every $u_{i}$ and $v_{j}$ are different from each other. We want to sort the sequence completely in increasing order as fast as possible. Given the initial permutation, calculate the number of ways to achieve this. Two ways are different if and only if there is a time $t$, such that the set of pairs used for swapping at that time are different as sets (so ordering of pairs doesn't matter). If the given permutation is already sorted, it takes no time to sort, so the number of ways to sort it is $1$. To make the problem more interesting, we have $k$ holes inside the permutation. So exactly $k$ numbers of $a_{1}, a_{2}, ..., a_{n}$ are not yet determined. For every possibility of filling the holes, calculate the number of ways, and print the total sum of these values modulo $1000000007$ $(10^{9} + 7)$.
Let us start with the case when there is no hole. Given any permutation, I will prove that it takes only at most two seconds to sort it completely. Since every permutation can be decomposed into disjoint cycles (link), we only need to take care of each decomposed cycle. That is, we only need to sort a cycle of arbitrary length in two steps. Let's make a table of 3 rows and $n$ columns. The first row will constitute the original, unsorted permutation. For each column, the next column will form the permutation after one second. The last column will be the sorted permutation. The following depicts the case where $n = 5$ and the permutation is a full cycle. 2 3 4 5 1 ? ? ? ? ? 1 2 3 4 5Now we have to show that we can fill the second column properly. Let's just fill the first number in the second column randomly, say 4, and see what happens. 2 3 4 5 1 4 ? ? ? ? 1 2 3 4 5Because 4 replaces 2 in the second column, 2 replaces 4 and we are forced to put 2 below the 4 in first column. 2 3 4 5 1 4 ? 2 ? ? 1 2 3 4 5Likewise, 3 replaces 2 in the third column, so we should put 3 above 2 in the third column. 2 3 4 5 1 4 3 2 ? ? 1 2 3 4 5Repeating the process will finally give a complete, valid answer. 2 3 4 5 1 4 3 2 1 5 1 2 3 4 5Like the example above, filling the first number in the second column by any number will give a unique and valid answer. I won't prove it formally, but by experimenting with different examples you can see it indeed works :) So now we know that (i) any permutation can be sorted in 2 seconds and, additionally, (ii) if the permutation is a cycle, there are exactly $n$ ways of doing it. Now let us see what happens if two disjoint cycles interact with each other. Try to fill the tables below and figure out what happens. First one is a disjoint union of cycles of length 4 and 5. Second one is a union of cycles of length 4 and 4. 2 3 4 5 1 7 8 9 6 2 3 4 1 6 7 8 5 8 ? ? ? ? ? ? ? ? 8 ? ? ? ? ? ? ? 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8By experimenting, you will see that if two disjoint cycles $A$ and $B$ interact (to be precise, when an element in $A$ swaps place with another element in $B$), (i) the size of $A$ and $B$ are equal and in that case (ii) the number of ways to achieve a complete assignment for elements of $A$ and $B$ is exactly the size of $A$ (or $B$). I won't prove it, but it can be done formally if one wishes to. Now we have the solution when there is no hole: decompose the permutation into disjoint cycles. Assume there are exactly $c_{i}$ cycles of length $l_{i}$ for each $i$. Let $a[c, l]$ be the number of ways to sort $c$ cycles of length $l$ completely. Then the answer will be $\prod_{i}a[c_{i},l_{i}]$, basically because only cycles of same length interact. To sort $c$ cycles of length $l$, we can pair some of the cycles to interact with each other. Then each pair and unpaired cycle will contribute multiplicative factor $l$ to the answer. Now we can derive a recursive formula for $a[c, l]$. Just take a cycle $C$ and decide if it will be paired to different cycle or not. For the first case, $C$ contributes multiplicative factor $l$ and we can decide on the rest of $c - 1$ cycles, so there are total of $l \cdot a[c - 1, l]$ ways. For the second case, we have $c - 1$ ways to pair $C$ with the other cycle, then the pair contributes factor $l$ and we can decide on the remaining $c - 2$ cycles. This contributes $l \cdot (c - 1) \cdot a[c - 2, l]$. Adding up will give us the recursive formula. $a[c, l] = l \cdot a[c - 1, l] + l \cdot (c - 1) \cdot a[c - 2, l]$ Computing every $a[c, l]$ can be done in reasonable time: $c_{l}$ will be at most $n / l$ and there will be total of $O(n\log n)$ values of $a[c, l]$ to compute using the recursive formula above. Given a permutation, we can count the number of cycles $c_{l}$ of length $l$ for each $l$ and compute $a[c_{l}, l]$. Since two cycles of different length cannot interact, the number of ways to sort the whole permutation will be the multiplication of $a[c_{l}, l]$'s over all $l$. Finally, we have to deal with $k \le 12$ holes. The crucial observation is that with holes, the permutation decomposes into cycles and paths. Filling the holes will group the paths to disjoint cycles. Considering every $12!$ possible ways will give TLE. But if we note that the order of paths in a same group does not make a change in cycle's length, we can actually deploy a bitmask DP to consider all possible way to partition at most 12 paths. Just multiply some constant to each partition and sum over (I'll skip the details).
[]
null
null
399
A
Pages
User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are $n$ pages numbered by integers from $1$ to $n$. Assume that somebody is on the $p$-th page now. The navigation will look like this: \begin{center} << $p - k$ $p - k + 1$ $...$ $p - 1$ $(p)$ $p + 1$ $...$ $p + k - 1$ $p + k$ >> \end{center} When someone clicks the button "<<" he is redirected to page $1$, and when someone clicks the button ">>" he is redirected to page $n$. Of course if someone clicks on a number, he is redirected to the corresponding page. There are some conditions in the navigation: - If page $1$ is in the navigation, the button "<<" must not be printed. - If page $n$ is in the navigation, the button ">>" must not be printed. - If the page number is smaller than $1$ or greater than $n$, it must not be printed.  You can see some examples of the navigations. Make a program that prints the navigation.
You can solve this problem by just following the statement. First, print << if $p - k > 1$. Next, iterate all the integers from $p - k$ to $p + k$, and print if the integer is in $[1..n]$. Finally, print >> if $p + k < n$. Time complexity: $O(n)$.
[ "implementation" ]
null
#include <stdio.h> int n, p, k; int main() { scanf("%d%d%d", &n, &p, &k); if(p - k > 1) printf("<< "); for(int i = p - k; i <= p + k; i++) if(1 <= i && i <= n) printf((i == p) ? "(%d) " : "%d ", i); if(p + k < n) printf(">> "); return 0; }
399
B
Red and Blue Balls
User ainta has a stack of $n$ red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack. - While the top ball inside the stack is red, pop the ball from the top of the stack. - Then replace the blue ball on the top with a red ball. - And finally push some blue balls to the stack until the stack has total of $n$ balls inside.  If there are no blue balls inside the stack, ainta can't apply this operation. Given the initial state of the stack, ainta wants to know the maximum number of operations he can repeatedly apply.
Change the blue balls to bit 1, and blue balls to bit 0. Interpret the stack as an integer represented in binary digits. Now, one may see that a single operation decreases the integer by 1, and will be unavailable iff the integer becomes zero. So the answer will be $2^{a1} + 2^{a2} + ... + 2^{ak}$ where the $(a_{i} + 1)$-th ($1 \le i \le k$) ball is blue in the beginning. Time complexity: $O(n)$
[]
null
#include <stdio.h> int n; char s[55]; long long res; int main() { scanf("%d%s", &n, s); for(int i = 0; i < n; i++) if(s[i] == 'B') res |= 1ll << i; printf("%I64d\n", res); return 0; }
400
A
Inna and Choose Options
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below: There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers $a$ and $b$ $(a·b = 12)$, after that he makes a table of size $a × b$ from the cards he put on the table as follows: the first $b$ cards form the first row of the table, the second $b$ cards form the second row of the table and so on, the last $b$ cards form the last (number $a$) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses. Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers $a$ and $b$ to choose. Help her win the game: print to her all the possible ways of numbers $a, b$ that she can choose and win.
Not difficult task. Let's iterate param $a$. If $12$ % $a$ != $0$, continue. Calculate $b = 12 / a$. Let's iterate column (from $1$ to $b$) and for each it's cell $(i, j)$ check, if it contains $X$ or not. Cell $(i, j)$ - is $((i-1) * a + j)$ -th element of string.
[ "implementation" ]
1,000
null
400
B
Inna and New Matrix of Candies
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload". The field for the new game is a rectangle table of size $n × m$. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose \textbf{all lines of the matrix where dwarf is not on the cell with candy} and shout "Let's go!". After that, all the dwarves from the chosen lines start to \textbf{simultaneously} move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs: - some dwarf in one of the chosen lines is located in the rightmost cell of his row; - some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells. Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.
In the final version of statement we must choose all lines we haven't finish already. If it is a string where we have $S...G$ - answer $- 1$. Otherwise, the answer is the number of distinct distances, as one step kills all distances of the minimal length.
[ "brute force", "implementation", "schedules" ]
1,200
null
400
C
Inna and Huge Candy Matrix
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from $1$ to $n$ from top to bottom and the columns — from $1$ to $m$, from left to right. We'll represent the cell on the intersection of the $i$-th row and $j$-th column as $(i, j)$. Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has $p$ candies: the $k$-th candy is at cell $(x_{k}, y_{k})$. The time moved closer to dinner and Inna was already going to eat $p$ of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix $x$ times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix $y$ times. And then he rotated the matrix $z$ times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!
Let's note that the number of 90 clockwise make sence only by modulo 4. Horizontal - by modulo 2, and 90 counterclockwise - by modulo 4, and 1 such rotation is 3 clockwise rotations. 90 clockwise: $newi = j;$ $newj = n-i + 1$ don't forget to $swap(n, m)$. Horizontal: $newj = m-j + 1$
[ "implementation", "math" ]
1,500
null
400
D
Dima and Bacteria
Dima took up the biology of bacteria, as a result of his experiments, he invented $k$ types of bacteria. Overall, there are $n$ bacteria at his laboratory right now, and the number of bacteria of type $i$ equals $c_{i}$. For convenience, we will assume that all the bacteria are numbered from $1$ to $n$. The bacteria of type $c_{i}$ are numbered from $(\sum_{k=1}^{i-1}c_{k})+1$ to $\sum_{k=1}^{i}c_{k}$. With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows $m$ ways to move energy from some bacteria to another one. The way with number $i$ can be described with integers $u_{i}$, $v_{i}$ and $x_{i}$ mean that this way allows moving energy from bacteria with number $u_{i}$ to bacteria with number $v_{i}$ or vice versa for $x_{i}$ dollars. Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost. As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix $d$ with size $k × k$. Cell $d[i][j]$ of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type $i$ to bacteria with type $j$.
If the distribution is correct, after deleting all ribs with cost more than 0 graph will transform to components of corrects size. Also, the nodes are numereted so we should turn dfs for the first node of each type and be sure that we receive exact all nodes of this type and no ohter. Now simple floyd warshall, and put in each cell of adjacent matrix of components the minimal weight between all ribs from 1 component to another.
[ "dsu", "graphs", "shortest paths" ]
2,000
null
400
E
Inna and Binary Logic
Inna is fed up with jokes about female logic. So she started using binary logic instead. Inna has an array of $n$ elements $a_{1}[1], a_{1}[2], ..., a_{1}[n]$. Girl likes to train in her binary logic, so she does an exercise consisting of $n$ stages: on the first stage Inna writes out all numbers from array $a_{1}$, on the $i$-th $(i ≥ 2)$ stage girl writes all elements of array $a_{i}$, which consists of $n - i + 1$ integers; the $k$-th integer of array $a_{i}$ is defined as follows: $a_{i}[k] = a_{i - 1}[k] AND a_{i - 1}[k + 1]$. Here AND is bit-wise binary logical operation. Dima decided to check Inna's skill. He asks Inna to change array, perform the exercise and say the sum of all $\textstyle{\frac{n(n+1)}{2}}$ elements she wrote out during the current exercise. Help Inna to answer the questions!
Let's solve this for each bit separately. Fix some bit. Let's put 1 if the number contains bit and 0 otherwise. Now we receive the sequence, for example $11100111101$. Now let's look on sequence of 1 without 0, for this sequence current bit will be added to the sum on the first stage (with all numbers single) on the second stage (with all neighbouring pairs) on the third stage and so on, the number of appiarence for sequence of neighbouring 1 is a formula which depends on the length of sequence only. The last is to learn how to modificate. For each bit let's save the set of sequence of 1. When the bit is deleted, one sequence is sepereted on two, or decreases its length by 1. When the bit is added, new sequence of length 1 appears, or some sequence increases its lentgh by 1 or two sequence transform to 1 biger sequence.
[ "binary search", "bitmasks", "data structures" ]
2,100
null
401
A
Vanya and Cards
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed $x$ in the absolute value. Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found $n$ of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero? You can assume that initially Vanya had infinitely many cards with each integer number from $ - x$ to $x$.
We must sum all numbers, and reduced it to zero by the operations +x and -x.
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int ans, sum, x, n, q; int main() { scanf("%d %d", &n, &x); sum = 0; for (int i = 0; i < n; i++) { cin>>q; sum += q; } sum = abs(sum); ans = sum / x; if (sum % x != 0) ans++; cout<<ans<<endl; }
401
B
Sereja and Contests
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: $Div1$ (for advanced coders) and $Div2$ (for beginner coders). Two rounds, $Div1$ and $Div2$, can go simultaneously, ($Div1$ round cannot be held without $Div2$) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the $Div1$ round is always greater. Sereja is a beginner coder, so he can take part only in rounds of $Div2$ type. At the moment he is taking part in a $Div2$ round, its identifier equals to $x$. Sereja remembers very well that he has taken part in exactly $k$ rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed. Sereja is wondering: what minimum and what maximum number of $Div2$ rounds could he have missed? Help him find these two numbers.
You must identify the array of numbers contests that remember Sereja, as employed. If we want to find maximal answer, we must count the number of immune cells. If we want to find mininum answer, we must do the following: if i-th element is free and (i+1)-th element is free, and i<x then we using round type of "Div1+Div2" and answer++, i-th and (i+1)-th elements define as employed. if i-th element is free and (i+1)-th element is employed then we usign round type "Div2" and answer++, i-th element define as employed.
[ "greedy", "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int min_ans, max_ans, x, k, t, num1, num2, num, a[4001], i; int main() { scanf("%d%d", &x, &k); for (int i = 0; i < k; i++) { scanf("%d", &t); if (t == 1) { scanf("%d%d", &num1, &num2); a[num1] = 1; a[num2] = 1; } if (t == 2) { scanf("%d", &num); a[num] = 1; } } i = 1; while (i < x) { if (a[i] == 0) { if (i + 1 < x && a[i + 1] == 0) { a[i] = 1; a[i + 1] = 1; min_ans++; max_ans += 2; i+=2; } else { a[i] = 1; max_ans++; min_ans++; i++; } } else i++; } printf("%d %d", min_ans, max_ans); }
401
C
Team
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying \textbf{all} the cards in a row so that: - there wouldn't be a pair of any side-adjacent cards with zeroes in a row; - there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought $n$ cards with zeroes and $m$ cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
n - the number of cards containing number 0 and m - the number of cards containing number 1. We have answer, when ((n-1)<=m && m <= 2 * (n + 1)). If we have answer then we must do the following: if (m == n - 1) then we derive the ones and zeros in one, but we must start from zero. if (m == n) then we derive the ones and zeros in one. if (m > n && m <= 2 * (n + 1)) then we must start form one and we derive the ones and zeros in one, but in the end must be one. And if we in the end and we have ones, then we try to stick to one unit so that we have. For example, we have 10101 and two ones, after we have 110101 and one ones, and then we have 1101101.
[ "constructive algorithms", "greedy", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; long long n, m, t, a[3000001], k; int main() { scanf("%d%d", &n, &m); if (n - 1 <= m && m <= 2*(n + 1)) { if (m == n - 1) { a[0] = -1; a[m + 1] = -1; t = n - 1; } else if (m == n) { a[m + 1] = -1; t = n; } else t = n + 1; k = m % t; if (k == 0 && m != t) k = n + 1; if (a[0] == -1) cout<<"0"; for (int i = 1; i <= n; i++) { if (a[i] != -1){ if (k > 0) cout<<"110"; else cout<<"10"; k--; } } if (a[m + 1] != -1) { if (k > 0) cout<<"11"<<endl; else cout<<"1"<<endl; } } else cout<<"-1"<<endl; }
401
D
Roman and Numbers
Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number $n$, modulo $m$. Number $x$ is considered close to number $n$ modulo $m$, if: - it can be obtained by rearranging the digits of number $n$, - it doesn't have any leading zeroes, - the remainder after dividing number $x$ by $m$ equals 0. Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.
This problem we can be attributed to the dynamic programming. We must using mask and dynamic. We have dynamic dp[i][x], when i - mask of reshuffle and x - remainder on dividing by m. if we want to add number a[j], we must using it: dp[i or (1 shl (j-1)),(x*10+a[j]) mod m] := dp[i or (1 shl (j-1)),(x*10+a[j]) mod m] + dp[i,x]; In the end we must answer to divide by the factorial number of occurrences of each digit.
[ "bitmasks", "brute force", "combinatorics", "dp", "number theory" ]
2,000
var l,ans,n,m,q,ost,q1:int64; i,j,t,p,x:longint; s:string; ok:boolean; a,qq:array [0..300000,0..101] of int64; aa,kol:array [0..200] of longint; begin read(q1,m); str(q1,s); l:=length(s); for i:=1 to l do begin val(s[i],aa[i],p); inc(kol[aa[i]]); end; for i:=1 to l do if aa[i]>0 then a[1 shl (i-1),aa[i] mod m]:=1; q:=(1 shl (l))-1; for i:=1 to q do begin for j:=1 to l do begin if ((1 shl (j-1)) and i=0) then begin ok:=true; for x:=1 to j-1 do if (aa[j]=aa[x]) and ((1 shl (x-1)) and i=0) then begin ok:=false; break; end; for x:=j+1 to l do if (aa[j]=aa[x]) and ((1 shl (x-1)) and i>0) then begin ok:=false; break; end; if not(ok) then continue; inc(qq[i,0]); qq[i,qq[i,0]]:=j; end; end; end; for i:=1 to q do begin for j:=0 to m-1 do begin if a[i,j]=0 then continue; for t:=1 to qq[i,0] do begin ost:=(j*10+aa[qq[i][t]]) mod m; inc(a[i+(1 shl (qq[i][t]-1)),ost],a[i][j]); end; end; end; writeln(a[q][0]); end.
401
E
Olympic Games
This problem was deleted from the contest, because it was used previously at another competition.
If first participant of the contest will contain at point (x1;y1) and second participant of the contest will contain at point (x2;y2), then we need to satisfy two conditions: L*L <= (abs(x1-x2)*abs(x1-x2) + abs(y1-y2)*abs(y1-y2)) <= R*R gcd(abs(x1-x2),abs(y1-y2)) == 1 Since the hall can potentially be of size 100,000 x 100,000, even considering each possible size of R or L once will take too much time. And if we iterate value abs(x1-x2) and iterate value abs(y1-y2) then it will take much time too. But if we iterate only value abs(x1-x2) we can find confines of value abs(y1-y2). We can do so: L*L<=(abs(x1-x2)*abs(x1-x2)+abs(y1-y2)*abs(y1-y2))<=R*R L*L - abs(x1-x2)*abs(x1-x2) <= abs(y1-y2)*abs(y1-y2) <= R*R - abs(x1-x2)*abs(x1-x2) Number of options to place the square in hall n*m will be (n-abs(x1-x2)+1)*(m-abs(y1-y2)+1). The first quantity is easy to obtain, while the second requires a little more work. To calculate the second quantity, we note that, although w could have a large variety of prime divisors, it does not have very many of them. This important insight allows us to quickly find the sum: we find the prime factors of w, then we use the inclusion-exclusion principle to calculate the sum of all numbers between L and R that are divisible by at least one of the numbers.
[ "math" ]
2,500
#include <bits/stdc++.h> #define nmax 100005 typedef long long ll; ll m, n, l, r, p, num[nmax], d[nmax][6], ans, ii; ll tt(ll ql, ll qh, ll mm) { qh = qh / mm; ql = (ql + mm - 1) / mm; return ((qh - ql + 1) * (n + 1) - mm * ((qh * (qh + 1) - (ql - 1) * ql) / 2)) % p; } int main() { scanf("%lld%lld", &n, &m); scanf("%lld%lld%lld", &l, &r, &p); for(int i = 2; i <= m; i++) if(num[i] == 0) for(int j = i; j <= m; j += i) d[j][num[j]++] = i; ll lo = l; ll hi = r; ll minn = (m < r ? m : r); for(ll w = 1; w <= minn; w++) { while(lo > 1 && l*l - w*w <= (lo-1)*(lo-1)) lo--; while(r*r - w*w < hi*hi) hi--; if(lo <= hi && lo <= n) { ll a = 0; int t = (1 << num[w]); for(int i = 0; i < t; i++) { ii = i; ll p1 = 1; ll p2 = 1; for(int j = 0; j < num[w]; j++) { if(ii & 1) { p1 *= d[w][j]; p2 *= -1; } ii >>= 1; } a += p2 * tt(lo, hi < n ? hi : n, p1); } ans = (ans + a*(m-w+1)) % p; if(ans < 0) ans += p; } } if(l <= 1 && r >= 1) ans = (2 * ans + m * (n + 1) + n * (m + 1)) % p; else ans = (2 * ans) % p; printf("%d\n", ans); }
402
A
Nuts
You have $a$ nuts and lots of boxes. The boxes have a wonderful feature: if you put $x$ $(x ≥ 0)$ divisors (the spacial bars that can divide a box) to it, you get a box, divided into $x + 1$ sections. You are minimalist. Therefore, on the one hand, you are against dividing some box into more than $k$ sections. On the other hand, you are against putting more than $v$ nuts into some section of the box. What is the minimum number of boxes you have to use if you want to put all the nuts in boxes, and you have $b$ divisors? Please note that you need to minimize the number of used boxes, not sections. You do not have to minimize the number of used divisors.
Let's fix some value of boxes $ans$. After that we can get exactly $cnt = ans + min((k - 1) * ans, B)$ of sections. So, if $cnt * v \ge a$, then $ans$ be an answer. After that you can use brute force to find smallest possible value of $ans$.
[ "greedy", "math" ]
1,100
null
402
B
Trees in a Row
The Queen of England has $n$ trees growing in a row in her garden. At that, the $i$-th $(1 ≤ i ≤ n)$ tree from the left has height $a_{i}$ meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all $i$ $(1 ≤ i < n)$, $a_{i + 1} - a_{i} = k$, where $k$ is the number the Queen chose. Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?
Let's fix height of the first tree: let's call it $a$. Of course, $a$ is an integer from segment $[1, 1000]$. After that, for the fixed height $a$ of the first tree we can calculate heights of the others trees: $a, a + k, a + 2k$, and so on. After that you should find minimal number of operations $ans$ to achive such heights. After that we can use brute force to find smallest possible $ans$ for each $a$ from $1$ to $1000$. For best height of the first tree you should print all operations.
[ "brute force", "implementation" ]
1,400
null
402
C
Searching for Graph
Let's call an undirected graph of $n$ vertices $p$-interesting, if the following conditions fulfill: - the graph contains exactly $2n + p$ edges; - the graph doesn't contain self-loops and multiple edges; - for any integer $k$ ($1 ≤ k ≤ n$), any subgraph consisting of $k$ vertices contains at most $2k + p$ edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a $p$-interesting graph consisting of $n$ vertices.
I will describe two solutions. First. Consider all pairs $(i, j)$ ($1 \le i < j \le n$). After you should ouput the first $2n + p$ pairs in lexicographical order. It's clear to understand, that it is enough to prove, that $0$-interesting graph is correct or $- 3$ -interesting graph is correct. We will prove for $- 3$ -interesting graph, that it is correct. This graph consists of triangles, which have an common edge $1$ - $2$. Let's fix some subset of vertexes, which does not contains vertexes $1$ and $2$. In such sets there are no edges. Let's fix some subset, which contains exactly one vertex ($1$ or $2$). In such subsets there are exactly $k - 1$ edges, where $k$ is the size of such subset. In other subset there are exactly 2 * (k - 2) + 1 edges, where $k$ is the size of such subset. Second. Let's use some brute force, to build graphs with $0$-interesting graphs with sizes $5, 6, 7, 8, 9$ vertexes. Now, to build $p$-interesting graph with $n$ vertexes, We will build $0$-interesting graph, and after that we will add to it $p$ another edges, which is not in the graph. We will build $0$-interesting graphs using the following approach: Let's took $k$ disjointed components, from graphs with number of vertexes from $5$ to $9$, in such way that there are exactly $n$ vertexes in graph.
[ "brute force", "constructive algorithms", "graphs" ]
1,500
null
402
D
Upgrading Array
You have an array of positive integers $a[1], a[2], ..., a[n]$ and a set of bad prime numbers $b_{1}, b_{2}, ..., b_{m}$. The prime numbers that do not occur in the set $b$ are considered good. The beauty of array $a$ is the sum $\sum_{i=1}^{n}f(a[i])$, where function $f(s)$ is determined as follows: - $f(1) = 0$; - Let's assume that $p$ is the minimum prime divisor of $s$. If $p$ is a good prime, then $f(s)=f(\frac{s}{p})+1$, otherwise $f(s)=f(\frac{s}{p})-1$. You are allowed to perform an arbitrary (probably zero) number of operations to improve array $a$. The operation of improvement is the following sequence of actions: - Choose some number $r$ ($1 ≤ r ≤ n$) and calculate the value $g$ = GCD($a[1], a[2], ..., a[r]$). - Apply the assignments: $a[1]={\frac{a|1}{g}}$, $a[2]={\frac{a|2|}{g}}$, $...$, $a[r]={\frac{a|r|}{g}}$. What is the maximum beauty of the array you can get?
I will describe two solutions. First. Dynamic programming approach. Let's calculate an DP $d[i][j]$ - which is the best possible answer we can achieve, if current prefix has length $i$ and we used operation of Upgrading last time in position $j$. It is clear to understand, that we should iterate $i$ from $n$ to $1$, and $j$ from $n$ to $i$. There are only two transitions: First, $d[i - 1][j] = max(d[i - 1][j], d[i][j])$ - we will not use operation of upgrading of array in the current position. Second, $d[i - 1][i - 1] = max(d[i - 1][i - 1], d[i][j] + f(tgcd[j]) * i - f(tgcd[i - 1]) * i$ - we are using an operation of upgrading. $f(a)$ - is a beauty of the number. $tgcd[i]$ - $gcd$ of all numbers on the prefix of length $i$. You can use function, which works in $O({\sqrt{(a)}})$ to calculate the beauty. Also you can make your solution more faster, it you will precalculate some small primes. Also you can use $map < int, int >$ to store calculated values. DP base $d[n][n] = curBeauty$ - is a current beauty of the array. Second. Greedy. Let's find position $r$, which can upgrade our answer. If there some values of $r$ - we will take most right position. We will add this position to the answer and upgrade our answer. Why it's correct? Let's fix an optimal solution (sequence of position, where we used an upgrading operation) $r_{1} > r_{2} > ... > r_{k}$. Also we have an solution which was built by using greedy $l_{1} > l_{2} > ... > l_{m}$. It's clear, that $r_{1} \le l_{1}$, because all position with $> l_{1}$ cannot upgrade anything (otherwise greedy will choose it as first position). In other hand, $r_{1} \ge l_{1}$, because otherwise we can upgrade in position $l_{1}$ and make answer better. So, $r_{1} = l_{1}$, and after that we can use our propositions for big indexes $i$.
[ "dp", "greedy", "math", "number theory" ]
1,800
null
402
E
Strictly Positive Matrix
You have matrix $a$ of size $n × n$. Let's number the rows of the matrix from $1$ to $n$ from top to bottom, let's number the columns from $1$ to $n$ from left to right. Let's use $a_{ij}$ to represent the element on the intersection of the $i$-th row and the $j$-th column. Matrix $a$ meets the following two conditions: - for any numbers $i, j$ ($1 ≤ i, j ≤ n$) the following inequality holds: $a_{ij} ≥ 0$; - $\textstyle\sum_{i=1}^{n}a_{i i}>0$. Matrix $b$ is strictly positive, if for any numbers $i, j$ ($1 ≤ i, j ≤ n$) the inequality $b_{ij} > 0$ holds. You task is to determine if there is such integer $k ≥ 1$, that matrix $a^{k}$ is strictly positive.
Let's look at the matrix $a$ as a connectivity matrix of some graph with n vertices. Moreover, if $a_{ij} > 0$, then we have directed edge in the graph between nodes $(i, j)$. Otherwise, if $a_{ij} = 0$ that graph does not contains directed edge between pair of nodes $(i, j)$. Let $b = a^{k}$. What does $b_{ij}$ means? $b_{ij}$ is the number of paths of length exactly $k$ in our graph from vertex $i$ to vertex $j$. Let $pos$ is an integer, such that $a[pos][pos] > 0$. That is, we have a loop in the graph. So, if from the vertex $pos$ achievable all other vertexes and vice versa, from all other vertices reachable vertex $pos$, then the answer is $YES$, otherwise the answer is $NO$. If reachability is missing, it is clear that for any $k$ $a^{k}_{ipos} = 0$. If reachability there, we will be able to reach self-loop, use self-loop "to twist", and after that we will go to some another vertex.
[ "graphs", "math" ]
2,200
null
403
D
Beautiful Pairs of Numbers
The sequence of integer pairs $(a_{1}, b_{1}), (a_{2}, b_{2}), ..., (a_{k}, b_{k})$ is beautiful, if the following statements are fulfilled: - $1 ≤ a_{1} ≤ b_{1} < a_{2} ≤ b_{2} < ... < a_{k} ≤ b_{k} ≤ n$, where $n$ is a given positive integer; - all numbers $b_{1} - a_{1}$, $b_{2} - a_{2}$, $...$, $b_{k} - a_{k}$ are distinct. For the given number $n$ find the number of beautiful sequences of length $k$. As the answer can be rather large, print the remainder after dividing it by $1000000007$ $(10^{9} + 7)$.
First, we can note, that length of sequence is not greater then $50$. Ok, but why? Because all numbers $b_{i} - a_{i}$ are different, so $0 + 1 + ... + 50 > 1000$. Let's imagine, that sequence from input is a sequence of non-intersecting segments. So, $c_{i} = b_{i} - a_{i} + 1$ is length of segment $i$. Also, $\textstyle\sum_{i}c_{i}\leq n$. After that let's calculate the following DP: $d[i][j][k]$ - - number of sequences for which following holds: $c_{1} < c_{2} < ... < c_{i}$, $c_{i} \ge 1$ , $c_{1} + c_{2} + ... + c_{i} = j$ and maximal number is less then $k$ (upper bound of sequence). This DP will helps us to calculate number of ways to set length to each segment in sequence. It's simple to calculate such DP: base $d[0][0][1] = 1$, $d[i][j][k + 1] = d[i][j][k + 1] + d[i][j][k]$ - we increase upper bound of sequence; $d[i + 1][j + k][k + 1] = d[i + 1][j + k][k + 1] + d[i][j][k]$ - we are adding upper bound to the sequence. We can calculate such DP, by using only $O(N^{2})$ of memory, where $N = 1000$. After that we should multiply $d[i][j][k]$ on $i!$, because we need number of sequences $c_{i}$, where order does not matter. After that we can calculate answer for $n, k$. Let's $s u m[l e n]=\sum_{x}d[k][l e n][x]$, where $x$ - some upper bound of sequences. After that we should calculate next number: how many ways to set to distances between segments? It's clear, that we can increase distance between some segments, but we have only $n - len$ such operations. It's well known, that answer number of ways equals to $C(n - len + k, k)$. So, for each $n$ we should sum by $len$ following values: $sum[len] * C(n - len + k, k)$. Note, that we need array $C[n][k]$ (binomials) where $n \le 2000, k \le 2000$.
[ "combinatorics", "dp" ]
2,300
null
403
E
Two Rooted Trees
You have two rooted undirected trees, each contains $n$ vertices. Let's number the vertices of each tree with integers from $1$ to $n$. The root of each tree is at vertex $1$. The edges of the first tree are painted blue, the edges of the second one are painted red. For simplicity, let's say that the first tree is blue and the second tree is red. Edge ${x, y}$ is called bad for edge ${p, q}$ if two conditions are fulfilled: - The color of edge ${x, y}$ is different from the color of edge ${p, q}$. - Let's consider the tree of the same color that edge ${p, q}$ is. Exactly one of vertices $x$, $y$ lies both in the subtree of vertex $p$ and in the subtree of vertex $q$. In this problem, your task is to simulate the process described below. The process consists of several stages: - On each stage edges of exactly one color are deleted. - On the first stage, exactly one blue edge is deleted. - Let's assume that at the stage $i$ we've deleted edges ${u_{1}, v_{1}}$, ${u_{2}, v_{2}}$, $...$, ${u_{k}, v_{k}}$. At the stage $i + 1$ we will delete all undeleted bad edges for edge ${u_{1}, v_{1}}$, then we will delete all undeleted bad edges for edge ${u_{2}, v_{2}}$ and so on until we reach edge ${u_{k}, v_{k}}$. For each stage of deleting edges determine what edges will be removed on the stage. Note that the definition of a bad edge always considers the initial tree before it had any edges removed.
First, for each vertex of the first and second tree we calculate two values $in[s]$, $out[s]$ - the entry time and exit time in dfs order from vertex with number $1$. Also with each edge from both trees we will assosiate a pair $(p, q)$, where $p = min(in[u], in[v])$, $q = max(in[u], in[v])$ (values $in, out$ for each vertex we take from tree with another color). Now for each tree we will build two segment trees (yes, totally 4 segment trees). In first segment will store all pairs in following way: we will store a pair in node of segment tree if and only if (node of segment tree is a segment $(l, r)$) left element of pair lies in segment $(l, r)$. In second segment tree we will store a pair if and only if right element of the pair lies in segment $(l, r)$ All pairs in segment trees we will store in some order (in first segment tree - increasing order, in the second tree - decreasing order). Such trees use $O(n\log(n))$ of memory, also you can build it in $O(n\log(n))$. Good. How to answer on query $(l, r)$ - erase all edges from tree for which exactly one vertex have value $in[s]$ in segment $(l, r)$? We will go down in our segment tree. Let's imagine, that now we in some node of segment tree. Because we store all pairs in the first segment tree in increasing order of the right element, so answer to the query is a some suffix of the array of pairs. After we can add they to the answer (if it not erased yet). After that we should modify our segment tree: for each node, where we work with suffixes, we should erase all pairs from such suffix. So, this solution in $O(n\log(n))$.
[ "data structures", "implementation", "trees" ]
2,900
#include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <list> #include <vector> #include <string> #include <deque> #include <bitset> #include <algorithm> #include <utility> #include <functional> #include <limits> #include <numeric> #include <complex> #include <cassert> #include <cmath> #include <memory.h> #include <cstdio> #include <cstdlib> #include <cstring> //#include <ctime> using namespace std; typedef long long li; typedef long double ld; typedef pair<int,int> pt; typedef pair<ld, ld> ptd; typedef unsigned long long uli; #define pb push_back #define mp make_pair #define mset(a, val) memset(a, val, sizeof (a)) #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #define ft first #define sc second #define sz(a) int((a).size()) #define x first #define y second template<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); } template<typename X> inline X sqr(const X& a) { return (a * a); } template<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; } template<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; } template<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << ", " << p.sc << ')'; } inline int nextInt() { int x; if (scanf("%d", &x) != 1) throw; return x; } inline li nextInt64() { li x; if (scanf("%I64d", &x) != 1) throw; return x; } inline double nextDouble() { double x; if (scanf("%lf", &x) != 1) throw; return x; } #define forn(i, n) for(int i = 0; i < int(n); i++) #define fore(i, a, b) for(int i = int(a); i <= int(b); i++) #define ford(i, n) for(int i = int(n - 1); i >= 0; i--) #define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++) const int INF = int(1e9); const li INF64 = li(INF) * li(INF); const ld EPS = 1e-9; const ld PI = ld(3.1415926535897932384626433832795); const int N = 2 * 1000 * 100 + 10; int n; pt edges[2][N]; int in[2][N], out[2][N], cur[N], szcur, curtime, szncur, ncur[N]; int used[2][N]; vector < int > g[2][N]; vector < pt > tv1[2][2 * N], tv2[2][2 * N]; vector < pt > t[4][8 * N]; inline bool read() { n = nextInt(); forn(it, 2) { forn(i, n - 1) { int a = nextInt() - 1; int b = i + 1; edges[it][i] = mp(a, b); g[it][a].pb(b); g[it][b].pb(a); } } int i = nextInt() - 1; cur[szcur ++] = i; return true; } void go(int id, int s, int prev = -1) { in[id][s] = curtime++; forn(i, sz(g[id][s])) { int to = g[id][s][i]; if (to == prev) continue; go(id, to, s); } out[id][s] = curtime ++; } void buildByFt(int v, int tl, int tr, int id) { if (tl == tr) { t[id][v] = tv1[id][tl]; sort(all(t[id][v])); return; } int mid = (tl + tr) >> 1; buildByFt((v << 1), tl, mid, id); buildByFt((v << 1) + 1, mid + 1, tr, id); int i = 0; int j = 0; int szt = 0; int szt1 = sz(t[id][(v << 1)]); int szt2 = sz(t[id][(v << 1) + 1]); int allszt = sz(t[id][(v << 1)]) + sz(t[id][(v << 1) + 1]); t[id][v].resize(allszt); while (szt < allszt) { if (i < szt1 && j < szt2) { if (t[id][(v << 1)][i] <= t[id][(v << 1) + 1][j]) { t[id][v][szt++] = t[id][(v << 1)][i]; i++; } else { t[id][v][szt++] = t[id][(v << 1) + 1][j]; j++; } continue; } if (i < szt1) { t[id][v][szt++] = t[id][(v << 1)][i]; i++; } if (j < szt2) { t[id][v][szt++] = t[id][(v << 1) + 1][j]; j++; } } } void buildBySc(int v, int tl, int tr, int id) { if (tl == tr) { t[id + 2][v] = tv2[id][tl]; sort(all(t[id + 2][v])); reverse(all(t[id + 2][v])); return; } int mid = (tl + tr) >> 1; buildBySc((v << 1), tl, mid, id); buildBySc((v << 1) + 1, mid + 1, tr, id); id += 2; int i = 0; int j = 0; int szt = 0; int szt1 = sz(t[id][(v << 1)]); int szt2 = sz(t[id][(v << 1) + 1]); int allszt = sz(t[id][(v << 1)]) + sz(t[id][(v << 1) + 1]); t[id][v].resize(allszt); while (szt < allszt) { if (i < szt1 && j < szt2) { if (t[id][(v << 1)][i] >= t[id][(v << 1) + 1][j]) { t[id][v][szt++] = t[id][(v << 1)][i]; i++; } else { t[id][v][szt++] = t[id][(v << 1) + 1][j]; j++; } continue; } if (i < szt1) { t[id][v][szt++] = t[id][(v << 1)][i]; i++; } if (j < szt2) { t[id][v][szt++] = t[id][(v << 1) + 1][j]; j++; } } } void get(int v, int tl, int tr, int l, int r, int id, int tvalue) { if (l > r) return; if (l == tl && r == tr) { if (id < 2) { while (!t[id][v].empty()) { pt s = t[id][v].back(); if (s.ft > tvalue) { if (!used[id & 1][s.sc]) { used[id & 1][s.sc] = 1; ncur[szncur++] = s.sc; } t[id][v].pop_back(); } else break; } } else { while (!t[id][v].empty()) { pt s = t[id][v].back(); if (s.ft < tvalue) { if (!used[id & 1][s.sc]) { used[id & 1][s.sc] = 1; ncur[szncur++] = s.sc; } t[id][v].pop_back(); } else break; } } return; } int mid = (tl + tr) >> 1; get((v << 1), tl, mid, l, min(r, mid), id, tvalue); get((v << 1) + 1, mid + 1, tr, max(l, mid + 1), r, id, tvalue); } inline void solve() { curtime = 0; go(0, 0); curtime = 0; go(1, 0); forn(it, 2) forn(i, n - 1) { int u = edges[it][i].ft; int v = edges[it][i].sc; int dv1 = in[it ^ 1][u]; int dv2 = in[it ^ 1][v]; if (dv1 > dv2) swap(dv1, dv2); tv1[it][dv1].pb(mp(dv2, i)); tv2[it][dv2].pb(mp(dv1, i)); } forn(it, 2) buildByFt(1, 0, 2 * n - 1, it); forn(it, 2) buildBySc(1, 0, 2 * n - 1, it); int idx = 0; forn(i, szcur) used[0][cur[i]] = 1; while(true) { if (szcur == 0) break; if (idx & 1) puts("Red"); else puts("Blue"); sort(cur, cur + szcur); forn(i, szcur) { if (i) printf(" "); printf("%d", cur[i] + 1); } puts(""); forn(i, szcur) { int u = edges[idx][cur[i]].ft; int v = edges[idx][cur[i]].sc; } forn(i, szcur) { int u = edges[idx][cur[i]].ft; int v = edges[idx][cur[i]].sc; int l, r; if (out[idx][u] > out[idx][v]) l = in[idx][v], r = out[idx][v]; else l = in[idx][u], r = out[idx][u]; if (!(idx & 1)) get(1, 0, 2 * n - 1, l, r, 1, r), get(1, 0, 2 * n - 1, l, r, 3, l); else get(1, 0, 2 * n - 1, l, r, 0, r), get(1, 0, 2 * n - 1, l, r, 2, l); } idx ^= 1; forn(i, szncur) cur[i] = ncur[i]; szcur = szncur; szncur = 0; } } int main() { #ifdef gridnevvvit freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif cout << setprecision(10) << fixed; cerr << setprecision(5) << fixed; assert(read()); solve(); }
404
A
Valera and X
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals $n$ squares ($n$ is an odd number) and each unit square contains some small letter of the English alphabet. Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if: - on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.
In this problem it was needed to check the constraints described in statement. You can use two sets here. You should insert diagonal elements of matrix into the first set, and the other elements into the second. Element $a_{i, j}$ belongs to the main diagonal if $i = j$ and belongs to the secondary diagonal if $i = n - j + 1$. After you split all elements into sets you should check if the sets sizes are equal to one and the elements from this sets differ from each other.
[ "implementation" ]
1,000
null
404
B
Marathon
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates $(0, 0)$ and the length of the side equals $a$ meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each $d$ meters of the path. We know that Valera starts at the point with coordinates $(0, 0)$ and runs counter-clockwise. That is, when Valera covers $a$ meters, he reaches the point with coordinates $(a, 0)$. We also know that the length of the marathon race equals $nd + 0.5$ meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers $d, 2·d, ..., n·d$ meters.
Let's notice that after Valera run $4 \cdot a$ meters he will be in the same point from which he started. Valera will have run $i \cdot d$ meters before he gets $i$-th bottle of drink. Let's calculate the value $c=\lfloor{\frac{i\,d}{4\,a}}\rfloor$ - how many laps he will run. Then he have already run $L = i \cdot d - c \cdot 4 \cdot a$ meters on his last lap. It is easy to get Valera's position from this $L$. For example, if $2 \cdot a \le L \le 3 \cdot a$ then Valera will be in the point with coordinates $(3 \cdot a - L, a)$. You can consider the other three cases in the same manner.
[ "implementation", "math" ]
1,500
null
404
C
Restore Graph
Valera had an undirected connected graph without self-loops and multiple edges consisting of $n$ vertices. The graph had an interesting property: there were at most $k$ edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to $n$. One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array $d$. Thus, element $d[i]$ of the array shows the shortest distance from the vertex Valera chose to vertex number $i$. Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array $d$. Help him restore the lost graph.
First of all let us notice that it must be only one $0$ in $d$. Also $d[start] = 0$ means that $start$ is the vertex from which Valera calculated the distance to the other vertices. Let's notice that every vertex $u$ with $d[u] = i$ must be adjacent only to the vertices $v$ such that $d[v] \ge i - 1$. Besides there is always must be such neighboor $v_{0}$ of $u$, that $d[v_{0}] = i - 1$. Let's build sought graph by adding one vertex to the existing graph. We will add vertex in order of increasing their distance to $start$. Initially, we have one vertex with number $start$ in our graph. When we add vertex $u$ with $d[u] = i$ let's consider such vertices $v$ that $d[v] = i - 1$. Let's choose the vertex with minimal degree among them. If this value is equal to $k$, then there is no solution. In other case let's add $u$ to our graph and add the edge $(u, v)$ to the answer. If there are no vertices with distance $i - 1$ to $start$ then the answer is also $- 1$. If everything fine we will get the answer which is tree, so the number of edges in it equals $n - 1 \le 10^{6}$.
[ "dfs and similar", "graphs", "sortings" ]
1,800
null
404
D
Minesweeper 1D
Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is $n$ squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of $n$ cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.
This problem can be solved by using dynamic programming. Let's calculate $d[i][type]$ - the number of correct ways to fill the prefix of length $i$ so that the last filled cell has one of the $5$ types. These types are the following: the cell contains "0" the cell contains "1" and the cell to the left of it contains bomb the cell contains "1" and the cell to the left of it doesn't contain bomb the cell contains "2" the cell contains bomb When we try to fill next cell we check two conditions. Firstly value of the filled cell in given string must be equal to either what we want to write or "?". Secondly new prefix must remain filled correct. For example, if we are in state $(i, 1)$ (it means that the cell $i$ contains "0") then we can fill next cell by "0" and go to the state $(i + 1, 1)$ or fill next cell by "1" and go to the state $(i + 1, 3)$. We cannot write "2" because both neighbours of the cell with "2" must contain bomb. Obvious, we cannot place bomb after "0". Note that, when we place "1" after "0" we go to the state $(i + 1, 3)$, but when we place "1" after bomb we go to the state $(i + 1, 2)$. You can consider other ways of going from one state to another in the same manner.
[ "dp", "implementation" ]
1,900
null
404
E
Maze 1D
Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number $0$ has a robot. The robot has instructions — the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number $0$. If the robot should go into the cell with an obstacle according the instructions, it will skip this move. Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once — at its last move. Moreover, the latter move cannot be skipped. Let's assume that $k$ is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose $k$ obstacles and the finishing cell so that the robot is able to complete the instructions successfully.
Let's consider the case when the last move of the robot is equal to "R". If the last move is equal to "L" then we can replace all "L" by "R" and vise versa and the answer doesn't change. Let's show that Valera doesn't need more than one obstacle. Suppose Valera placed obstacles somewhere. We will say that the number of obstacle is the number of cell containing it. Let's consider the rightmost obstacle $obs1$ among the obstacles with negative numbers and the leftmost obstacle $obs2$ among the obstacles with positive numbers. Obvious robot cannot go to the left of $obs1$ and to the right of $obs2$. So the needed number of obstacles is not greater than two. Let's show that Valera doesn't need to place obstacles to the cells with numbers greater than zero. Suppose he place obstacle to the cell with number $a > 0$. If robot doesn't try to go to this cell then its obstacle is out of place. If robot try to go to this cell then it will visit finish cell more than once. It is because robot needs to go to the right on its last move, but it can't do it from cell $a - 1$ and it has already visited all cells to the left of $a$. So Valera doesn't need more than one obstacle and its obstacle must have number less than zero. Let's now check if Valera can do without obstacles. If so the robot won't skip moves and will stop in some cell. Than Valera can choose this cell as finish and the answer will be one. We have to consider only one case when Valera must place one obstacle. Firstly let's notice that if Valera place obstacle to some cell, the finish cell can be restored uniquely. It means that the number of ways to choose where to place obstacles and finish cell is equal to the number of ways to choose one cell to place one obstacle. Suppose Valera placed obstacle in the cell with number $b < 0$ and robot completed its instructions successfully. Notice, that in that case robot skipped some moves of type "L", completed all moves of type "R" and went to the right on its last move to the unvisited cell. If we shift Valera's obstacle to the right on one cell then robot is going to skip not less moves of type "L" than in the previous case. It means that the finish cell can either go to the right or remains the same. But last time robot visited this cell on its last move, so it is going to visit a new finish cell on its last move either. This means that there is such cell $p < 0$ that if Valera place obstacle to the cells $c \ge p$ then robot will be able to complete its instructions successfully, but if Valera place obstacle to the cells $d < p$ then robot will not. This cell $p$ can be found by using binary search and simple simulation on each iteration. Time complexity is $O(n log n)$.
[ "binary search", "greedy", "implementation" ]
2,200
null
405
A
Gravity Flip
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are $n$ columns of toy cubes in the box arranged in a line. The $i$-th column contains $a_{i}$ cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange. Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the $n$ columns after the gravity switch!
Observe that in the final configuration the heights of the columns are in non-decreasing order. Also, the number of columns of each height remains the same. This means that the answer to the problem is the sorted sequence of the given column heights. Solution complexity: $O(n)$, since we can sort by counting.
[ "greedy", "implementation", "sortings" ]
900
null
405
B
Domino Effect
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play \underline{with} the dominoes and make a "domino show". Chris arranges $n$ dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!
If the first pushed domino from the left was pushed to the left at position $l$, all dominoes at prefix $[1;l]$ fall down, otherwise let $l$ be 0. Similarly, if the first pushed domino from the right was pushed to the right at position $r$, all dominoes at suffix $[r;n]$ also fall down, otherwise let $r$ be $n + 1$. Now, in the segment $(l;r)$ there will remain vertical dominoes and blocks of dominoes supported by the equal forces from both sides. When does a domino at position $p$ in segment $(l, r)$ remains standing vertically? One way is that it is not pushed by any other domino. This could be easily checked by looking at the pushed dominoes closest to $p$ (from both sides). It is pushed by dominoes, only if the closest from the left was pushed to the right, and the closest from the right was pushed to the left. Suppose these dominoes are at positions $x$ and $y$, $x < p < y$. Then, the only way that the domino is still standing is if it is positioned at the center of the block $[x;y]$, which could be checked by ${\frac{x+y}{2}}=p$. Solution complexity: $O(n) / O(n^{2})$, depends on implementation.
[]
1,100
null
405
C
Unusual Product
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the \underline{unusual square} of a square matrix. The \underline{dot product} of two integer number vectors $x$ and $y$ of size $n$ is the sum of the products of the corresponding components of the vectors. The \underline{unusual square} of an $n × n$ square matrix $A$ is defined as the sum of $n$ dot products. The $i$-th of them is the dot product of the $i$-th row vector and the $i$-th column vector in the matrix $A$. Fortunately for Chris, he has to work only in $GF(2)$! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix $A$ is binary: each element of $A$ is either 0 or 1. For example, consider the following matrix $A$: The unusual square of $A$ is equal to $(1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0$. However, there is much more to the homework. Chris has to process $q$ queries; each query can be one of the following: - given a row index $i$, flip all the values in the $i$-th row in $A$; - given a column index $i$, flip all the values in the $i$-th column in $A$; - find the unusual square of $A$. To flip a bit value $w$ means to change it to $1 - w$, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix $A$, output the answers for each query of the third type! Can you solve Chris's homework?
Written as a formula, the problem asks to find the value of $\sum_{i=1}^{n}\sum_{j=1}^{n}A_{i j}A_{j i}{\mathrm{~(mod~}}2)$ Suppose that $i \neq j$. Then the sum contains summands $A_{ij}A_{ji}$ and $A_{ji}A_{ij}$. Since the sum is taken modulo 2, these summands together give 0 to the sum. It follows that the expression is always equal to the sum of the diagonal bits: $\sum_{i=1}^{n}A_{i i}^{2}{\mathrm{~(mod~2)}}=\sum_{i=1}^{n}A_{i i}{\mathrm{~(mod~2)}}$ Now, each query of type 1 and 2 flips the value of exactly one bit on the diagonal. Thus we can calculate the unusual product of the original matrix, and flip its value after each query of type 1 and 2. Solution complexity: $O(n + q)$, if we don't take the reading of the input into account... :)
[ "implementation", "math" ]
1,600
null
405
D
Toy Sum
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris. There are exactly $s$ blocks in Chris's set, each block has a unique number from 1 to $s$. Chris's teacher picks a subset of blocks $X$ and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset $Y$ from the remaining blocks, that the equality holds: \[ \textstyle\sum_{x\in X}(x-1)=\sum_{y\in Y}(s-y) \] "Are you kidding me?", asks Chris.For example, consider a case where $s = 8$ and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: $(1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7$. However, now Chris has exactly $s = 10^{6}$ blocks. Given the set $X$ of blocks his teacher chooses, help Chris to find the required set $Y$!
Let's define the symmetric number of $k$ to be $s + 1 - k$. Since in this case $s$ is an even number, $k \neq s - k$. Note that $(k - 1) + (s + 1 - k) = s$, i.e., the sum of a number and its symmetric is always $s$. Let's process the given members $x$ of $X$. There can be two cases: If the symmetric of $x$ does not belong to $X$, we add it to $Y$. Both give equal values to the respective sums: $x - 1 = s - (s + 1 - x)$. The symmetric of $x$ belongs to $X$. Then we pick any $y$ that neither $y$ and symmetric of $y$ belong to $X$, and add them to $Y$. Both pairs give equal values to the respective sums, namely $s$. How to prove that in the second step we can always find such $y$? Let the number of symmetric pairs that were processed in the step 1 be $a$, then there remain $\textstyle{\frac{s}{2}}-a$ other pairs. Among them, for $\scriptstyle{\frac{n-a}{2}}$ pairs both members belong to $X$, and for other $\begin{array}{l}{{\frac{3}{2}}-a-{\frac{n-a}{2}}}\end{array}$ pairs none of the members belong to $X$. To be able to pick the same number of pairs for $Y$, as there are in $X$, we should have $\stackrel{\vec{s}}{2}-a-\stackrel{n-a}{2}\ge\frac{n-a}{2},$ which is equivalent to $\textstyle{\frac{s}{2}}\geq n$, as given in the statement. Solution complexity: $O(s) / O(n)$.
[ "greedy", "implementation", "math" ]
1,700
null
405
E
Graph Cutting
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with $n$ vertices (numbered from 1 to $n$) and $m$ edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair. For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph. You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
It can be proved that only graphs with an odd number of edges cannot be partitioned into path of length 2. We will construct a recursive function that solves the problem and also serves as a proof for this statement. The function partition(v) will operate on non-blocked edges. It will partition the component of vertex $v$ connected by the non-blocked edges into paths of length 2. If this component has an odd number of edges, the function will partition all the edges of the component, except one edge $(u, v)$; the function then will return vertex $u$, expecting that the parent function call will assign it to some path. The function works as follows: find all vertices that are adjacent to $v$ by the non-blocked edges, call this set adjacent. Then block all the edges from this set vertices to $v$. For each $u$ in adjacent, call partition(u). Suppose partition(u) returned a vertex $w$. That means we can pair it into the path $(v, u, w)$. Otherwise, if partition(u) does not return anything, we add $u$ to unpaired, since the edge $(v, u)$ is not yet in any path. We can pair any two vertices of this set $u$, $w$ into a single path $(u, v, w)$. We pair as much of them as possible in any order. If from this set a single vertex, $u$, is left unpaired, the function will return $u$. Otherwise the function will not return anything. The function could be implemented as a single DFS: Solution complexity: $O(n + m)$.
[ "dfs and similar", "graphs" ]
2,300
null
406
D
Hill Climbing
This problem has nothing to do with Little Chris. It is about hill climbers instead (and Chris definitely isn't one). There are $n$ hills arranged on a line, each in the form of a vertical line segment with one endpoint on the ground. The hills are numbered with numbers from 1 to $n$ from left to right. The $i$-th hill stands at position $x_{i}$ with its top at height $y_{i}$. For every two hills $a$ and $b$, if the top of hill $a$ can be seen from the top of hill $b$, their tops are connected by a rope. Formally, the tops of two hills are connected if the segment connecting their top points does not intersect or touch any of the other hill segments. Using these ropes, the hill climbers can move from hill to hill. There are $m$ teams of climbers, each composed of exactly two members. The first and the second climbers of the $i$-th team are located at the top of the $a_{i}$-th and $b_{i}$-th hills, respectively. They want to meet together at the top of some hill. Now, each of two climbers move according to the following process: - if a climber is at the top of the hill where the other climber is already located or will come eventually, the former climber stays at this hill; - otherwise, the climber picks a hill to the right of his current hill that is reachable by a rope and \textbf{is the rightmost possible}, climbs this hill and continues the process (the climber can also climb a hill whose top is lower than the top of his current hill). For each team of climbers, determine the number of the meeting hill for this pair!
Note that the path of each hill climber is strictly convex in any case. Let's draw the paths from all hills to the rightmost hill. Then these paths form a tree with the "root" at the top of the rightmost hill. We can apply the Graham scan from the right to the left to find the edges of this tree. Each pop and insert in the stack corresponds to a single edge in the tree. Now it is easy to see that for each team of climbers, we should calculate the number of the lowest common ancestor for the corresponding two vertices in the tree. The size if the tree is $n$, so each query works in $O(\log n)$. Solution complexity: $O(n\log n)$.
[ "dfs and similar", "geometry", "trees" ]
2,200
null
406
E
Hamming Triples
Little Chris is having a nightmare. Even in dreams all he thinks about is math. Chris dreams about $m$ binary strings of length $n$, indexed with numbers from 1 to $m$. The most horrifying part is that the bits of each string are ordered in either ascending or descending order. For example, Chris could be dreaming about the following 4 strings of length 5: The \underline{Hamming distance} $H(a, b)$ between two strings $a$ and $b$ of length $n$ is the number of positions at which the corresponding symbols are different. Сhris thinks that each three strings with different indices constitute a single triple. Chris's delusion is that he will wake up only if he counts the number of such string triples $a$, $b$, $c$ that the sum $H(a, b) + H(b, c) + H(c, a)$ is maximal among all the string triples constructed from the dreamed strings. Help Chris wake up from this nightmare!
Let's look at the Hamming graph of all possible distinct $2n$ strings, where each two strings are connected by an edge with length equal to the Hamming distance between these strings. We can observe that this graph has a nice property: if we arrange the vertices cyclically as a regular $2n$-gon with a side length of 1, then the Hamming distance between two strings is the length of the shortest route between these vertices on the perimeter of the polygon. For example, the figure shows the graph for $n = 3$. The gray edges have length 1, the orange edges have length 2 and the blue edges have length 3. That is the corresponding Hamming distance. Now, we can convert each string coded by a pair $(s, f)$ to an integer $(f + 1) \cdot n - s$. The new numbers will be 0, 1, ..., $2n - 1$ and correspond to the same cyclical order on the perimeter of the polygon. The given strings are mapped to some subset of the vertices. Now we have to find the number of triangles (possibly degenerate) with maximal perimeter in this subgraph. It will be useful to keep the new converted numbers sorted. First, we can figure out what this perimeter could be. If there exists a diameter in the full graph, so that all of the points are on one side of the diameter, the perimeter is $2d$, where $d$ is the length of the longest edge: Then any triangle with two vertices at the longest edge points and the third one being any point has the maximal perimeter. Since the numbers are sorted, the longest edge in this case will be produced by two cyclically adjacent elements, which is not hard to find. If for any diameter this does not hold, then the maximal perimeter is $2n$. This can be proved by taking two different points $a$, $b$ and drawing two diameters with them as endpoints; since it is not the previous case, there shoud be a third point $c$ in area where the perimeter of triangle $a$, $b$, $c$ is $2n$. The tricky part is to count the triples in this case. We do this by working with the diameter $(0, n)$. There can be several cases: A maximum triangle has vertices 0 and $n$. This a simple case: with any other vertex as the third the triangle has perimeter $2n$. A maximum triangle has vertex 0, but not $n$. Then the second vertex should be in interval $[0, n)$, and the third in interval $(n + 1, 2n - 1]$, and the clockwise distance between the second and the third should not exceed $n$ (since then the perimeter of the triangle would be less than $2n$). We count the number of such triples iterating two pointers (one in each of these intervals). For each pointer in the first interval, all points from $n + 1$ till the second pointer will make a maximal perimeter triangle. We similarly solve the case where the maximal triangle has vertex $n$, but not 0. The maximal triangle does not have 0 or $n$ as its vertices. Then one vertex of the triangle should be on one side of diameter $(0, n)$, and two should be on the opposite side. To count them, we iterate a vertex pointer on the first side, say, $(0, n)$; let the diametrally opposite vertex on the opposite side be $x$. Then the second vertex can be any in $[n + 1, s]$, and the third can be any of the $[s, 2n - 1]$. It is easy to calculate these numbers using partial sums on the circle. Note that $s$ can be both the second and the third vertex (since strings can repeat). So we iterate this pointer over all one side vertices and update the answer. Similarly we solve the case where a single vertex is on the other side, and two on this side. One only needs to be careful with the formulas in each case. Solution complexity: $O(m\log m)$, because of the sorting.
[ "implementation", "math", "two pointers" ]
2,800
null
407
A
Triangle
There is a right triangle with legs of length $a$ and $b$. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
In this problem you have to locate the right triangle with cathetuses $a$, $b$ on a plane with its vertices in integer points. If the required layout exists, then cathetus $a$ always can be represented as a vector with integer coordinates $A{x;y}$, and $a^{2} = x^{2} + y^{2}$. Iterate over all possible $x$ ($1 \le x \le a - 1$), check, that $y = sqrt(a^{2} - x^{2})$ is integer. Vector, ortogonal to vector ${x;y}$, is ${ - y;x}$. Take vector $B{ - y / g;x / g}$, where $g = gcd(x, y)$. The triangle can be located on the plane if and only if $b$ % $|B| = 0$, where |B| - length of vector B. The candidate for the answer - triangle $(0;0)(x;y)( - y / g * b / |B|;x / g * b / |B|)$, but don't forget about checking that the hypotenuse isn't parallel to coordinate axes.
[ "brute force", "geometry", "implementation", "math" ]
1,600
null
407
B
Long Path
One day, little Vasya found himself in a maze consisting of $(n + 1)$ rooms, numbered from $1$ to $(n + 1)$. Initially, Vasya is at the first room and to get out of the maze, he needs to get to the $(n + 1)$-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number $i$ $(1 ≤ i ≤ n)$, someone can use the first portal to move from it to room number $(i + 1)$, also someone can use the second portal to move from it to room number $p_{i}$, where $1 ≤ p_{i} ≤ i$. In order not to get lost, Vasya decided to act as follows. - Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room $1$. - Let's assume that Vasya is in room $i$ and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room $p_{i}$), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room $(n + 1)$ in the end.
In this problem you had to simulate route of character in graph. Note that if you are in vertice $i$, then edges in all vertices with numbers less than $i$ are turned to $p_{i}$. It gives us opportunity to see a recurrence formula: let $dp_{i}$ be number of steps, needed to get from vertice $1$ to vertice $i$, if all edges are rotated back, into $p_{i}$. Then $dp_{i + 1} = 2dp_{i} + 2 - dp_{pi}$. Answer will be $dp_{n + 1}$.
[ "dp", "implementation" ]
1,600
null
407
C
Curious Array
You've got an array consisting of $n$ integers: $a[1], a[2], ..., a[n]$. Moreover, there are $m$ queries, each query can be described by three integers $l_{i}, r_{i}, k_{i}$. Query $l_{i}, r_{i}, k_{i}$ means that we should add $\binom{b-l_{i}+k_{i}}{k_{i}}$ to each element $a[j]$, where $l_{i} ≤ j ≤ r_{i}$. Record $\textstyle{\binom{y}{x}}$ means the binomial coefficient, or the number of combinations from $y$ elements into groups of $x$ elements. You need to fulfil consecutively all queries and then print the final array.
In this problem you had to find how to add binomial coefficients in array offline. Let's see, how problem changes due to increasing k from small to big values. 1) All queries have K = 0 Every time you add 1 on subsegment. For solve this task you can add 1 at some array b[] in b[L] 1, then substract 1 from b[R+1], and after doing all queries make array a[] as array of prefix sums of array b[]. 2) All queries have K = 1 Arithmetic progression 1 2 3 4 ... is added on subsegment For solve this task you can add 1 at some array c[] in c[L] 1, then substract 1 from c[R+1], and after doing all queries make array b[] as array of prefix sums of array c[]. Actually you added 1 1 ... 1 on every subsegment at each query. If you will substract (R - L + 1) from c[R+1], and make array a[] as array of prefix sums of array b[], then it will be an answer: 1 1 ... 1 became 1 2 3 ... (R-L+1). 3) K is arbitrary Summaring previous results one can see that if we will do and after that do a[i][j] = a[i][j-1] + a[i+1][j] (making a[i] as array of prefix sums array a[i+1]), a[0] will be the answer. What is C(k + 1 - j + r - l, k + 1 - j)? This number is need for each query affect only on segment L..R, and you can see, why is it so, in Pascal's Triangle.
[ "brute force", "combinatorics", "implementation", "math" ]
2,500
null
407
D
Largest Submatrix 3
You are given matrix $a$ of size $n × m$, its elements are integers. We will assume that the rows of the matrix are numbered from top to bottom from 1 to $n$, the columns are numbered from left to right from 1 to $m$. We will denote the element on the intersecting of the $i$-th row and the $j$-th column as $a_{ij}$. We'll call submatrix $i_{1}, j_{1}, i_{2}, j_{2}$ $(1 ≤ i_{1} ≤ i_{2} ≤ n; 1 ≤ j_{1} ≤ j_{2} ≤ m)$ such elements $a_{ij}$ of the given matrix that $i_{1} ≤ i ≤ i_{2}$ AND $j_{1} ≤ j ≤ j_{2}$. We'll call the area of the submatrix number $(i_{2} - i_{1} + 1)·(j_{2} - j_{1} + 1)$. We'll call a submatrix inhomogeneous, if all its elements are distinct. Find the largest (in area) inhomogenous submatrix of the given matrix.
In this task you have to find largest by area submatrix, consisting from different numbers. Let's see solutions from slow to fast. 1) Solution by $O(n^{6})$: Iterate through two opposite vertices submatrix-answer and check that all numbers are different. 2) Solution by $O(n^{4})$: Let's fix Up and Down borders submatrix-answer ($O(n^{2})$). Use two pointers method to iterate Left and Right borders: while in submatrix there are no equal numbers, increment Right, while there are equal numbers - increment Left. Every check - $(O(n))$, increments - $(O(n))$. 3) Solution by $O(n^{3}logn)$: Let's construct function maxR(Left) (let's consider that Up <= Down are fixed): maximal value Right, so that in submatrix (Up, Down, Left, Right) there is no equals numbers. You can see that maxR(i) <= maxR(i + 1) is true for every i. How values of this function changes by shift Down to Down-1? Every value maxR(Left) can only be the same (if segment(Down, Down, Left, maxR(Left)) only added new numbers), or it can decrease. When maxR(Left) is decreasing? Only when one of the numbers from added segment have already been in the current submatrix. Shift Down to down let's see all numbers in row Down. For each number (let it be in column j) find indices i and k so i <= j, there is number, equal to a[Down][j] between rows Up and Down-1, i - maximal; k >= j, there is number, equal to a[Down][j] between rows Up and Down-1, k - minimal. When you find these indices (it is easy to find them using set, when you store all columns where number x was between Up and Down for all numbers x), you can try to update maxR[i] with j - 1, maxR[j] with k - 1. It will be enough, if you also update for all i = m..1 maxR[i] = min(maxR[i], maxR[i + 1]). Now maxR(Left) is correct, and you can check answer for these Up and Down by $O(n)$. 4) Now, solution by $O(n^{3})$. It requires understanding previous solution. Previous solution, despite good asymptotics, requires to store a lot (about 160 000) sets, where you will store about 160 000 elements. Even at n = 200 it works very slow. Let's get rid of log. Set is using only for finding nearest left and right elements, which are in rows from Up to Down, and equal to current. Note that when you do Up = Up - 1, nearest element comes near (by column) to a[i][j], so we can find all numbers, for which the nearest element will be in new row Up, and update them nearest number, and do that in $O(n^{2})$. This solution uses $O(n^{2})$ memory and $O(n^{3})$ time.
[ "dp", "hashing" ]
2,700
null
407
E
k-d-sequence
We'll call a sequence of integers a good $k$-$d$ sequence if we can add to it at most $k$ numbers in such a way that after the sorting the sequence will be an arithmetic progression with difference $d$. You got hold of some sequence $a$, consisting of $n$ integers. Your task is to find its longest contiguous subsegment, such that it is a good $k$-$d$ sequence.
In this problem you have to find longest subsegment, satisfying the condition. Reduce problem to $d = 1$. If $d = 0$, then answer is longest subsegment from equal numbers, this case we solve separately. If $d \neq 0$, then notice that if on some subsegment there are two numbers $a_{i}, a_{j}$ so that $a_{i}$%$d \neq a_{j}$%$d$, then this segment can't be good. Divide the sequence to consequent subsegments numbers, equal by modulo d, and divide each number by d, and solve task separately with every segment, consider that $d = 1$. Notice that segment [L, R] is good if and only if when max(L, R) - min(L, R) - (R - L) <= k, and there are no equal numbers. It is easy to exlain: if there are no equal numbers, then max(L, R) - min(L, R) - (R - L) is exactly number of numbers is needed to add for segment to consist of all numbers from min(L, R) to max(L, R). For all L lets find such maxR[L], that on segment [L..maxR[l]] there are no equal numbers, and maxR[L] is maximal. It can be done by $O(nlogn)$ by many ways, for example you can use map. Let's learn how we can maintain array a[R] = max(L, R) - min(L, R) - (R - L). If we have such array, then we have to find rightmost R such that a[R] <= k to get an answer. We will need two stacks and segment tree with operations "Add number on segment", "Find min element on segment", "Find rightmost number doesn't exceed k". Let's iterate L from right to left (n downto 1). How does function max(L, R) look like with fixed L? It's values represent a set of segments so that maximum on the segment is leftmost element of segment, and these maximums are increasing. (example: for array 6 4 8 0 7 9 function max(1, R) will be 6 6 8 8 8 9). How function changes with shift L to left? Some segments are absorbed by new element, if new element is bigger than maximum on segment. Maximums on segments are increasing, so we can keep them all in stack, and when we need to add new element we have to only pop some segments from stacks while maximum on top of stack is less then new element, and push new segment after that. If every operation with stack will be accompanied with right operation with segment tree, we can store array a[R] = max(L, R). For get array a[R] = max(L, R) - min(L, R) we need only to maintain second similar stack. For get array a[R] = max(L, R) - min(L, R) we need add -1 on all suffix when we are shitfing L. Now query "Find fightmost number less of equal k". First, segment tree divides segment of request to log(n) segments with length powers of two. Let's choose rightmost segment with minimum <= k, and do iterative deeping there to find element that we need. So, for every L we get query on segment L..maxR(L) on rightmost number less or equal k. It is one of candidates to an answer. We are doing O(n) operation with stack, and every requires query to segment tree, so asymptotics is $O(nlogn)$.
[ "data structures" ]
3,100
null
408
A
Line to Cashier
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are $n$ cashiers at the exit from the supermarket. At the moment the queue for the $i$-th cashier already has $k_{i}$ people. The $j$-th person standing in the queue to the $i$-th cashier has $m_{i, j}$ items in the basket. Vasya knows that: - the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
In this problem you were to find waiting the time for every queue by summing up the purchases of all the people, and return the minimum.
[ "implementation" ]
900
null
408
B
Garland
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought $n$ colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly $m$ pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​$m$ pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get.
In this problem it is necessary to find the garland with the maximal length, which can be composed of elements that we have. First, if you need some color, but you don't have it, then the answer is -1 Otherwise, answer is always exists. Let's sum the answers for all the colors separately. Suppose we have $a$ pieces of a garland of some color, and we need $b$ pieces. Then we have to add $min(a, b)$ to the answer: if $a > = b$ we will use $b$ 1 meter pieces, in the other case if $a < b$ we will use all $a$ pieces.
[ "implementation" ]
1,200
null
411
A
Password Check
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check. Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions: - the password length is at least 5 characters; - the password contains at least one large English letter; - the password contains at least one small English letter; - the password contains at least one digit. You are given a password. Please implement the automatic check of its complexity for company Q.
In the first problem you should correctly implement what was written in statement. It could be done like this:
[ "*special", "implementation" ]
800
null
411
B
Multi-core Processor
The research center Q has developed a new multi-core processor. The processor consists of $n$ cores and has $k$ cells of cache memory. Consider the work of this processor. At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked. The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within $m$ cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the $m$ cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.
In this problem you should read the statement carefully, consider some principal cases and implement them in your program. The author's solution is: We will store array $blockedCell[]$ (value in cell $i$ equals $1$ if this cell is blocked, $0$ otherwise), blockedCore[]$ (value in cell $i$ equals $0$, if this core is not blocked and the number cycle when this core is blocked otherwise). Consider all cycles from the first to the last. Consider the cycle number $k$. Consider all processors and calc what cells will blocked on the cycle $k$. Set values one to corresponding cells of array $blockedCell[]$ Then for each core $i$ if conditions $blockedCore[i] = 0$ and $blockedCell[x[i][k]] = 1$ meet then core $i$ is blocked on cycle $k$. Set $blockedCore[i] = k$.
[ "implementation" ]
1,600
null
411
C
Kicker
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack). Two teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from $1$ to $4$. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the $i$-th player is $a_{i}$, the attack skill is $b_{i}$. Before the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents. We will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence. The teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.
To solve this problem you should use logic (mathematic logic) :] Logic says: If for some arrangement of the first team there is no arrangement to have even a draw then the first team is guaranteed to win. If for any arrangement of the first team there is some arrangement for the second team when the second team wins then the second team is guaranteed to win. Otherwise nobody is guaranteed to win. The answer is Draw. This logic should be implemented in your program. I could be done considering each arrangement of every team.
[ "*special", "implementation" ]
1,700
null
412
A
Poster
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building. The slogan of the company consists of $n$ characters, so the decorators hung a large banner, $n$ meters wide and $1$ meter high, divided into $n$ equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on. Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the $k$-th square of the poster. To draw the $i$-th character of the slogan on the poster, you need to climb the ladder, standing in front of the $i$-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the $i$-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left. Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
One of the optimal solutions is the following. If $k - 1 \le n - k$ then firstly let's move ladder to the left by $k - 1$ positions. After that we will do the following pair of operations $n - 1$ times: paint $i$-th symbol of the slogan and move the ladder to the right. In the end we will paint the last symbol of the slogan. If $k - 1 > n - k$ then we will move the ladder to the right by $n - k$ positions. After that we will also paint symbol and move the ladder to the left. Our last action will be to paint the first symbol of the slogan. Total number of sought operations is $min(k - 1, n - k) + 2 \cdot n - 1$.
[ "greedy", "implementation" ]
900
null