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
1213
F
Unstable String Sort
Authors have come up with the string $s$ consisting of $n$ lowercase Latin letters. You are given two permutations of its indices (not necessary equal) $p$ and $q$ (both of length $n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once. For all $i$ from $1$ to $n-1$ the following properties hold: $s[p_i] \le s[p_{i + 1}]$ and $s[q_i] \le s[q_{i + 1}]$. It means that if you will write down all characters of $s$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order. Your task is to restore \textbf{any} such string $s$ of length $n$ consisting of \textbf{at least $k$ distinct lowercase Latin letters} which suits the given permutations. If there are multiple answers, you can print any of them.
Because if we write down all characters of $s$ in order of both permutations and this string will be sorted, it is obvious that these two strings are equal. Let's try the maximum possible number of distinct characters and then replace extra characters with 'z'. How to find the maximum number of distinct characters? Let's iterate over all values of $p$ (and $q$) in order from left to right. If we staying at the position $i$ now, let's add to the set $vals_1$ the value $p_i$ and to the set $vals_2$ the value $q_i$. And when these sets become equal the first time, let's say that the block of positions $i$ such that values $p_i$ are in the set right now, have the same letter, and then clear both sets. We can see that this segment of positions is the minimum by inclusion set that can contain equal letters. We don't need to compare sets naively and clear them naively, you can see implementation details in author's solution. If the number of such segments is less than $k$ then the answer is "NO", otherwise the answer is "YES" and we can fill the string $s$ with letters in order of these segments (if the segment is $[l; r]$ then all characters of $s$ with indices $p_l, p_{l + 1}, \dots, p_r$ has the same letter, the first segment has the letter 'a', the second one has the letter 'b', and so on, all segments after $25$-th has the letter 'z'). Time complexity: $O(n \log n)$.
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy", "implementation", "strings" ]
2,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> p1(n), p2(n); for (int i = 0; i < n; ++i) { cin >> p1[i]; --p1[i]; } for (int i = 0; i < n; ++i) { cin >> p2[i]; --p2[i]; } set<int> vals1, vals2; vector<int> rb; for (int i = 0; i < n; ++i) { if (vals2.count(p1[i])) { vals2.erase(p1[i]); } else { vals1.insert(p1[i]); } if (vals1.count(p2[i])) { vals1.erase(p2[i]); } else { vals2.insert(p2[i]); } if (vals1.empty() && vals2.empty()) { rb.push_back(i); } } if (int(rb.size()) < k) { cout << "NO" << endl; } else { string s(n, ' '); int l = 0; for (int it = 0; it < int(rb.size()); ++it) { int r = rb[it]; char c = 'a' + min(it, 25); for (int i = l; i <= r; ++i) { s[p1[i]] = c; } l = r + 1; } cout << "YES" << endl << s << endl; } return 0; }
1213
G
Path Queries
You are given a weighted tree consisting of $n$ vertices. Recall that a tree is a connected graph without cycles. Vertices $u_i$ and $v_i$ are connected by an edge with weight $w_i$. You are given $m$ queries. The $i$-th query is given as an integer $q_i$. In this query you need to calculate the number of pairs of vertices $(u, v)$ ($u < v$) such that the maximum weight of an edge on a simple path between $u$ and $v$ doesn't exceed $q_i$.
Let's carry the value $res$ that means the answer for the current set of edges. Initially it is $0$. Let's sort all edges by their weight and all queries by their weight also (both in non-decreasing order). Let's merge components of the tree using DSU (disjoint set union). We need to carry sizes of components also (it is easy if we use DSU). Then let's iterate over all queries in order of non-decreasing their weights. If the current query has weight $cw$ then let's merge all components connected by edges with weight $w_i \le cw$. When we merge two components with sizes $s_1$ and $s_2$, the answer changes like that: $res := res - \binom{s_1}{2} - \binom{s_2}{2} + \binom{s_1 + s_2}{2}$. The value $\binom{x}{2}$ equals to $\frac{x(x-1)}{2}$. It is so because we subtract all old paths corresponding to these components and add all new paths in the obtained component. So the answer for the current query will be $res$ after all required merges. Time complexity: $O(n \log n + m \log m)$.
[ "divide and conquer", "dsu", "graphs", "sortings", "trees" ]
1,800
#include <bits/stdc++.h> using namespace std; vector<int> p, rk; int getp(int v) { if (v == p[v]) return v; return p[v] = getp(p[v]); } long long res; long long get(int cnt) { return cnt * 1ll * (cnt - 1) / 2; } void merge(int u, int v) { u = getp(u); v = getp(v); if (rk[u] < rk[v]) swap(u, v); res -= get(rk[u]); res -= get(rk[v]); rk[u] += rk[v]; res += get(rk[u]); p[v] = u; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; res = 0; p = rk = vector<int>(n, 1); iota(p.begin(), p.end(), 0); vector<pair<int, pair<int, int>>> e(n - 1); for (int i = 0; i < n - 1; ++i) { cin >> e[i].second.first >> e[i].second.second >> e[i].first; --e[i].second.first; --e[i].second.second; } vector<pair<int, int>> q(m); vector<long long> ans(m); for (int i = 0; i < m; ++i) { cin >> q[i].first; q[i].second = i; } sort(e.begin(), e.end()); sort(q.begin(), q.end()); int pos = 0; for (int i = 0; i < m; ++i) { while (pos < n - 1 && e[pos].first <= q[i].first) { int u = e[pos].second.first; int v = e[pos].second.second; merge(u, v); ++pos; } ans[q[i].second] = res; } for (int i = 0; i < m; ++i) { cout << ans[i] << " "; } cout << endl; return 0; }
1214
A
Optimal Currency Exchange
Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $n$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $d$ rubles, and one euro costs $e$ rubles. Recall that there exist the following dollar bills: $1$, $2$, $5$, $10$, $20$, $50$, $100$, and the following euro bills — $5$, $10$, $20$, $50$, $100$, $200$ (note that, in this problem we do \textbf{not} consider the $500$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange. Help him — write a program that given integers $n$, $e$ and $d$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.
If we have bought dollar bills with value of two or more dollar bill, we can change it one-dollar bills. Same goes for euro, we can replace all euro bills with several $5$-euro bills. Now we can simply try buying some number of five-euro bills and buying all the rest with one-dollar bills. Complexity is $\mathcal{O}(n)$.
[ "brute force", "math" ]
1,400
null
1214
B
Badges
There are $b$ boys and $g$ girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and $n$ participants have accepted the invitation. The organizers do not know how many boys and girls are among them. Organizers are preparing red badges for girls and blue ones for boys. Vasya prepared $n+1$ decks of badges. The $i$-th (where $i$ is from $0$ to $n$, inclusive) deck contains $i$ blue badges and $n-i$ red ones. The total number of badges in any deck is exactly $n$. Determine the \textbf{minimum} number of decks among these $n+1$ that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.
Vasya must take one deck for each possible combination $(participants_{girls}, participants_{boys})$ (where $0 \le participants_{girls} \le g$, $0 \le participants_{boys} \le b$ and $participants_{girls} + participants_{boys} = n$). Let's determine how many girls can come for the game: at least $n - min(b, n)$, at most $min(g, n)$. All intermediate values are also possible, to the answer is just $min(g, n) - (n - min(b, n)) + 1$.
[ "brute force", "math" ]
1,100
null
1214
C
Bad Sequence
Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $s$ is called correct if: - $s$ is empty; - $s$ is equal to "($t$)", where $t$ is correct bracket sequence; - $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.
Let's call a balance of bracket sequence a number of opening brackets minus the number of closing brackets. Correct bracket sequence is such a sequence that balance of any of its prefixes is at least $0$ and the balance of the entire sequence is equal to $0$. To solve the problem let's consider the shortest prefix with balance equal to $-1$. In this prefix last symbol is obviously equal to ")", so let's move this closing bracket to the end of the sequence. If the sequence is correct now, then the answer is "Yes", otherwise it is "No", because it means that in original sequence there exists some longer prefix with balance equal to $-2$. Let's show why we can't move some bracket so that the sequence becomes correct. Consider the shortest prefix with balance equal to $-2$. If we move some opening bracket to the beginning of the sequence, balance of considered prefix becomes $-1$ and the sequence is not correct yet. Moving opening bracket from considered prefix to the beginning doesn't change anything. Even more, if we move the closing bracket from the end of the considered prefix to the end of the sequence, it still doesn't become correct, because balance of the prefix is $-1$. This results in a following solution: if balance of all prefixes is not less than $-1$, answer is "Yes", otherwise it's "No".
[ "data structures", "greedy" ]
1,200
null
1214
D
Treasure Island
All of us love treasures, right? That's why young Vasya is heading for a Treasure Island. Treasure Island may be represented as a rectangular table $n \times m$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $1$ to $n$ from top to bottom and columns with consecutive integers from $1$ to $m$ from left to right. Denote the cell in $r$-th row and $c$-th column as $(r, c)$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $(n, m)$. Vasya got off the ship in cell $(1, 1)$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $(x, y)$ he can move only to cells $(x+1, y)$ and $(x, y+1)$. Of course Vasya can't move through cells with impassable forests. Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $(1, 1)$ where Vasya got off his ship and $(n, m)$ where the treasure is hidden. Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.
The answer is no more than two as we can block $(2, 1)$ and $(1, 2)$. If there is no way from $(1, 1)$ to $(n, m)$, the answer is zero. The only thing to do is to distinguish $k = 1$ and $k = 2$. If answer is one, there must exist such cell $(x, y)$ that each path from $(1, 1)$ to $(n, m)$ goes through that cell. Also we can notice that in each path the cell $(x, y)$ goes on the $(x + y - 1)^th$ place. Let's run $dfs$ to obtain the set of cells which are accessible from $(1, 1)$ and $dfs$ backwards to obtain the set on cells such that $(n, m)$ is accessible from them. Let's intersect these sets and group cells by the distance from $(1, 1)$. If some group has a single cell, that would be the cell to block and the answer is one. If each group has more than one cell, the answer is two.
[ "dfs and similar", "dp", "flows", "hashing" ]
1,900
null
1214
E
Petya and Construction Set
It's Petya's birthday party and his friends have presented him a brand new "Electrician-$n$" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him. Construction set "Electrician-$n$" consists of $2n - 1$ wires and $2n$ light bulbs. Each bulb has its own unique index that is an integer from $1$ to $2n$, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain. Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed $2i$ and $2i - 1$ turn on if the chain connecting them consists of exactly $d_i$ wires. Moreover, the following \textbf{important} condition holds: the value of $d_i$ is never greater than $n$. Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.
Assume without loss of generality that the array $d$ sorted in non-increasing order. Let's make a linear ("bamboo") graph from the vertices $1, 3, 5, \ldots, 2n - 1$ in this order. We will add nodes $2i$ one by one, we will also maintain the longest route during that. On the $i$-th step we are looking for the vertex at the distance $d_i - 1$ from $2i - 1$. That node is $(i + d_i - 1)$-th on the route. So we can connect to it vertex $2i$. If $2i$ was connected to the last vertex of the route we should add $2i$ to the end of it. $(i + d_i - 1)$-th node on the longest route always exists because of two limitations: $d_1 \leq n$ for all $i \geq 2$: $d_{i - 1} \geq d_i$.
[ "constructive algorithms", "graphs", "math", "sortings", "trees" ]
2,000
null
1214
F
Employment
Two large companies "Cecsi" and "Poca Pola" are fighting against each other for a long time. In order to overcome their competitor, "Poca Pola" started a super secret project, for which it has total $n$ vacancies in all of their offices. After many tests and interviews $n$ candidates were selected and the only thing left was their employment. Because all candidates have the same skills, it doesn't matter where each of them will work. That is why the company decided to distribute candidates between workplaces so that the total distance between home and workplace over all candidates is minimal. It is well known that Earth is round, so it can be described as a circle, and all $m$ cities on Earth can be described as points on this circle. All cities are enumerated from $1$ to $m$ so that for each $i$ ($1 \le i \le m - 1$) cities with indexes $i$ and $i + 1$ are neighbors and cities with indexes $1$ and $m$ are neighbors as well. People can move only along the circle. The distance between any two cities equals to minimal number of transitions between neighboring cities you have to perform to get from one city to another. In particular, the distance between the city and itself equals $0$. The "Poca Pola" vacancies are located at offices in cities $a_1, a_2, \ldots, a_n$. The candidates live in cities $b_1, b_2, \ldots, b_n$. It is possible that some vacancies are located in the same cities and some candidates live in the same cities. The "Poca Pola" managers are too busy with super secret project, so you were asked to help "Poca Pola" to distribute candidates between workplaces, so that the sum of the distance between home and workplace over all candidates is minimum possible.
First, let's notice that the optimal answer can be achieved without changing the relative order of candidates. That means that if we order candidates by circle clockwise, the second candidate will work at the next clockwise workplace from the first candidate's workplace, the third candidate will work at the next clockwise workplace from the second candidate's workplace and so on. Let's prove it. If in optimal answer the order has changed, then there should be 2 candidates, so that the first of them lives earlier clockwise then the second and works at workplace, which is further. If we swap their workplaces, the distance between home and workplace for each of them will either stay the same or decrease. So, doing this swaps, we can achieve the situation, when the relative order of candidates stay the same. Now we can come up with simple $O(n^2)$ solution. Let's first sort all candidates and workplaces by their city number. Let's select some workplace for the first candidate. Because in the optimal answer the order of candidates will not change, for each candidate we know his workplace. Now in $O(n)$ time we can calculate the total distance. And because there are $n$ possible workplaces for the first candidate, the solution works in $O(n^2)$ time. To solve problem faster, let's notice, that if some candidate lives in city with number $x$ and his workplace has number $y$, the the total distance from home to work for him will be: $-x + y + m$ if $y < x - m / 2$ $x - y$ if $x - m / 2 \le y < x$ $-x + y$ if $x \le y < x + m / 2$ $x - y + m$ if $x + m / 2 \le y$
[ "greedy", "sortings" ]
2,700
null
1214
G
Feeling Good
Recently biologists came to a fascinating conclusion about how to find a chameleon mood. Consider chameleon body to be a rectangular table $n \times m$, each cell of which may be green or blue and may change between these two colors. We will denote as $(x, y)$ ($1 \leq x \leq n$, $1 \leq y \leq m$) the cell in row $x$ and column $y$. Let us define a chameleon good mood certificate to be four cells which are corners of some subrectangle of the table, such that colors in opposite cells among these four are similar, and at the same time not all of the four cell colors are similar. Formally, it is a group of four cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$ for some $1 \leq x_1 < x_2 \leq n$, $1 \leq y_1 < y_2 \leq m$, that colors of $(x_1, y_1)$ and $(x_2, y_2)$ coincide and colors of $(x_1, y_2)$ and $(x_2, y_1)$ coincide, but not all of the four cells share the same color. It was found that whenever such four cells are present, chameleon is in good mood, and vice versa: if there are no such four cells, chameleon is in bad mood. You are asked to help scientists write a program determining the mood of chameleon. Let us consider that initially all cells of chameleon are green. After that chameleon coloring may change several times. On one change, colors of contiguous segment of some table row are replaced with the opposite. Formally, each color change is defined by three integers $a$, $l$, $r$ ($1 \leq a \leq n$, $1 \leq l \leq r \leq m$). On such change colors of all cells $(a, b)$ such that $l \leq b \leq r$ are replaced with the opposite. Write a program that reports mood of the chameleon after each change. Additionally, if the chameleon mood is good, program should find out any four numbers $x_1$, $y_1$, $x_2$, $y_2$ such that four cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$ are the good mood certificate.
Let's define the set $A_i$ for each $1 \leq i \leq n$ as a set of columns $j$, such that the color of the cell $(i, j)$ is blue. If there exists two rows $1 \leq x_1 < x_2 \leq n$, such that $A_{x_1} \not\subset A_{x_2}$ and $A_{x_2} \not\subset A_{x_1}$ the good mood certificate exists. It's easy to see, because if $A_{x_1} \not\subset A_{x_2}$ there exists some $y_1$, such that $y_1 \in A_{x_1}$ and $y_1 \not\in A_{x_2}$ and if $A_{x_2} \not\subset A_{x_1}$ there exists some $y_2$, such that $y_2 \in A_{x_2}$ and $y_2 \not\in A_{x_1}$. Four cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$ will be the good mood certificate. Otherwise, if for any two rows $1 \leq x_1 < x_2 \leq n$ $A_{x_1} \subset A_{x_2}$ or $A_{x_2} \subset A_{x_1}$, there is no good mood certificate. Let's use bitset $a_i$ for each row, such that $a_{{i}{j}} = 1$, if the color of the cell $(i, j)$ is blue. For two rows $1 \leq x_1 < x_2 \leq n$ it's easy to check that $A_{x_1} \subset A_{x_2}$ or $A_{x_2} \subset A_{x_1}$ and find any good mood certificate if it is false using simple operations with two bitsets $a_{x_1}$ and $a_{x_2}$ in time $O(\frac{m}{w})$. Let's sort rows by the size of $A_i$. If for every two adjacent rows in this order one of them was a subset of other it is true for every pair of rows. So, we can check only pairs of adjacent rows in the sorted order. Let's keep a set of rows, sorting them by the size of $A_i$. And let's keep set of any good mood certificate for every two adjacent rows in the first set, if it exists. Now, if some row $x$ changes, we can change bitset $a_x$ in time $O(\frac{m}{w})$ and make $O(1)$ changes with our two sets. Time complexity: $O((\log{n} + \frac{m}{w})q)$, there $w=32$ or $w=64$.
[ "bitmasks", "data structures" ]
3,200
null
1214
H
Tiles Placement
The new pedestrian zone in Moscow city center consists of $n$ squares connected with each other by $n - 1$ footpaths. We define a simple path as a sequence of squares such that no square appears in this sequence twice and any two adjacent squares in this sequence are directly connected with a footpath. The size of a simple path is the number of squares in it. The footpaths are designed in a such a way that there is exactly one simple path between any pair of different squares. During preparations for Moscow City Day the city council decided to renew ground tiles on all $n$ squares. There are $k$ tile types of different colors, numbered from $1$ to $k$. For each square exactly one tile type must be selected and then used to cover this square surface. To make walking through the city center more fascinating, it was decided to select tiles types for each square in such a way that any possible simple path of size exactly $k$ contains squares with all $k$ possible tile colors. You need to find out whether it is possible to place the tiles this way or not.
Suppose there exists a vertex with tree with a tree paths going from it, with longest paths of lengths $a$, $b$ and $c$ (in edges). Then if $a + b \ge k - 1$, $b + c \ge k - 1$, $a + c \ge k - 1$, then clearly the answer is Impossible. We can check whether such vertex exists in $\mathcal{O}(n)$ using subtree dp and "uptree dp". Good news: this is the only case when the answer is "No". Bad news: providing the coloring is slightly more sophisticated. In fact, we can prove that the following coloring works: Construct a tree's diameter. Color vertices on diameter with periodic colors: $1$, $2$, ..., $k$, $1$, $2$, ... By the way, if diameter has less than $k$ vertices, any coloring will be correct. Cut the diameter in half, the parts' lengths will differ by $1$ atmost. Color both halves of the tree with dfs: colors in the left part will decrease $i \to i - 1 \to \ldots$, while colors in the right part will increase $i \to i + 1 \to \ldots$. The result will look roughly as follows: The total complexity is $\mathcal{O}(n)$. Let's give a sketch of the proof why this coloring works. Well, suppose there is some bad path of $k$ vertices. Let's analyze path's position with respect to the diameter. Case 1. The bad path is not related to the diameter. It's easy to see that blue part of diameter is greater or equal than any half of the red path; so the vertex $v$ is a bad vertex to the our criterion. Case 2. The bad path goes through a diameter, but lies in one half of it. The vertex $v$ makes a bad vertex for the criterion, just for the same reasons. Case 3. The bad path goes through a diameter, and lies in both halves. If you recall how our coloring looks like, you will see that all paths of this form are well-colored.
[ "constructive algorithms", "dfs and similar", "trees" ]
2,800
null
1215
A
Yellow Cards
The final match of the Berland Football Cup has been held recently. The referee has shown $n$ yellow cards throughout the match. At the beginning of the match there were $a_1$ players in the first team and $a_2$ players in the second team. The rules of sending players off the game are a bit different in Berland football. If a player from the first team receives $k_1$ yellow cards throughout the match, he can no longer participate in the match — he's sent off. And if a player from the second team receives $k_2$ yellow cards, he's sent off. After a player leaves the match, he can no longer receive any yellow cards. Each of $n$ yellow cards was shown to exactly one player. Even if all players from one team (or even from both teams) leave the match, the game still continues. The referee has lost his records on who has received each yellow card. Help him to determine the minimum and the maximum number of players that could have been thrown out of the game.
At first, if $k_1 > k_2$, then we swap $k_1$ with $k_2$ and $a_1$ with $a_2$, so the number of yellow cards required to send a player of the first team off is not greater than the same value for the second team. If all players from the first team receive $k_1 - 1$ cards each and all players from the second team receive $k_2 - 1$ cards each, we will minimize the number of players who left the game. Let $cnt = a_1 \cdot (k_1 - 1) + a_2 \cdot (k_2 - 1)$. If $cnt \le 0$, then the minimum number of players who left the game is equal to $0$. In the other case, if any player receivse one more yellow card, he leaves the game. So the minimum number of players who left the game is $(n - cnt)$. When we maximize the number of players who left the game, at first we should give cards to players in the first team, and then give cards to players in the second team. So, if $n \le a_1 \cdot k_1$, the answer is $\lfloor \frac{n}{k_1} \rfloor$. In the other case, the answer is $a_1 + \lfloor \frac{n - a_1 \cdot k_1}{k_2} \rfloor$.
[ "greedy", "implementation", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; int a1, a2, k1, k2, n; inline void read() { cin >> a1 >> a2 >> k1 >> k2 >> n; } inline void solve() { if (k1 > k2) { swap(k1, k2); swap(a1, a2); } int minCnt = max(0, n &mdash; a1 * (k1 &mdash; 1) &mdash; a2 * (k2 &mdash; 1)); int maxCnt = 0; if (n <= a1 * k1) { maxCnt = n / k1; } else { maxCnt = a1 + (n &mdash; a1 * k1) / k2; } cout << minCnt << ' ' << maxCnt << endl; } int main () { #ifdef fcspartakm freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif srand(time(NULL)); cerr << setprecision(10) << fixed; read(); solve(); //cerr << "TIME: " << clock() << endl; }
1215
B
The Number of Products
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ non-zero integers (i.e. $a_i \ne 0$). You have to calculate two following values: - the number of pairs of indices $(l, r)$ $(l \le r)$ such that $a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$ is negative; - the number of pairs of indices $(l, r)$ $(l \le r)$ such that $a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$ is positive;
At first, let's calculate the value of $ans_p$ - the number of subsegments with positive product. We should iterate through the array and store $bal$ - the number of negative elements. Also we should store $cnt_1$ and $cnt_2$ - the number of elements such that there is an even number of negative elements before them ($cnt_1$) or an odd number of negative elements before them ($cnt_2$). If for the current element $bal$ is even, we should increase $cnt_1$ by one, else we should increase $cnt_2$ by one. Then if the current element is negative, we should increase $bal$ by one. Then we should add the number of subsegments ending in the current element and having positive product to $ans_p$. If $bal$ is even, then any subsegment ending in the current element and containing even number of negative elements should begin in a position where $bal$ was even too, so we should add $cnt_1$ to $ans_p$. If $bal$ is odd, we should add $cnt_2$ to $ans_p$ (we use similar reasoning). The number of segments having negative product can be calculated, for example, by subtracting $ans_p$ from the total number of subsegments, which is $\frac{n \cdot (n + 1)}{2}$.
[ "combinatorics", "dp", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 13; int n; int a[N]; inline void read() { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } } inline void solve() { int pos = -1; li ans0 = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { pos = i; } if (pos != -1) { ans0 += pos + 1; } } int cnt1 = 0, cnt2 = 0; int bal = 0; li ansP = 0; for (int i = 0; i < n; i++) { if (a[i] == 0) { cnt1 = 0, cnt2 = 0, bal = 0; continue; } if (bal % 2 == 0) { cnt1++; } else { cnt2++; } if (a[i] < 0) { bal++; } if (bal % 2 == 0) { ansP += cnt1; } else { ansP += cnt2; } } cout << n * 1ll * (n + 1) / 2 - ans0 - ansP << ' ' << ansP << endl; } int main () { #ifdef fcspartakm freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif srand(time(NULL)); cerr << setprecision(10) << fixed; read(); solve(); //cerr << "TIME: " << clock() << endl; }
1215
C
Swap Letters
Monocarp has got two strings $s$ and $t$ having equal length. Both strings consist of lowercase Latin letters "a" and "b". Monocarp wants to make these two strings $s$ and $t$ equal to each other. He can do the following operation any number of times: choose an index $pos_1$ in the string $s$, choose an index $pos_2$ in the string $t$, and swap $s_{pos_1}$ with $t_{pos_2}$. You have to determine the minimum number of operations Monocarp has to perform to make $s$ and $t$ equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.
Let's calculate two vectors $pos_{01}$ and $pos_{10}$. $pos_{01}$ will contain all positions $x$ such that $s[x] = 0$ and $t[x] = 1$. Analogically, $pos_{10}$ will contain all positions $x$ such that $s[x] = 1$ and $t[x] = 0$. If the sizes of these vectors are not equal modulo $2$, the answer does not exist, because the total number of letters "a" and "b" should be even. In the other case, we should perform operations in a greedy way. In one operation we can make $s[a]$ equal to $t[a]$ and $s[b]$ equal to $t[b]$, if both $a$ and $b$ belong to $pos_{01}$, or if both these positions belong $pos_{10}$. If the sizes of $pos_{01}$ and $pos_{10}$ are even, we need only $(\frac{|pos_{01}|}{2} + \frac{|pos_{10}|}{2})$ operation. In the other case, there are two positions $x$ and $y$ such that $s[x] = 0$, $s[y] = 1$, $t[x] = 1$, $t[y] = 0$. We need two operations to make $s[x] = t[x]$ and $s[y] = t[y]$: at first we perform the operation $(x, x)$, and then the operation $(x, y)$. After that, strings $s$ and $t$ will be equal to each other.
[ "constructive algorithms", "greedy" ]
1,500
#include<bits/stdc++.h> using namespace std; int n; string s, t; inline void read() { cin >> n >> s >> t; } inline void solve() { vector<int> pos01, pos10; for (int i = 0; i < n; i++) { if (s[i] != t[i]) { if (s[i] == 'a') { pos01.pb(i); } else { pos10.pb(i); } } } if (sz(pos01) % 2 != sz(pos10) % 2) { cout << -1 << endl; return; } vector<pair<int, int> > ans; for (int i = 0; i + 1 < sz(pos01); i += 2) { ans.pb(mp(pos01[i], pos01[i + 1])); } for (int i = 0; i + 1 < sz(pos10); i += 2) { ans.pb(mp(pos10[i], pos10[i + 1])); } if (sz(pos01) % 2) { int x = pos01.back(); int y = pos10.back(); ans.pb(mp(x, x)); ans.pb(mp(x, y)); } cout << sz(ans) << endl; for (int i = 0; i < sz(ans); i++) { cout << ans[i].ft + 1 << ' ' << ans[i].sc + 1 << endl; } } int main () { #ifdef fcspartakm freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif srand(time(NULL)); cerr << setprecision(10) << fixed; read(); solve(); //cerr << "TIME: " << clock() << endl; }
1215
D
Ticket Game
Monocarp and Bicarp live in Berland, where every bus ticket consists of $n$ digits ($n$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. \textbf{The number of digits that have been erased is even}. Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $\frac{n}{2}$ digits of this ticket is equal to the sum of the last $\frac{n}{2}$ digits. Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $0$ to $9$. The game ends when there are no erased digits in the ticket. If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.
Let's denote the balance as the difference between the sum of digits in the left half and the sum of digits in the right half. Also let $L$ be the minimum possible balance (it can be calculated if we replace all question marks in the left half with $0$'s and all the question marks in the right half with $9$'s), and let $R$ be the maximum possible balance. The second player wins if and only if $\frac{L + R}{2} = 0$. Let's prove it by induction on the number of question marks left in the ticket. If all characters are digits, the second player wins only if the ticket is happy, and that is when $\frac{L + R}{2} = 0$. Okay, now suppose the number of question marks is even, and now it's first player's turn. Each turn decreases the value of $R - L$ by $9$, and may set $L$ to any number from current $L$ to $L + 9$. If $L + R > 0$, then the first player can make $L$ as large as possible, and set it to $L + 9$. The best thing the second player can do on his turn is to set $R$ to $R - 9$ (and leave $L$ as it is), and the value of $L + R$ will be the same as it was two turns earlier. The case $L + R < 0$ can be analyzed similarly. And in the case $L + R = 0$ the second player has a symmetric strategy.
[ "games", "greedy", "math" ]
1,700
#include <iostream> #include <set> #include <string> #include <vector> #include <algorithm> #include <cmath> using namespace std; int n; int main() { cin >> n; long double sum1 = 0, sum2 = 0; string s; cin >> s; for (int i = 0; i < n; i++) { if (s[i] != '?') { if (i < n / 2) { sum1 += (long double)(s[i] - '0'); } else { sum2 += (long double)(s[i] - '0'); } } else { if (i < n / 2) { sum1 += (long double)4.5; } else { sum2 += (long double)4.5; } } } if (fabsl(sum1 - sum2) < 1e-9) { cout << "Bicarp" << endl; } else { cout << "Monocarp" << endl; } }
1215
E
Marbles
Monocarp has arranged $n$ colored marbles in a row. The color of the $i$-th marble is $a_i$. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color). In other words, Monocarp wants to rearrange marbles so that, for every color $j$, if the leftmost marble of color $j$ is $l$-th in the row, and the rightmost marble of this color has position $r$ in the row, then every marble from $l$ to $r$ has color $j$. To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them. You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.
The main fact is that the number of colors is less than $20$, which allows us to use exponential solutions. For each pair of colors $(i, j)$, we can calculate $cnt[i][j]$ - the number of swaps required to place all marbles of color $i$ before all marbles of color $j$ (if we consider only marbles of these two colors). We can store a sorted vector for each color, and calculate this information for a fixed pair with two pointers. Then let's use subset DP to fix the order of colors. Let $d[mask]$ be the minimum number of operations to correctly order all marbles from the $mask$ of colors. Let's iterate on the next color we consider - it should be a position in binary representation of $mask$ with $0$ in it. We will place all marbles of this color after all marbles we already placed. If we fix a new color $i$, let's calculate the $sum$ (the additional number of swaps we have to make) by iterating on the bit $j$ equal to $1$ in the $mask$, and increasing $sum$ by $cnt[j][i]$ for every such bit. The new state of DP can be calculated as $nmask = mask | (1 << i)$. So the transition can be implemented as $d[nmask] = min(d[nmask], d[mask] + sum)$. The answer is the minimum number of swaps required to place all the colors, and that is $d[2^{20} - 1]$.
[ "bitmasks", "dp" ]
2,200
#include <iostream> #include <set> #include <string> #include <vector> #include <algorithm> using namespace std; const int N = 1000 * 1000 + 13; const int M = 20 + 1; const long long INF = 1000 * 1000 * 1000 * 1ll * 1000 * 1000 * 1000; int n; long long d[(1 << M)]; long long cnt[M][M]; vector<int> col[M]; int main() { cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; x--; col[x].push_back(i); } for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { if (i == j) { continue; } if ((int)col[i].size() == 0 || (int)col[j].size() == 0) { continue; } int pos2 = 0; for (int pos1 = 0; pos1 < (int)col[i].size(); pos1++) { while (true) { if (pos2 == (int)col[j].size() - 1 || col[j][pos2 + 1] > col[i][pos1]) { break; } pos2++; } if (col[i][pos1] > col[j][pos2]) { cnt[i][j] += pos2 + 1; } } } } for (int mask = 0; mask < (1 << 20); mask++) { d[mask] = INF; } d[0] = 0; for (int mask = 0; mask < (1 << 20); mask++) { vector<int> was; for (int i = 0; i < 20; i++) { if (mask & (1 << i)) { was.push_back(i); } } for (int i = 0; i < 20; i++) { if (mask & (1 << i)) { continue; } long long sum = 0; for (int j = 0; j < (int)was.size(); j++) { sum += cnt[was[j]][i]; } int nmask = mask | (1 << i); d[nmask] = min(d[nmask], d[mask] + sum); } } cout << d[(1 << 20) - 1] << endl; }
1215
F
Radio Stations
In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. $n$ complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the $i$-th complaint, one of the radio fans has mentioned that the signals of two radio stations $x_i$ and $y_i$ are not covering some parts of the city, and demanded that the signal of \textbf{at least one} of these stations can be received in the whole city. Of cousre, the mayor of Bertown is currently working to satisfy these complaints. A new radio tower has been installed in Bertown, it can transmit a signal with any integer power from $1$ to $M$ (let's denote the signal power as $f$). The mayor has decided that he will choose a set of radio stations and establish a contract with every chosen station. To establish a contract with the $i$-th station, the following conditions should be met: - the signal power $f$ should be not less than $l_i$, otherwise the signal of the $i$-th station won't cover the whole city; - the signal power $f$ should be not greater than $r_i$, otherwise the signal will be received by the residents of other towns which haven't established a contract with the $i$-th station. All this information was already enough for the mayor to realise that choosing the stations is hard. But after consulting with specialists, he learned that some stations the signals of some stations may interfere with each other: there are $m$ pairs of stations ($u_i$, $v_i$) that use the same signal frequencies, and for each such pair it is impossible to establish contracts with both stations. \textbf{If stations $x$ and $y$ use the same frequencies, and $y$ and $z$ use the same frequencies, it does not imply that $x$ and $z$ use the same frequencies}. The mayor finds it really hard to analyze this situation, so he hired you to help him. You have to choose signal power $f$ and a set of stations to establish contracts with such that: - all complaints are satisfied (formally, for every $i \in [1, n]$ the city establishes a contract either with station $x_i$, or with station $y_i$); - no two chosen stations interfere with each other (formally, for every $i \in [1, m]$ the city \textbf{does not} establish a contract either with station $u_i$, or with station $v_i$); - for each chosen station, the conditions on signal power are met (formally, for each chosen station $i$ the condition $l_i \le f \le r_i$ is met).
Let's try to solve the problem without any constraints on $f$ (we just need to choose a set of stations that satisfies all the complaints and contains no forbidden pair). We can see that this is an instance of 2-SAT: we can convert it into a logical expression that is a conjunction of some clauses, and each clause contains exactly two variables (maybe negated), we have to assign some values to all variables so that this expression is true. The $i$-th variable $true$ if we include the $i$-th station in our answer, or $false$ otherwise. We can solve this problem in linear time by building an implication graph and finding strongly connected components in it. If the constraints were lower, we could iterate on $f$ and initially set all variables corresponding to stations we can't use with fixed $f$ to $false$. But this solution is quadratic, so we have to include $f$ into our original 2-SAT problem. Let's introduce $M$ additional variables, the $i$-th of them corresponding to the fact "$f \ge i$". Add $M - 1$ clause of the form "$f \ge i$ OR NOT $f \ge i + 1$" into our conjunction. The prefix of additional variables which are equal to $true$ can be transformed into the value or $f$ we should use, and vice versa. If we introduce these variables, the constraints on $f$ that are implied by some station can be modeled with two additiona clauses: "$f \ge l_i$ OR station $i$ is not used" and "NOT $f \ge r_i + 1$ OR station $i$ is not used". So we get a linear solution (though with a noticeable constant factor).
[ "2-sat" ]
2,700
#include<bits/stdc++.h> using namespace std; const int N = 1600043; vector<int> g[N]; vector<int> gt[N]; int used[N]; vector<int> order; int comp[N]; vector<int> result; int v; void add_edge(int v1, int v2) { g[v1].push_back(v2); gt[v2].push_back(v1); } void add_disjunction(int v1, int v2) { add_edge(v1 ^ 1, v2); add_edge(v2 ^ 1, v1); } void dfs1(int v) { if(used[v]) return; used[v] = 1; for(auto u : g[v]) dfs1(u); order.push_back(v); } void dfs2(int v, int cc) { if(comp[v]) return; comp[v] = cc; for(auto u : gt[v]) dfs2(u, cc); } bool solve2SAT() { for(int i = 0; i < v * 2; i++) dfs1(i); reverse(order.begin(), order.end()); int cc = 0; for(auto x : order) { if(comp[x] == 0) { cc++; dfs2(x, cc); } } for(int i = 0; i < v; i++) { if(comp[i * 2] == comp[i * 2 + 1]) return false; else if(comp[i * 2] > comp[i * 2 + 1]) result.push_back(i); } return true; } int main() { int n, p, M, m; scanf("%d %d %d %d", &n, &p, &M, &m); v = p + M - 1; for(int i = 0; i < n; i++) { int x, y; scanf("%d %d", &x, &y); --x; --y; add_disjunction(x * 2, y * 2); } for(int i = 0; i < p; i++) { int l, r; scanf("%d %d", &l, &r); if(l != 1) add_disjunction((l - 2 + p) * 2, i * 2 + 1); if(r != M) add_disjunction((r - 1 + p) * 2 + 1, i * 2 + 1); } for(int i = 0; i < m; i++) { int x, y; scanf("%d %d", &x, &y); --x; --y; add_disjunction(x * 2 + 1, y * 2 + 1); } for(int i = 2; i <= M - 1; i++) { int f1 = i - 2 + p; int f2 = f1 + 1; add_disjunction(f1 * 2, f2 * 2 + 1); } if(!solve2SAT()) { puts("-1"); return 0; } int k = 1; vector<int> stations; for(auto x : result) if(x < p) stations.push_back(x); else k = max(k, x - p + 2); printf("%d %d\n", int(stations.size()), k); for(auto x : stations) printf("%d ", x + 1); return 0; }
1216
A
Prefixes
Nikolay got a string $s$ of \textbf{even} length $n$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $1$ to $n$. He wants to modify his string so that every its prefix of \textbf{even} length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'. The prefix of string $s$ of length $l$ ($1 \le l \le n$) is a string $s[1..l]$. For example, for the string $s=$"abba" there are two prefixes of the even length. The first is $s[1\dots2]=$"ab" and the second $s[1\dots4]=$"abba". Both of them have the same number of 'a' and 'b'. Your task is to calculate the minimum number of operations Nikolay has to perform with the string $s$ to modify it so that every its prefix of \textbf{even} length has an equal amount of letters 'a' and 'b'.
The problem can be solved like this: firstly let's iterate over all $i$ from $1$ to $\frac{n}{2}$. If characters $s_{2i-1}$ and $s_{2i}$ are the same then we obviously need to replace one of them with the other character. We can see that such replacements are enough to make the string suitable.
[ "strings" ]
800
n, s = int(input()), list(input()) ans = 0 for i in range(0, n, 2): if (s[i] == s[i + 1]): s[i] = chr(1 - ord(s[i]) + 2 * ord('a')) ans += 1 print(ans) print(''.join(s))
1216
B
Shooting
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $n$ cans in a row on a table. Cans are numbered from left to right from $1$ to $n$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose \textbf{the order} in which he will knock the cans down. Vasya knows that the durability of the $i$-th can is $a_i$. It means that if Vasya has already knocked $x$ cans down and is now about to start shooting the $i$-th one, he will need $(a_i \cdot x + 1)$ shots to knock it down. You can assume that if Vasya starts shooting the $i$-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the $n$ given cans down exactly once is minimum possible.
We can see that because the multiplier $x$ in the formula $(a_i \cdot x + 1)$ is the position of the number and we want to minimize the sum of such formulas, the following greedy solution comes up to mind: because we want to count greater values as earlier as possible, let's sort the array $a$ in non-increasing order (saving initial indices of elements), calculate the answer and print the permutation of indices in order from left to right.
[ "greedy", "implementation", "sortings" ]
900
n, a = int(input()), list(map(int, input().split())) res = [] ans = 0 for i in range(n): pos = -1 for j in range(n): if (pos == -1 or a[j] > a[pos]): pos = j res.append(pos + 1) ans += i * a[pos] + 1 a[pos] = 0 print(ans) print(' '.join([str(x) for x in res]))
1216
C
White Sheet
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates $(0, 0)$, and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates $(x_1, y_1)$, and the top right — $(x_2, y_2)$. After that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are $(x_3, y_3)$, and the top right — $(x_4, y_4)$. Coordinates of the bottom left corner of the second black sheet are $(x_5, y_5)$, and the top right — $(x_6, y_6)$. \begin{center} {\small Example of three rectangles.} \end{center} Determine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying \textbf{not strictly inside} the white sheet and \textbf{strictly outside} of both black sheets.
There are at least two solution to the problem. I'll describe both of them. The first solution: firstly let's notice that the point we search can have non-integer coordinates, but if the answer exists then there will be the answer such that its point has at most half-integer coordinates. So let's multiply all coordinates by two and solve the problem with integer coordinates. The second thing is that for some $x$ there is only two points we need to check - top point with this $x$ and bottom point with this $x$. The same for some $y$. So we can iterate over all possible values of $x$ and check if the point $(x, y_1)$ lies outside of both black rectangles. The same with point $(x, y_2)$. Then do the same for points $(y, x_1)$ and $(y, x_2)$. $x$ should be in range $[x_1; x_2]$ and $y$ should be in range $[y_1; y_2]$. Time complexity is linear on size of the white rectangle. The second solution is most tricky but has the better time complexity. Let $wb_1$ be the intersection of white rectangle and the first black rectangle, $wb_2$ the same but with the second black rectangle and $inter$ be the intersection of $wb_1$ and $wb_2$. Then it is obvious that the answer exists if $wb_1$ and $wb_2$ doesn't cover the whole white rectangle ($sq(w) > sq(wb_1) + sq(wb_2) - sq(inter)$). Time complexity: $O(1)$.
[ "geometry", "math" ]
1,700
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> #include <algorithm> #include <cstdio> #include <random> #include <ctime> #include <string> #include <iomanip> #include <set> #include <map> #include <queue> #include <stack> using namespace std; typedef long long li; typedef unsigned long long uli; typedef pair<int, int> pii; typedef long double ld; #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() #define pb push_back #define forn(i, n) for(int i = 0; i < int(n); ++i) #define fore(i, l, r) for(int i = int(l); i < int(r); ++i) #define forb(i, n) for(int i = int(n) - 1; i >= 0; --i) #define vi vector<int> #define x first #define y second const int INF = 2e9; const li INF64 = 1e18; const int M = 2 * 1000 * 1000; const int N = 300 * 1000 + 100; const int MOD = 1e9 + 7; const double EPS = 1e-9; const double PI = 3.14159265359; pair<pii, pii> intersect(pii a, pii b, pii c, pii d) { int lf, rg, up, dn; lf = max(min(a.x, b.x), min(c.x, d.x)); rg = min(max(a.x, b.x), max(c.x, d.x)); up = min(max(a.y, b.y), max(c.y, d.y)); dn = max(min(a.y, b.y), min(c.y, d.y)); if (rg <= lf || up <= dn) return { {0, 0}, {0, 0} }; return { { lf, dn }, { rg, up } }; } li square(pii a, pii b) { return 1ll * abs(a.x - b.x) * abs(a.y - b.y); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(0); cin.tie(0); vector<pii> p(6); forn(i, 6) cin >> p[i].x >> p[i].y; pair<pii, pii> wb1 = intersect(p[0], p[1], p[2], p[3]); pair<pii, pii> wb2 = intersect(p[0], p[1], p[4], p[5]); pair<pii, pii> inter = intersect(wb1.x, wb1.y, wb2.x, wb2.y); li swhite = square(p[0], p[1]); li swb1 = square(wb1.x, wb1.y); li swb2 = square(wb2.x, wb2.y); li sinter = square(inter.x, inter.y); if (swhite > swb1 + swb2 - sinter) cout << "YES\n"; else cout << "NO\n"; }
1216
D
Swords
There were $n$ types of swords in the theater basement which had been used during the plays. Moreover there were \textbf{exactly} $x$ swords of each type. $y$ people have broken into the theater basement and each of them has taken exactly $z$ swords of some \textbf{single type}. Note that different people might have taken different types of swords. Note that the values $x, y$ and $z$ are unknown for you. The next morning the director of the theater discovers the loss. He counts all swords — exactly $a_i$ swords of the $i$-th type are left untouched. The director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken. For example, if $n=3$, $a = [3, 12, 6]$ then one of the possible situations is $x=12$, $y=5$ and $z=3$. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values $x, y$ and $z$ beforehand but know values of $n$ and $a$. Thus he seeks for your help. Determine the \textbf{minimum} number of people $y$, which could have broken into the theater basement, and the number of swords $z$ each of them has taken.
Firstly, let's notice that for the fixed value of $z$ our problem is reduced to the following: we are given $n$ numbers $a_1, a_2, \dots, a_n$. We need to choose such values $k_1, k_2, \dots, k_n$ that $a_1 + k_1 \cdot z = a_2 + k_2 \cdot z = \dots = a_n + k_n \cdot z$. And among all such values $k_1, k_2, \dots, k_n$ we need to choose values in a way to minimize $\sum\limits_{i=1}^{n}k_i$. And the sum of $k_i$ is $y$! Of course, for the fixed value $z$ the minimum sum of $k_i$ can be only one. Let's start with $z=1$. It is obvious that if the maximum value in the array $a$ is $mx$ the value $k_i$ equals $mx - a_i$ (for $z=1$). Assume that each $k_i$ from $1$ to $n$ has some divisor $d$. Then if we multiply $z$ by $d$ and divide each $k_i$ by $d$ the answer will only become better. How to calculate this value of $z$ fast? We can see that this value equals to $gcd(k_1, k_2, \dots, k_n)$! And it can be proven that this value of $z$ is always optimal and we can easily determine $y$ for such $z$. Time complexity: $O(n + \log max(a_i))$.
[ "math" ]
1,300
#include <iostream> #include <sstream> #include <cstdio> #include <vector> #include <cmath> #include <queue> #include <string> #include <cstring> #include <cassert> #include <iomanip> #include <algorithm> #include <set> #include <map> #include <ctime> #include <cmath> #define forn(i, n) for(int i=0;i<n;++i) #define fore(i, l, r) for(int i = int(l); i <= int(r); ++i) #define sz(v) int(v.size()) #define all(v) v.begin(), v.end() #define pb push_back #define mp make_pair #define x first #define y1 ________y1 #define y second #define ft first #define sc second #define pt pair<int, int> 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; using namespace std; const int INF = 1000 * 1000 * 1000; const ld EPS = 1e-9; const ld PI = acos(-1.0); const int N = 200 * 1000 + 13; int n; int a[N]; inline void read() { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } } inline int gcd(int a, int b) { while (a != 0 && b != 0) { if (a > b) { a %= b; } else { b %= a; } } return max(a, b); } inline void solve() { int ma = *max_element(a, a + n); li sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; } int g = ma - a[0]; for (int i = 1; i < n; i++) { g = gcd(g, ma - a[i]); } li ans = (ma * 1ll * n - sum) / g; cout << ans << ' ' << g << endl; } int main () { #ifdef fcspartakm freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif srand(time(NULL)); cerr << setprecision(10) << fixed; read(); solve(); //cerr << "TIME: " << clock() << endl; }
1216
E1
Numerical Sequence (easy version)
\textbf{The only difference between the easy and the hard versions is the maximum value of $k$}. You are given an infinite sequence of form "112123123412345$\dots$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the second one — from $1$ to $2$, the third one — from $1$ to $3$, $\dots$, the $i$-th block consists of all numbers from $1$ to $i$. So the first $56$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $1$-st element of the sequence is $1$, the $3$-rd element of the sequence is $2$, the $20$-th element of the sequence is $5$, the $38$-th element is $2$, the $56$-th element of the sequence is $0$. Your task is to answer $q$ independent queries. In the $i$-th query you are given one integer $k_i$. Calculate the digit at the position $k_i$ of the sequence.
Let's take a look on the upper bound of the number $n$, where $n$ is the maximum possible number of block which can be asked. If we assume that each number has length $1$ then the sum of lengths will be equal to $1 + 2 + \dots + n$. And as we know this value equals $\frac{n(n+1)}{2}$. So the maximum value of $n$ is not greater than $O(\sqrt{k})$. Now we can just iterate over all $i$ from $1$ to $n$ (where $n$ is no more than $5 \cdot 10^4$) and carry the length of the last block. If this length is greater than or equal to $k$ ($0$-indexed) then let's decrease $k$ by this length, increase the length of the last block and continue. Otherwise our answer lies in the current block. So then let's iterate over all $j$ from $1$ to $i$ and if the decimal length of $j$ is greater than or equal to $k$ then decrease $k$ by this length otherwise our answer lies in the current number $j$ and we just need to print $j_k$ ($0$-indexed). Time complexity: $O(\sqrt{k})$ per query.
[ "binary search", "brute force", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; while (q--) { long long k; cin >> k; --k; long long lst = 0; long long nxtpw = 1; int numlen = 0; for (long long i = 1; ; ++i) { if (i == nxtpw) { ++numlen; nxtpw *= 10; } lst += numlen; if (k >= lst) { k -= lst; } else { long long nxtpw = 1; int numlen = 0; for (long long j = 1; j <= i; ++j) { if (j == nxtpw) { ++numlen; nxtpw *= 10; } if (k >= numlen) { k -= numlen; } else { cout << to_string(j)[k] << endl; break; } } break; } } } return 0; }
1216
E2
Numerical Sequence (hard version)
\textbf{The only difference between the easy and the hard versions is the maximum value of $k$}. You are given an infinite sequence of form "112123123412345$\dots$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the second one — from $1$ to $2$, the third one — from $1$ to $3$, $\dots$, the $i$-th block consists of all numbers from $1$ to $i$. So the first $56$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $1$-st element of the sequence is $1$, the $3$-rd element of the sequence is $2$, the $20$-th element of the sequence is $5$, the $38$-th element is $2$, the $56$-th element of the sequence is $0$. Your task is to answer $q$ independent queries. In the $i$-th query you are given one integer $k_i$. Calculate the digit at the position $k_i$ of the sequence.
This problem idea is not very hard. Now $n$ can be up to $10^9$ so we need to find the number of block $i$ faster. Let's do binary search on it! Now using some shitty pretty formulas we can determine if the total sum of lengths of blocks from $1$ to $i$ is greater than or equal to $k$ or not. And more about these formulas: let's iterate over all possible length of numbers from $1$ to $len(i)$ and carry the sum of lengths $add$ of numbers with length less than the current length $l$. We know that the number of numbers (he-he) of length $l$ is exactly $cnt = 10^{l+1}-10^l$ ($cnt = i - 10^l + 1$ for $l=len(i)$). Let's add $add \cdot cnt + \frac{cnt(cnt+1)}{2} \cdot cnt$ to the total sum of lengths and increase $add$ by $cnt \cdot len$. What does $add \cdot cnt$ means? This formula means that we have exactly $cnt$ blocks ending with numbers of length $l$ and we need to add sum of lengths of all numbers with length less than $l$ exactly $cnt$ times. And what does $\frac{cnt(cnt+1)}{2} \cdot cnt$ means? It is the sum sums of lengths of all numbers of length $l$ (i.e. previously we added sum of lengths of numbers with length less than $l$ and now we add sum of sums of lengths of numbers with length $l$). When we found the number of block $i$, let's decrease $k$ by the total length of all blocks from $1$ to $i-1$ and continue solving the problem. This part was pretty hard to understand. And the easiest part: when we determined the number of block $i$ we can easily determine the number $j$ from $1$ to $i$ such that our answer lies in the number $j$. Let's iterate over all lengths from $1$ to $len(i)$ (here we go again) and for the current length $l$ let $cnt = 10^{l+1}-10^l$ ($cnt = j - 10^l + 1$ for $l=len(j)$). And now all we need is to increase the sum of lengths by $cnt \cdot len$. After determining $j$ decrease $k$ by sum of lengths of numbers from $1$ to $j-1$ and print $j_k$. Time complexity: $O(\log^2{n})$.
[ "binary search", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; long long get(long long r) { return (r + 1) * r / 2; } long long sumto(long long r, int need) { long long pw = 1; long long sum = 0; long long add = 0; for (int len = 1; ; ++len) { if (pw * 10 - 1 < r) { long long cnt = pw * 10 - pw; if (need) { sum += add * cnt + get(cnt) * len; add += cnt * len; } else { sum += cnt * len; } } else { long long cnt = r - pw + 1; if (need) { sum += add * cnt + get(cnt) * len; } else { sum += cnt * len; } break; } pw *= 10; } return sum; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; while (q--) { long long k; cin >> k; --k; long long l = 1 , r = 1e9; long long res = -1; while (r - l >= 0) { long long mid = (l + r) >> 1; if (sumto(mid, 1) > k) { res = mid; r = mid - 1; } else { l = mid + 1; } } k -= sumto(res - 1, 1); l = 1, r = res; long long num = -1; while (r - l >= 0) { int mid = (l + r) >> 1; if (sumto(mid, 0) > k) { num = mid; r = mid - 1; } else { l = mid + 1; } } cout << to_string(num)[k - sumto(num - 1, 0)] << endl; } return 0; }
1216
F
Wi-Fi
You work as a system administrator in a dormitory, which has $n$ rooms one after another along a straight hallway. Rooms are numbered from $1$ to $n$. You have to connect all $n$ rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the $i$-th room is $i$ coins. Some rooms also have a spot for a router. The cost of placing a router in the $i$-th room is also $i$ coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room $i$, you connect all rooms with the numbers from $max(1,~i - k)$ to $min(n,~i + k)$ inclusive to the Internet, where $k$ is the range of router. The value of $k$ is the same for all routers. Calculate the minimum total cost of connecting all $n$ rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.
Firstly, I know that this problem has very pretty linear solution and its author can describe it if he wants. I'll describe my own solution without any data structures but std::set. Let $dp_i$ be the total cost to connect all rooms from $i$ to $n-1$ to the Internet ($0$-indexed). Initially $dp_{n} = 0$, all other values are $+\infty$. Let's iterate over all $i$ from $n-1$ to $0$ and make some transitions. After all the answer will be $dp_0$. The first transition is the easier: update $dp_i$ with $dp_{i + 1} + i + 1$ (just connect the current room directly). To do other transitions, let's carry two sets $mins$ and $vals$ and one array of vectors $del$ of length $n$. Set $mins$ carries all values $dp_{i + 1}, dp_{i + 2}, \dots, dp_{i + k + 1}$. Initially it carries $dp_n = 0$. Set $vals$ carries the minimum cost to cover some suffix of rooms that also covers the room $i$. Array of vectors $rem$ helps us to carry the set $vals$ efficiently. First of all, if $i + k + 2 \le n$ then let's remove $dp_{i + k + 2}$ from $mins$. Then let's remove all values of $del_i$ from $vals$. Then if $vals$ is not empty, let's update $dp_i$ with the minimum value of $vals$. Then if $s_i =$ '1' then let $val$ be the minimum value of $mins$ plus $i + 1$. Update $dp_i$ with $val$ and insert $val$ into $vals$. Also let's add $val$ into $del_{i - k - 1}$ if $i - k - 1 \ge 0$. And after we make all we need with the current $i$, add the value $dp_i$ to the set $mins$. Time complexity: $O(n \log n)$. It can be optimized to $O(n)$ solution with some advanced data structures as a queue with minimums.
[ "data structures", "dp", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; string s; cin >> s; vector<long long> dp(n + 1); multiset<long long> mins, vals; mins.insert(0); vector<vector<long long>> del(n); for (int i = n - 1; i >= 0; --i) { dp[i] = i + 1 + dp[i + 1]; if (i + k + 2 <= n) mins.erase(mins.find(dp[i + k + 2])); for (auto it : del[i]) vals.erase(vals.find(it)); if (!vals.empty()) dp[i] = min(dp[i], *vals.begin()); if (s[i] == '1') { long long val = (mins.empty() ? 0 : *mins.begin()) + i + 1; dp[i] = min(dp[i], val); vals.insert(val); if (i - k - 1 >= 0) del[i - k - 1].push_back(val); } mins.insert(dp[i]); } cout << dp[0] << endl; return 0; }
1217
A
Creating a Character
You play your favourite game yet another time. You chose the character you didn't play before. It has $str$ points of strength and $int$ points of intelligence. Also, at start, the character has $exp$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $1$ or raise intelligence by $1$). Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is \textbf{strictly greater} than the resulting intelligence). Calculate the number of different character builds you can create (for the purpose of replayability) if you must \textbf{invest all free points}. Two character builds are different if their strength and/or intellect are different.
Let $addS$ and $addI$ be number of free points that we invest in the strength and intelligence respectively. It's obvious that $addS + addI = exp$ since we must spend all free points. From the other side we must make $str + addS > int + addI$. Now we can expess $addI = exp - addS$ and put it in the inequality: $str + addS > int + (exp - addS)$ $2addS > exp + int - str$ $2addS \ge exp + int - str + 1$ $addS \ge \left \lceil \frac{exp + int - str + 1}{2} \right \rceil$ Since $addS$ must be non negative we can get $addS \ge \max(0, \left \lceil \frac{exp + int - str + 1}{2} \right \rceil)$ We can use or write the correct ceiling function that works with negative numerator or use one hack and magic and get $addS \ge \max(0, \frac{exp + int - str + 2}{2})$ Since all integer values $addS$ from $[minAddS, exp]$ are good for us, so the number of pairs is equal to $\max(0, exp - minAddS + 1)$. P.S.: Let me explain how to prove that $k \cdot x > y$ is equal to $x \ge \left \lfloor \frac{y + k}{k} \right \rfloor$. $k \cdot x > y \Leftrightarrow k \cdot x \ge y + 1 \Leftrightarrow x \ge \left \lceil \frac{y + 1}{k} \right \rceil \Leftrightarrow x \ge \left \lfloor \frac{y + 1 + k - 1}{k} \right \rfloor \Leftrightarrow x \ge \left \lfloor \frac{y + k}{k} \right \rfloor$ P.P.S.: Interesting fact: the formula above works for all positive $k$ and $y \in [-k, +\infty)$ thats why it works in our case even though $exp + int - str$ can be negative.
[ "binary search", "math" ]
1,300
fun main() { val t = readLine()!!.toInt() for (ct in 1..t) { val (str, int, exp) = readLine()!!.split(' ').map { it.toInt() } val minAddStr = maxOf(0, (exp + int - str + 2) / 2) println(maxOf(exp - minAddStr + 1, 0)) } }
1217
B
Zmei Gorynich
You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-th type, you decrease the number of Gorynich's heads by $min(d_i, curX)$, there $curX$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $h_i$ new heads. If $curX = 0$ then Gorynich is defeated. \textbf{You can deal each blow any number of times, in any order.} For example, if $curX = 10$, $d = 7$, $h = 10$ then the number of heads changes to $13$ (you cut $7$ heads off, but then Zmei grows $10$ new ones), but if $curX = 10$, $d = 11$, $h = 100$ then number of heads changes to $0$ and Zmei Gorynich is considered defeated. Calculate the minimum number of blows to defeat Zmei Gorynich! You have to answer $t$ independent queries.
Lets divide all dealing blows into two parts: the last blow and others blows. The last hit should be with maximum value of $d$. The others blows should be with the maximum value of $d - h$. So, lets denote $\max\limits_{1 \le i \le n} d_i$ as $maxD$ and $\max\limits_{1 \le i \le n} (d_i - h_i)$ as $maxDH$. Then if $x \le maxD$ the we can beat Zmei Gorynich with one blow. Otherwise, if $maxDH \le 0$, then we cannot defeat Zmei Gorynich. Otherwise (if $x > maxD$ and $maxDH > 0$) the answer is $\lceil \frac{x - maxD}{maxDH} \rceil$.
[ "greedy", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = 105; int t; int n, m; int d[N], h[N]; int main() { cin >> t; for(int tc = 0; tc < t; ++tc){ cin >> n >> m; int maxDH = -2e9; for(int i = 0; i < n; ++i){ cin >> d[i] >> h[i]; maxDH = max(maxDH, d[i] - h[i]); } int res = 1; int maxD = *max_element(d, d + n); m -= maxD; if(m > 0){ if(maxDH <= 0) res = -1; else res += (m + maxDH - 1) / maxDH; } cout << res << endl; } return 0; }
1217
C
The Number Of Good Substrings
You are given a binary string $s$ (recall that a string is binary if each character is either $0$ or $1$). Let $f(t)$ be the decimal representation of integer $t$ written in binary form (possibly with leading zeroes). For example $f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$ and $f(000100) = 4$. The substring $s_{l}, s_{l+1}, \dots , s_{r}$ is good if $r - l + 1 = f(s_l \dots s_r)$. For example string $s = 1011$ has $5$ good substrings: $s_1 \dots s_1 = 1$, $s_3 \dots s_3 = 1$, $s_4 \dots s_4 = 1$, $s_1 \dots s_2 = 10$ and $s_2 \dots s_4 = 011$. Your task is to calculate the number of good substrings of string $s$. You have to answer $t$ independent queries.
At first, lets precalc the array $nxt_1, nxt_2, \dots , nxt_n$. The value of $nxt_i$ if equal the maximum position $j$ in range $1 \dots i$ such that $s_j = 1$. After that lets iterate over the right boundary of substring and high $1$-bit position (denote it as $r$ and $l$ respectively). Note that if $r - l > 18$ then $f(l, r) > 2 \cdot 10^5$. So we iterate over such pair $(l, r)$ that $1 \le l \le r \le n$ and $r - l \le 18$. Lets look at value $f(l, r)$. If $f(l, r) > r - l + 1$, then we have to increase the length of substring without increasing the value of $f(l, r)$. So we need to check if there exists a position $nl$ such that $f(nl, r) = f(l, r)$ and $r - nl + 1 = f(nl, r)$. This position exists if the condition $f(l, r) \le r - nxt_{l - 1}$ is met ($nxt_0$ is equal to -1).
[ "binary search", "bitmasks", "brute force" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int t; string s; int nxt[N]; int main() { cin >> t; for(int tc = 0; tc < t; ++tc){ cin >> s; for(int i = 0; i < s.size(); ++i) if(s[i] == '1') nxt[i] = i; else nxt[i] = (i == 0? -1 : nxt[i - 1]); int res = 0; for(int r = 0; r < s.size(); ++r){ int sum = 0; for(int l = r; l >= 0 && r - l < 20; --l){ if(s[l] == '0') continue; sum += 1 << (r - l); if(sum <= r - (l == 0? -1 : nxt[l - 1])) ++res; } } cout << res << endl; } return 0; }
1217
D
Coloring Edges
You are given a directed graph with $n$ vertices and $m$ directed edges without self-loops or multiple edges. Let's denote the $k$-coloring of a digraph as following: you color each edge in one of $k$ colors. The $k$-coloring is \textbf{good} if and only if there no cycle formed by edges of same color. Find a good $k$-coloring of given digraph with minimum possible $k$.
Let's run dfs on the graph and color all "back edges" ($(u, v)$ is back edge if there is a path from $v$ to $u$ by edges from dfs tree) in black and all other edges in white. It can be proven that any cycle will have at least one white edge and at least black edge. Moreover each back edge connected with at least one cycle (path from $v$ to $u$ and $(u, v)$ back edge). So the coloring we got is exactly the answer. How to prove that any cycle have at least one edge of both colors? Let's look only at edges from dfs trees. We can always renumerate vertices in such way that index of parent $id(p)$ is bigger than the index of any its child $id(c)$. We can process and assign $id(p)$ with minimal free number after we processed all its children. Now we can note that for any white edge $(u, v)$ (not only tree edge) condition $id(u) > id(v)$ holds (because of properties of dfs: forward edges are obvious; cross edge $(u, v)$ becomes cross because dfs at first processed vertex $v$ and $u$ after that, so $id(v) < id(u)$). And for each back edge $(u, v)$ it's true that $id(u) < id(v)$. Since any cycle have both $id(u) > id(v)$ and $id(u) < id(v)$ situations, profit!
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,100
#include<bits/stdc++.h> using namespace std; const int N = int(1e6) + 55; int n, m; vector <pair<int, int> > g[N]; int col[N]; bool cyc; int res[N]; void dfs(int v){ col[v] = 1; for(auto p : g[v]){ int to = p.first, id = p.second; if(col[to] == 0){ dfs(to); res[id] = 1; } else if(col[to] == 2) res[id] = 1; else{ res[id] = 2; cyc = true; } } col[v] = 2; } int main(){ cin >> n >> m; for(int i = 0; i < m; ++i){ int u, v; cin >> u >> v; --u, --v; g[u].push_back(make_pair(v, i)); } for(int i = 0; i < n; ++i) if(col[i] == 0) dfs(i); cout << (cyc? 2 : 1) << endl; for(int i = 0; i < m; ++i) cout << res[i] << ' '; cout << endl; return 0; }
1217
E
Sum Queries?
Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced. For example, multiset $\{20, 300, 10001\}$ is balanced and multiset $\{20, 310, 10001\}$ is unbalanced: The red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is $10321$, every position has the digit required. The sum of the second multiset is $10331$ and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced. You are given an array $a_1, a_2, \dots, a_n$, consisting of $n$ integers. You are asked to perform some queries on it. The queries can be of two types: - $1~i~x$ — replace $a_i$ with the value $x$; - $2~l~r$ — find the \textbf{unbalanced} subset of the multiset of the numbers $a_l, a_{l + 1}, \dots, a_r$ with the minimum sum, or report that no unbalanced subset exists. Note that the empty multiset is balanced. For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
We are given the definition of the balanced multiset but let's instead fix the criteria to determine if the multiset is unbalanced. Take an empty multiset and start adding numbers to it until it becomes unbalanced. Empty set to the set of one number is trivial. Now for the second number. If there is some position such that both numbers have non-zero digits in it, then the multiset becomes unbalanced (let these be non-zero digits $d_1$ and $d_2$, then $d_1 + d_2$ can be neither $d_1$, nor $d_2$). After that let's prove that you can never make an unbalanced multiset balanced again by adding numbers to it. Let there be such multisets $a$ and $b$ such $a$ is unbalanced, $b$ is balanced and $a \subset b$. Take a look at the lowest position which has non-zero digits in several numbers from $b$. The sum of these digits should be equal to at least one of them modulo $10$ (to satisfy the condition of balance). That can only mean their sum is greater or equal to $10$, thus is make a carry to the next position. The sum of digits on the next position plus carry should also be equal to some digit of them, thus pushing some other carry value to the next one. And so on until the carry makes it to the position greater than any position in any of the numbers. But the carry is non-zero and there is no number with any non-zero digit in this position. That makes our assumption incorrect. After all, it implies that any unbalanced multiset of size greater than two has an unbalanced multiset of size two. The problem now got reduced to: find a pair of numbers $a_i$ and $a_j$ such that $l \le i < j \le r$, there is at least one position such that both $a_i$ and $a_j$ have non-zero digits on it and $a_i + a_j$ is minimal possible. That can be easily maintained in a segment tree. Let a node corresponding to the interval $[l; r)$ keep the best answer on an interval (the sum of such a pair) and an array $min\_by\_digit[i]$ - the smallest number on an interval $[l; r)$ which has a non-zero digit at position $i$ or $\infty$ if none exists. The update is easy. Iterate over the digits of a new number and update the values in the array $min\_by\_digit$ in the corresponding nodes. The merge is done the following way: push the best answers from children to the parent and then iterate over the positions and try to combine the smallest numbers at each one from the left child and the right child. Idea-wise this is the same as storing a segtree and calculating the answer by each position separately. However, these approaches differ by a huge constant factor performance-wise. The former one accesses the memory in a much more cache-friendly way. You might want to take that as a general advice on implementing multiple segtrees. Overall complexity: $O((n + m) \cdot \log n \cdot \log_{10} MAXN)$.
[ "data structures", "greedy", "implementation", "math" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; const int INF = 2e9; const int LOGN = 9; struct node{ int best; int mn[LOGN]; node(){ best = INF; forn(i, LOGN) mn[i] = INF; } int& operator [](int x){ return mn[x]; } }; int a[N]; node t[4 * N]; void upd(node &t, int val){ int x = val; forn(i, LOGN){ if (x % 10 != 0) t[i] = min(t[i], val); x /= 10; } } node merge(node &a, node &b){ node c; c.best = min(a.best, b.best); forn(i, LOGN){ c[i] = min(a[i], b[i]); if (a[i] < INF && b[i] < INF) c.best = min(c.best, a[i] + b[i]); } return c; } void build(int v, int l, int r){ if (l == r - 1){ t[v] = node(); upd(t[v], a[l]); return; } int m = (l + r) / 2; build(v * 2, l, m); build(v * 2 + 1, m, r); t[v] = merge(t[v * 2], t[v * 2 + 1]); } void upd(int v, int l, int r, int pos, int val){ if (l == r - 1){ t[v] = node(); upd(t[v], val); return; } int m = (l + r) / 2; if (pos < m) upd(v * 2, l, m, pos, val); else upd(v * 2 + 1, m, r, pos, val); t[v] = merge(t[v * 2], t[v * 2 + 1]); } node get(int v, int l, int r, int L, int R){ if (l == L && r == R) return t[v]; int m = (l + r) / 2; if (R <= m) return get(v * 2, l, m, L, R); if (L >= m) return get(v * 2 + 1, m, r, L, R); node ln = get(v * 2, l, m, L, m); node rn = get(v * 2 + 1, m, r, m, R); return merge(ln, rn); } int main() { int n, m; scanf("%d%d", &n, &m); forn(i, n) scanf("%d", &a[i]); build(1, 0, n); forn(i, m){ int t, x, y; scanf("%d%d%d", &t, &x, &y); --x; if (t == 1) upd(1, 0, n, x, y); else{ node res = get(1, 0, n, x, y); printf("%d\n", res.best == INF ? -1 : res.best); } } return 0; }
1217
F
Forced Online Queries Problem
You are given an undirected graph with $n$ vertices numbered from $1$ to $n$. Initially there are no edges. You are asked to perform some queries on the graph. Let $last$ be the answer to the latest query of the second type, it is set to $0$ before the first such query. Then the queries are the following: - $1~x~y$ ($1 \le x, y \le n$, $x \ne y$) — add an undirected edge between the vertices $(x + last - 1)~mod~n + 1$ and $(y + last - 1)~mod~n + 1$ if it doesn't exist yet, otherwise remove it; - $2~x~y$ ($1 \le x, y \le n$, $x \ne y$) — check if there exists a path between the vertices $(x + last - 1)~mod~n + 1$ and $(y + last - 1)~mod~n + 1$, which goes only through currently existing edges, and set $last$ to $1$ if so and $0$ otherwise. Good luck!
The problem directly tells you do solve some kind of Dynamic Connectivity Problem. You could use the online approach with Link-Cut Tree if you'd had its implementation beforehand. There is also a nice modification to the $log^2$ solution of the offline version of DCP (check out the comment). I'd tell the solution which is probably the easiest to come up with and to code. Let's recall the sqrt-optimization method of solving DCP. Process blocks of queries of size $P$ one at a time. Split the edges into two groups: The edges which were added on queries before the block and aren't touched by the queries in the block; the edges modified by the queries in the block. The first type of edges can be added to the graph before the block processing starts. You can use DSU for that. The second type contains no more than $P$ edges. Maintain the list of those of them which exist in the graph. On each ask query add them to graph, then delete them. This can be done explicitly by doing DFS only over these edges and the vertices which correspond to the connected components on the edges of the first type. Implicitly doing DSU merges for these edges and rolling them back is a viable option as well (costs extra log factor but has lower constant). It's easy to see that it isn't hard to modify this solution to our problem. Let's define the edges of the first type more generally: the edges which were added on queries before the block and could not be touched by the queries in the block. So neither $(v, u)$ from the add query, nor $(v~mod~n + 1, u~mod~n + 1)$ could be of the first type. Now there might be $2P$ edges of the second type in the list. However, that doesn't make the complexity any worse. Process block the same way, rebuild the DSU with the edges of the first type every $P$ queries. The overall complexity can be $O((n + m) \sqrt{m})$ if you use DFS or $O((n + m) \sqrt{m \log n})$ if you use DSU (notice how the rebuild is $P \cdot O(n + m)$ and the query is $m \cdot O(\frac{m}{P} \cdot \log n)$ and set the size of the block so that these parts are about the same).
[ "data structures", "divide and conquer", "dsu", "graphs", "trees" ]
2,600
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int BUF = 10 * 1000 * 1000 + 13; const int N = 300 * 1000 + 13; const int M = 300 * 1000 + 13; const int P = 400; struct query{ int t, x, y; int e0, e1; }; int n, m; query q[M]; int p[N], rk[N]; int cnt; int* where[BUF]; int val[BUF]; void rollback(){ while (cnt > 0){ *where[cnt - 1] = val[cnt - 1]; --cnt; } } int getp(int a){ return (a == p[a] ? a : getp(p[a])); } void unite(int a, int b){ a = getp(a), b = getp(b); if (a == b) return; if (rk[a] < rk[b]) swap(a, b); where[cnt] = &rk[a]; val[cnt++] = rk[a]; where[cnt] = &p[b]; val[cnt++] = p[b]; assert(cnt <= BUF); rk[a] += rk[b]; p[b] = a; } int getpFast(int a){ return (a == p[a] ? a : p[a] = getpFast(p[a])); } void uniteFast(int a, int b){ a = getpFast(a), b = getpFast(b); if (a == b) return; if (rk[a] < rk[b]) swap(a, b); rk[a] += rk[b]; p[b] = a; } struct edge{ int v, u; }; bool operator <(const edge &a, const edge &b){ if (a.v != b.v) return a.v < b.v; return a.u < b.u; } edge edges[2 * M]; map<edge, int> rev; bool used[2 * M]; bool state[2 * M]; int ans[M]; vector<int> cur; void rebuild(int l){ int r = min(m, l + P); forn(i, n) p[i] = i, rk[i] = 1; memset(used, 0, sizeof(used)); memset(state, 0, sizeof(state)); forn(i, l) if (q[i].t == 1){ int e = (ans[i] ? q[i].e1 : q[i].e0); used[e] = true; state[e] ^= 1; } for (int i = l; i < r; ++i) if (q[i].t == 1) used[q[i].e0] = used[q[i].e1] = false; cur.clear(); cnt = 0; forn(i, l) if (q[i].t == 1){ int e = (ans[i] ? q[i].e1 : q[i].e0); if (used[e] && state[e]){ state[e] = false; uniteFast(edges[e].v, edges[e].u); } else if (!used[e] && state[e]){ state[e] = false; cur.push_back(e); } } } int get_edge(edge e){ if (!rev.count(e)){ int k = rev.size(); edges[k] = e; rev[e] = k; } return rev[e]; } int main(){ scanf("%d%d", &n, &m); forn(i, m){ scanf("%d%d%d", &q[i].t, &q[i].x, &q[i].y); --q[i].x, --q[i].y; if (q[i].t == 1){ edge e({q[i].x, q[i].y}); if (e.v > e.u) swap(e.v, e.u); q[i].e0 = get_edge(e); e.v = (e.v + 1) % n, e.u = (e.u + 1) % n; if (e.v > e.u) swap(e.v, e.u); q[i].e1 = get_edge(e); } } string res = ""; ans[0] = 0; forn(i, m){ if (i % P == 0) rebuild(i); int x = (q[i].x + ans[i]) % n; int y = (q[i].y + ans[i]) % n; if (x > y) swap(x, y); if (q[i].t == 1){ rollback(); int e = get_edge({x, y}); auto it = find(cur.begin(), cur.end(), e); if (it == cur.end()) cur.push_back(e); else cur.erase(it); ans[i + 1] = ans[i]; } else{ for (auto e : cur) unite(edges[e].v, edges[e].u); bool rc = (getp(x) == getp(y)); ans[i + 1] = rc; res += ('0' + rc); } } puts(res.c_str()); return 0; }
1220
A
Cards
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.
It's easy to see that letter $\text{z}$ contains only in $\text{zero}$ and $\text{n}$ contains only in $\text{one}$, so we should print $1$ $count(\text{n})$ times and then $0$ $count(\text{z})$ times.
[ "implementation", "sortings", "strings" ]
800
null
1220
B
Multiplication Table
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $M$ with $n$ rows and $n$ columns such that $M_{ij}=a_i \cdot a_j$ where $a_1, \dots, a_n$ is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $a_1, \dots, a_n$. Help Sasha restore the array!
Let's note that $\frac{(xy) \cdot (xz)}{(yz)} = x^2$ if $x, y, z > 0$. In this problem $n \ge 3$, so we can get each value this way.
[ "math", "number theory" ]
1,300
null
1220
C
Substring Game in the Lesson
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $s$ and a number $k$ ($0 \le k < |s|$). At the beginning of the game, players are given a substring of $s$ with left border $l$ and right border $r$, both equal to $k$ (i.e. initially $l=r=k$). Then players start to make moves one by one, according to the following rules: - A player chooses $l^{\prime}$ and $r^{\prime}$ so that $l^{\prime} \le l$, $r^{\prime} \ge r$ and $s[l^{\prime}, r^{\prime}]$ is lexicographically less than $s[l, r]$. Then the player changes $l$ and $r$ in this way: $l := l^{\prime}$, $r := r^{\prime}$. - Ann moves first. - The player, that can't make a move loses. Recall that a substring $s[l, r]$ ($l \le r$) of a string $s$ is a continuous segment of letters from s that starts at position $l$ and ends at position $r$. For example, "ehn" is a substring ($s[3, 5]$) of "aaaehnsvz" and "ahz" is not. Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $s$ and $k$. Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $s$ and determines the winner for all possible $k$.
The main idea of this task is that Mike never moves. Lets fix $k$, there two cases: 1) $s[k] \ge s[i]$ for all $i < k$, in this case $s[k, k] \le s[l, r]$ for all $l \le k$ and $r \ge k$, so Ann can't make her first move (Mike wins). 2) There is $i < k$ such that $s[i] < s[k]$. In this case Ann can move with substring $s[i, r]$. If we choose the least possible $i < k$ such that $s[i]$ is minimal, we will deprive Misha of the opportunity to make a move (Ann wins) Final solution: for all $k$ we should check whether $s[k]$ is the least on substring $s[0, k]$. It can be done with one for in wich we should maintain a minimum on prefix. Complexity $O(|s|)$.
[ "games", "greedy", "strings" ]
1,300
null
1220
D
Alex and Julian
Boy Dima gave Julian a birthday present — set $B$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else! Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two $i$ and $j$ with an edge if $|i - j|$ belongs to $B$. Unfortunately, Julian doesn't like the graph, that was built using $B$. Alex decided to rectify the situation, so he wants to erase some numbers from $B$, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of \textbf{minimum} size from $B$ so that graph constructed on the new set is bipartite. Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Let all numbers in $B$ be odd. If two vertices $i$ and $j$ are connected, then they have different parity, hence our graph is already bipartite (first part is even vertices, second - odd vertices). Now let's see that if we choose an integer $k > 0$, multiply all elements of the set by $2^k$ and build a new graph on this set, our new graph will also be bipartite. Proof: consider $k$-th bit. An edge connects only vertices with different $k$-th bit, so partition is clear. So, we found out that if all elements in $B$ have equal power of $2$ in their factorization, then this set builds a bipartite graph. What about other cases? Let $a, b \in B$. They form a cycle with $len = \frac{lcm(a, b)}{a} + \frac{lcm(a, b)}{b} = \frac{a}{gcd(a, b)} + \frac{b}{gcd(a, b)}$. It's easy to see that $len$ is odd iff $a$ and $b$ contain different powers of $2$ in their factorization, so we just proved that there is no other cases. Finally, the solution is to find maximum power of $2$ that divides $B_i$ for all $1 \le i \le n$, find the largest subset $B'$ with equal power of $2$ and drop $B \setminus B'$. Complexity $O(n \log{maxB})$.
[ "bitmasks", "math", "number theory" ]
1,900
null
1220
E
Tourism
Alex decided to go on a touristic trip over the country. For simplicity let's assume that the country has $n$ cities and $m$ bidirectional roads connecting them. Alex lives in city $s$ and initially located in it. To compare different cities Alex assigned each city a score $w_i$ which is as high as interesting city seems to Alex. Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city $v$ from city $u$, he may choose as the next city in the trip any city connected with $v$ by the road, except for the city $u$. Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.
Let's note that if you visit a vertex $u$ located on a loop, you can always add the numbers on vertices in this loop to answer and you can also add the numbers on vertices between $u$ and $s$. It is true because you can just visit $u$, go through the vertices of the cycle, return to $u$ and then go back to $s$. But if from the given vertex we can't get to the cycle, then we can't return back. So the problem is to choose the best branch leading only to the leaves. And from this point there are several solutions for this problem. Let's discuss one of them: Let $e_u$ be the maximum extra value we could get, if we are in $u$ and we want to go only to leaves. First of all just put all the leaves except $s$ in stack or queue. Then we choose the next vertex $u$ from our queue and look at its parent $v$. Let's decrease $v$'s degree and update $e_v = \max(e_v, e_u + w_u)$. If $v$'s deegre became $1$, it means that $v$ is the leave now, so let's push it in our queue, if it isn't $s$. It looks like at each step, we just erase one leave from our graph and recompute $e$ value for its parent. At the end, we considered all vertexes which are not belong to the cycles and not belong to the pathes from $s$ to one of the cycles. So we need to sum up the biggest $e_u$ with the sum of all $w_v$, where $v$ wasn't considered during our leaves removing. There are also solutions that build edge-connectivity components and compute the value using DP on tree.
[ "dfs and similar", "dp", "dsu", "graphs", "greedy", "trees" ]
2,200
null
1220
F
Gardener Alex
Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on $n$ vertices. Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from $1$ to $n$ which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts. Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him? We remind that cyclic shift of permutation $a_1, a_2, \ldots, a_k, \ldots, a_n$ for $k$ elements to the left is the permutation $a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k$.
Notice that element $a$ is an ancestor of an element $b$ when it's minimum on a subsegment from $a$ to $b$. Count amount of ancestors for every element in initial permutation. Now, when you remove element $l$ from the left, all elements between it and the leftmost element smaller than $l$ now have one ancestor less. When you move it to the right, all elements between it and the rightmost element smaller than it have one ancestor more. And new amount of ancestors for element moved to the right is one more than amount of ancestors of the rightmost element smaller than it. You can store amounts of ancestors in a segment tree with lazy propagation if you concatenate given permutation with itself.
[ "binary search", "data structures" ]
2,700
null
1220
G
Geolocation
You are working for the Gryzzl company, headquartered in Pawnee, Indiana. The new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be $n$ antennas located somewhere in the park. When someone would like to know their current location, their Gryzzl hologram phone will communicate with antennas and obtain distances from a user's current location to all antennas. Knowing those distances and antennas locations it should be easy to recover a user's location... Right? Well, almost. The only issue is that there is no way to distinguish antennas, so you don't know, which distance corresponds to each antenna. Your task is to find a user's location given as little as all antennas location and an unordered multiset of distances.
Let's look on the sum of squared distances from unknown point $(x;y)$ to all known points $(x_i;y_i)$: $\sum\limits_{i=1}^n d_i^2 = \sum\limits_{i=1}^n\left((x-x_i)^2+(y-y_i)^2\right)= n(x^2+y^2)-2x\sum\limits_{i=1}^n x_i - 2y\sum\limits_{i=1}^n y_i + \sum\limits_{i=1}^n (x_i^2+y_i^2)$ If we switch to new coordinates with the origin in the center of mass of all points, terms $\sum\limits_{i=1}^n x_i$ and $\sum\limits_{i=1}^n y_i$ will be equal to zero, thus the whole sum will be equal to: $\sum\limits_{i=1}^n d_i^2 = n(x^2+y^2)+\sum\limits_{i=1}^n(x_i^2+y_i^2)$ From this we obtain that all possible points $(x;y)$ lie on the circumference with the center in the center of mass of all points with the squared radius equal to $\frac{1}{n}\sum\limits_{i=1}^n (d_i^2-x_i^2-y_i^2)$. Due to the randomness of unknown point we may assume that there is only as much as $\log n$ integer points on this circumference. If we try all possible distances from first point, we may reduce possible points to only those found on the intersection of two circumferences.
[ "geometry" ]
3,400
null
1221
A
2048 Game
You are playing a variation of game 2048. Initially you have a multiset $s$ of $n$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two \textbf{equal} integers from $s$, remove them from $s$ and insert the number equal to their sum into $s$. For example, if $s = \{1, 2, 1, 1, 4, 2, 2\}$ and you choose integers $2$ and $2$, then the multiset becomes $\{1, 1, 1, 4, 4, 2\}$. You win if the number $2048$ belongs to your multiset. For example, if $s = \{1024, 512, 512, 4\}$ you can win as follows: choose $512$ and $512$, your multiset turns into $\{1024, 1024, 4\}$. Then choose $1024$ and $1024$, your multiset turns into $\{2048, 4\}$ and you win. You have to determine if you can win this game. You have to answer $q$ independent queries.
It's obvious that we don't need elements that are larger than $2048$. If the sum of the remaining elements is greater than or equal to 2048, then the answer is YES, and NO otherwise. It's true because for getting a integer $x$ that wasn't in the multiset initially, we first need to get integer $\frac{x}{2}$.
[ "brute force", "greedy", "math" ]
1,000
for t in range(int(input())): n = input() l = filter(lambda x : x <= 2048, map(int, input().split()) ) print('YES' if sum(l) >= 2048 else 'NO')
1221
B
Knights
You are given a chess board with $n$ rows and $n$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board. A knight is a chess piece that can attack a piece in cell ($x_2$, $y_2$) from the cell ($x_1$, $y_1$) if one of the following conditions is met: - $|x_1 - x_2| = 2$ and $|y_1 - y_2| = 1$, or - $|x_1 - x_2| = 1$ and $|y_1 - y_2| = 2$. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them). A duel of knights is a pair of knights of \textbf{different} colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.
Let's denote a cell ($i$, $j$) as black if $i + j$ is even, otherwise the cell is white. It's easy to see that if a knight is occupying a black cell, then all cells attacked by it are white, and vice versa. Using this fact, we can construct a solution where every pair of knights that attack each other have different colors - put black knights into black cells, and white knights into white cells, so every pair of knights that can possibly form a duel actually form it.
[ "constructive algorithms", "greedy" ]
1,100
n = int(input()) for i in range(n): print(''.join(['W' if (i + j) % 2 == 0 else 'B' for j in range(n)]))
1221
C
Perfect Team
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. \textbf{She/he can have no specialization, but can't have both at the same time.} So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members. You are a coach at a very large university and you know that $c$ of your students are coders, $m$ are mathematicians and $x$ have no specialization. What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team. You are also asked to answer $q$ independent queries.
Notice that if $c \ne m$, then you can equalize them to the min and re-qualify the rest into students without specialization. That won't change the answer. Now analyze the possible team formations: 1 of each kind, 2 coders and 1 mathematician or 1 coder and 2 mathematicians. Each of these squads have 1 coder and 1 mathematician, so you can only choose the type of the third member. The students without specialization can only be used in the first kind of teams, so let's use them first. After that you might have been left with a nonzero count of coders and mathematicians. These are equal however, so $\lfloor \frac{c + m}{3} \rfloor$ can be added to the answer. This solves each query in $O(1)$. You can also run a binary search and solve each query in $O(\log MAX)$.
[ "binary search", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main(){ int q; cin >> q; for (int i = 0; i < q; ++i){ int c, m, x; cin >> c >> m >> x; int l = 0, r = min(c, m); int ans = 0; while (l <= r){ int mid = (l + r) / 2; if (c + m + x - 2 * mid >= mid){ l = mid + 1; ans = mid; } else{ r = mid - 1; } } cout << ans << "\n"; } }
1221
D
Make The Fence Great Again
You have a fence consisting of $n$ vertical boards. The width of each board is $1$. The height of the $i$-th board is $a_i$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $2$ to $n$, the condition $a_{i-1} \neq a_i$ holds. Unfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the $i$-th board by $1$, but you have to pay $b_i$ rubles for it. The length of each board can be increased any number of times (possibly, zero). Calculate the minimum number of rubles you have to spend to make the fence great again! You have to answer $q$ independent queries.
Let's notice that in optimal answer all boards will be increased by no more than two. It is true because if it is beneficial to increase the length of some board by three or more (denote its length as $len$) then increasing to the length $len - 1$, $len - 2$ or $len - 3$ is cheaper and one of these boards is not equal to any of its adjacent boards. Noticing this, we can write a solution based on dynamic programming. Let's $dp_{pos, add}$ is minimum amount of money for making fence $a_1, a_2, \dots , a_{pos}$ great, moreover the last board(with index $pos$) we increase by $add$. Then value $dp_{pos, add}$ can be calculated as follows: $dp_{pos, add} = add \cdot b_{pos} + \min\limits_{x=0 \dots 2, a_{pos-1}+x \neq a_{pos}+add} dp_{pos-1, x}$
[ "dp" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; const long long INF64 = (long long)(1e18) + 100; int t; int n; int a[N]; int b[N]; long long dp[3][N]; long long calc(int add, int pos){ long long &res = dp[add][pos]; if(res != -1) return res; res = INF64; if(pos == n) return res = 0; for(long long x = 0; x <= 2; ++x) if(pos == 0 || a[pos] + x != a[pos - 1] + add) res = min(res, calc(x, pos + 1) + x * b[pos]); return res; } int main() { scanf("%d", &t); for(int tc = 0; tc < t; ++tc){ scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%d", a + i); scanf("%d", b + i); } for(int i = 0; i <= n; ++i) dp[0][i] = dp[1][i] = dp[2][i] = -1; printf("%lld\n", calc(0, 0)); } return 0; }
1221
E
Game With String
Alice and Bob play a game. Initially they have a string $s_1, s_2, \dots, s_n$, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length $a$, and Bob must select a substring of length $b$. It is guaranteed that $a > b$. For example, if $s =$ ...X.. and $a = 3$, $b = 2$, then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string $s =$ ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX. Whoever is unable to make a move, loses. You have to determine who wins if they both play optimally. You have to answer $q$ independent queries.
At first, let's transform input to a more convenient form. We consider only such subsegments that consist of the symbols . and which cannot be expanded to the right or left. For example, for $s = XX...X.X...X..$ we consider segments of length $3$, $1$, $3$, and $2$. Let's divide all such segments into four groups by their length $len$: $len < b$; $b \le len < a$; $a \le len < 2b$; $len \ge 2b$. In such a division, each segment belongs to exactly one type. Suppose that the Bob takes the first turn. If there is a segment of second type, then Bob wins, because he always have a spare turn that Alice cannot make. If there is a segment of fourth type then the Bob also wins because he can make the segment of second type by taking turn in this segment of four type. If there are no segments of second and four types, then victory depends on the parity of the number of segments of the third type. But it is true if the Bob takes first turn. If Alice takes first turn then she doesn't want, after her move, there are segments of the second and fourth types. So if initially there is a segment of second type then Alice loses because she can't take turns into segment of second type. If there are two or more segments of four type then Alice also loses, because after her turn at least one such segments remains. If there are only one segment of four type then Alice have to take turn into this segment. Since the length of this segment doesn't exceed $n$, we can iterate over all possible Alice moves. After Alice's move segment of fourth type can be divided into no more than two new segments, let's denote their types as $t_1$ and $t_2$. If at least one of these segments of second or fourth type, then it's bad turn for Alice. Otherwise Alice win if remaining number of segment of third type is even (note that $t_1$ or $t_2$ also can be the third type). And finally, if initially there are only segments of first or third type, then victory depends on the parity of the number of segments of the third type.
[ "games" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 99; int t; int a, b; string s; int main() { cin >> t; for(int tc = 0; tc < t; ++tc){ cin >> a >> b >> s; vector <int> v; int l = 0; while(l < s.size()){ if(s[l] == 'X'){ ++l; continue; } int r = l + 1; while(r < s.size() && s[r] == '.') ++r; v.push_back(r - l); l = r; } bool ok = true; int id = -1; int cnt = 0; for(int i = 0; i < v.size(); ++i){ if(b <= v[i] && v[i] < a) ok = false; if(b + b <= v[i]){ if(id == -1) id = i; else ok = false; } if(a <= v[i] && v[i] < b + b) ++cnt; } if(!ok){ cout << "NO" << endl; continue; } if(id == -1){ if(cnt & 1) cout << "YES" << endl; else cout << "NO" << endl; continue; } ok = false; int sz = v[id]; assert(sz >= a); for(int rem1 = 0; sz - a - rem1 >= 0; ++rem1){ int rem2 = sz - a - rem1; int ncnt = cnt; if((rem1 >= b + b) || (b <= rem1 && rem1 < a)) continue; if((rem2 >= b + b) || (b <= rem2 && rem2 < a)) continue; if(rem1 >= a) ++ncnt; if(rem2 >= a) ++ncnt; if(ncnt % 2 == 0) ok = true; } if(ok) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
1221
F
Choose a Square
Petya recently found a game "Choose a Square". In this game, there are $n$ points numbered from $1$ to $n$ on an infinite field. The $i$-th point has coordinates $(x_i, y_i)$ and cost $c_i$. You have to choose a square such that its sides are parallel to coordinate axes, the lower left and upper right corners belong to the line $y = x$, and all corners have integer coordinates. The score you get is the sum of costs of the points covered by the selected square minus the length of the side of the square. Note that the length of the side can be zero. Petya asks you to calculate the maximum possible score in the game that can be achieved by placing exactly one square.
Notice that the square ($l, l$) ($r, r$) covers the point ($x, y$) if and only if $l \le min(x, y) \le max(x, y) \le r$. Using this fact, let's reformulate the problem the following way: we have to find the segment $(l, r)$, such that the sum of the segments fully covered by it is maximal. Let's build a segment tree, the $r$-th of its leaves stores $f(l, r)$ - the sum of the segments covered by the segment $(l, r)$ . Initially, it's built for some $l$ such that it is to the right of all segments. Other nodes store the maximum in them. Now let's iterate over the values of $l$ in descending order. Let there be some segment starting in $l$ $(l, x)$ with the cost $c$. All the answers $f(l, r)$ for $r < x$ won't change because they don't cover that new segment. And the values on the suffix from the position $x$ ($r \ge x$) will increase by $c$. The only thing left is to learn how to handle the subtraction of the length of the side. That term is $(r - l)$ and the thing we are looking for is $\max \limits_{r} f(l, r) - (r - l)$. Rewrite it in form $l + \max \limits_{r} f(l, r) - r$ and you'll see that you can just subtract $r$ from the value of the $r$-th leaf of the segment tree at the beginning to get the correct result. Surely, you'll need to add that $l$ after you ask the maximum of all the segtree to obtain the answer. You'll probably need to compress the coordinates - leave only such positions $i$ that there is at least one $x = i$ or $y = i$. Implicit segtree might work but neither ML, nor TL are not friendly to it. Also be careful with the case with all points being negative.
[ "binary search", "data structures", "sortings" ]
2,400
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define all(a) (a).begin(), (a).end() #define sz(a) int((a).size()) #define forn(i, n) for (int i = 0; i < int(n); ++i) typedef long long li; typedef pair<int, int> pt; const int N = 1000 * 1000 + 13; int n; pair<pt, int> a[N]; vector<int> vals; vector<pt> ev[N]; pair<li, int> t[4 * N]; li add[4 * N]; void build(int v, int l, int r) { if (l == r) { t[v] = mp(-vals[l], l); add[v] = 0; return; } int m = (l + r) >> 1; build(v * 2 + 1, l, m); build(v * 2 + 2, m + 1, r); t[v] = max(t[v * 2 + 1], t[v * 2 + 2]); } void push(int v, int l, int r) { if (add[v] == 0) return; t[v].x += add[v]; if (l != r) { add[v * 2 + 1] += add[v]; add[v * 2 + 2] += add[v]; } add[v] = 0; } void upd(int v, int l, int r, int L, int R, int val) { push(v, l, r); if (L > R) return; if (l == L && r == R) { add[v] += val; push(v, l, r); return; } int m = (l + r) >> 1; upd(v * 2 + 1, l, m, L, min(m, R), val); upd(v * 2 + 2, m + 1, r, max(m + 1, L), R, val); t[v] = max(t[v * 2 + 1], t[v * 2 + 2]); } pair<li, int> get(int v, int l, int r, int L, int R) { push(v, l, r); if (L > R) return mp(-li(1e18), 0); if (l == L && r == R) return t[v]; int m = (l + r) >> 1; auto r1 = get(v * 2 + 1, l, m, L, min(m, R)); auto r2 = get(v * 2 + 2, m + 1, r, max(m + 1, L), R); return max(r1, r2); } int main() { scanf("%d", &n); forn(i, n) scanf("%d%d%d", &a[i].x.x, &a[i].x.y, &a[i].y); forn(i, n) { vals.pb(a[i].x.x); vals.pb(a[i].x.y); } vals.pb(0); sort(all(vals)); vals.pb(vals.back() + 1); vals.resize(unique(all(vals)) - vals.begin()); forn(i, n) { int x = lower_bound(all(vals), a[i].x.x) - vals.begin(); int y = lower_bound(all(vals), a[i].x.y) - vals.begin(); ev[min(x, y)].pb(mp(max(x, y), a[i].y)); } n = sz(vals); build(0, 0, n - 1); li ans = -1; int ansl = -1, ansr = -1; for (int i = sz(vals) - 1; i >= 0; i--) { for (auto it : ev[i]) upd(0, 0, n - 1, it.x, n - 1, it.y); auto cur = get(0, 0, n - 1, i, n - 1); if (cur.x + vals[i] > ans) { ans = cur.x + vals[i]; ansl = vals[i]; ansr = vals[cur.y]; } } printf("%lld\n%d %d %d %d\n", ans, ansl, ansl, ansr, ansr); }
1221
G
Graph And Numbers
You are given an undirected graph with $n$ vertices and $m$ edges. You have to write a number on each vertex of this graph, each number should be either $0$ or $1$. After that, you write a number on each edge equal to the sum of numbers on vertices incident to that edge. You have to choose the numbers you will write on the vertices so that there is at least one edge with $0$ written on it, at least one edge with $1$ and at least one edge with $2$. How many ways are there to do it? Two ways to choose numbers are different if there exists at least one vertex which has different numbers written on it in these two ways.
Let $F(S)$ be the number of ways to paint the graph so that all numbers on edges belong to the set $S$. Using inclusion-exclusion we may get that the answer is $F(\{0, 1, 2\}) - F(\{1, 2\}) - F(\{0, 2\}) + F(\{2\}) - F(\{0, 1\}) + F(\{1\}) + F(\{0\}) - F(\{\})$. Okay, let's analyze everything separatedly. $F(\{0, 1, 2\})$ is $2^n$, because every number is allowed; $F(\{1, 2\})$ will be analyzed later; $F(\{0, 2\})$ is $2^C$, where $C$ is the number of connected components - in each component we have to use the same number; $F(\{2\})$ is $2^I$, where $I$ is the number of isolated vertices - every non-isolated vertex should have number $1$ on it, and all isolated vertices may have any numbers; $F(\{0, 1\}) = F(\{1, 2\})$, since these cases are symmetric; $F(\{1\})$ is the number of bipartite colorings of the graph. It is $0$ if the graph contains an odd cycle, or $2^C$ if it is bipartite; $F(\{0\}) = F(\{2\})$, since these cases are symmetric; $F(\{\})$ is $2^n$ if there are no edges in the graph, otherwise it is $0$. So, the only thing left to consider is $F(\{1, 2\})$. Actually, it is easier to calculate $F(\{0, 1\})$ - it is the number of independent sets of this graph. This problem is NP-complete, but when $n = 40$, we may apply meet-in-the-middle technique as follows: divide all vertices into two sets $S_1$ and $S_2$ of roughly equal size; for $S_1$, find all its independent subsets, and for each such subset, find which vertices from $S_2$ can be added to it without breaking its independency; for each subset of $S_2$, find the number of independent subsets of $S_1$ such that no vertex from chosen subset of $S_2$ is adjacent to any vertex from chosen subset of $S_1$ (you may use subset DP and OR-convolution here); find all independent subsets of $S_2$, and for every such subset, add the number of subsets of $S_1$ that can be merged with it so the resulting set is independent. The most time-consuming part is counting all independent sets, so the time complexity is $(O(n2^{n/2}))$.
[ "bitmasks", "brute force", "combinatorics", "dp", "meet-in-the-middle" ]
2,900
#include <bits/stdc++.h> using namespace std; const int N = 40; const int M = 20; long long incident_mask[N]; vector<int> g[N]; int n, m; long long ans = 0; long long cntmask[1 << M]; long long binpow(long long x, long long y) { long long z = 1; while(y > 0) { if(y % 2 == 1) z *= x; x *= x; y /= 2; } return z; } int used[N]; void dfs(int x, int c) { if(used[x]) return; used[x] = c; for(auto y : g[x]) dfs(y, 3 - c); } long long countIsolated() { long long ans = 0; for(int i = 0; i < n; i++) if(g[i].empty()) ans++; return ans; } long long countComponents() { memset(used, 0, sizeof used); long long ans = 0; for(int i = 0; i < n; i++) if(!used[i]) { ans++; dfs(i, 1); } return ans; } bool bipartite() { memset(used, 0, sizeof used); for(int i = 0; i < n; i++) if(!used[i]) dfs(i, 1); for(int i = 0; i < n; i++) for(auto j : g[i]) if(used[i] == used[j]) return false; return true; } long long countIndependentSets() { int m1 = min(n, 20); int m2 = n - m1; //cerr << m1 << " " << m2 << endl; memset(cntmask, 0, sizeof cntmask); for(int i = 0; i < (1 << m1); i++) { long long curmask = 0; bool good = true; for(int j = 0; j < m1; j++) { if((i & (1 << j)) == 0) continue; if(curmask & (1 << j)) good = false; curmask |= ((1 << j) | incident_mask[j]); } if(good) { cntmask[curmask >> m1]++; } } for(int i = 0; i < m2; i++) for(int j = 0; j < (1 << m2); j++) if(j & (1 << i)) cntmask[j] += cntmask[j ^ (1 << i)]; long long ans = 0; for(int i = 0; i < (1 << m2); i++) { long long curmask = 0; bool good = true; for(int j = m1; j < n; j++) { if((i & (1 << (j - m1))) == 0) continue; if(curmask & (1ll << j)) good = false; curmask |= (1ll << j) | incident_mask[j]; } if(good) { //cerr << i << endl; ans += cntmask[(i ^ ((1 << m2) - 1))]; } } return ans; } long long calc(int mask) { if(mask == 0) return binpow(2, n); if(mask == 1 || mask == 4) return countIndependentSets(); if(mask == 2) return binpow(2, countComponents()); if(mask == 3 || mask == 6) return binpow(2, countIsolated()); if(mask == 5) return (bipartite() ? binpow(2, countComponents()) : 0); if(mask == 7) return (m == 0 ? binpow(2, n) : 0); return 0; } int main() { cin >> n >> m; for(int i = 0; i < m; i++) { int x, y; cin >> x >> y; --x; --y; g[x].push_back(y); g[y].push_back(x); incident_mask[x] ^= (1ll << y); incident_mask[y] ^= (1ll << x); } for(int i = 0; i < 8; i++) { //cerr << i << " " << calc(i) << endl; if(__builtin_popcount(i) % 2 == 0) ans += calc(i); else ans -= calc(i); } cout << ans << endl; return 0; }
1223
A
CME
Let's denote correct match equation (we will denote it as CME) an equation $a + b = c$ there all integers $a$, $b$ and $c$ are greater than zero. For example, equations $2 + 2 = 4$ (||+||=||||) and $1 + 2 = 3$ (|+||=|||) are CME but equations $1 + 2 = 4$ (|+||=||||), $2 + 2 = 3$ (||+||=|||), and $0 + 1 = 1$ (+|=|) are not. Now, you have $n$ matches. You want to assemble a CME using \textbf{all} your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME! For example, if $n = 2$, you can buy two matches and assemble |+|=||, and if $n = 5$ you can buy one match and assemble ||+|=|||. Calculate the minimum number of matches which you have to buy for assembling CME. Note, that you have to answer $q$ independent queries.
If $n$ is odd then we have to buy at least one match because integers $a+b$ and $c$ ($a$, $b$ and $c$ is elements of equation $a+b=c$) must be of the same parity, so integer $a+b+c$ is always even. If $n$ is even then we can assemble an equation $1 + \frac{n-2}{2} = \frac{n}{2}$. But there is one corner case. If $n = 2$, then we have to buy two matches, because all integers $a$, $b$ and $c$ must be greater than zero. In this way, the answer is equal: $2$ if $n = 2$; $1$ if $n$ is odd; $0$ if $n$ is even and greater than $2$.
[ "math" ]
800
for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n & 1))
1223
B
Strings Equalization
You are given two strings of equal length $s$ and $t$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings. During each operation you choose two \textbf{adjacent} characters in \textbf{any} string and assign the value of the first character to the value of the second or vice versa. For example, if $s$ is "acbc" you can get the following strings in \textbf{one} operation: - "aabc" (if you perform $s_2 = s_1$); - "ccbc" (if you perform $s_1 = s_2$); - "accc" (if you perform $s_3 = s_2$ or $s_3 = s_4$); - "abbc" (if you perform $s_2 = s_3$); - "acbb" (if you perform $s_4 = s_3$); Note that you can also apply this operation to the string $t$. Please determine whether it is possible to transform $s$ into $t$, applying the operation above any number of times. Note that you have to answer $q$ independent queries.
If there is a character which is contained in string $s$ and $t$ (let's denote it as $c$), then we answer is "YES" because we can turn these string into string consisting only of this character $c$. Otherwise the answer is "NO", because if initially strings have not a common character, then after performing operation they also have not a common character.
[ "strings" ]
1,000
for t in range(int(input())): print('NO' if len(set(input()) & set(input())) == 0 else 'YES')
1223
C
Save the Nature
You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something! You have $n$ tickets to sell. The price of the $i$-th ticket is $p_i$. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them \textbf{to the order you chose}: - The $x\%$ of the price of each the $a$-th sold ticket ($a$-th, $2a$-th, $3a$-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources. - The $y\%$ of the price of each the $b$-th sold ticket ($b$-th, $2b$-th, $3b$-th and so on) in the order you chose is aimed for pollution abatement. If the ticket is in both programs then the $(x + y) \%$ are used for environmental activities. Also, it's known that all prices are multiples of $100$, so there is no need in any rounding. For example, if you'd like to sell tickets with prices $[400, 100, 300, 200]$ and the cinema pays $10\%$ of each $2$-nd sold ticket and $20\%$ of each $3$-rd sold ticket, then arranging them in order $[100, 200, 300, 400]$ will lead to contribution equal to $100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$. But arranging them in order $[100, 300, 400, 200]$ will lead to $100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$. Nature can't wait, so you decided to change the order of tickets in such a way, so that the \textbf{total} contribution to programs will reach at least $k$ in \textbf{minimum} number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least $k$.
At first, let's assume that $x \ge y$ (otherwise, we can swap parameters of programs). Let's define $cont(len)$ as the maximum contribution we can get selling exactly $len$ tickets. Note, in general case sold ticket can be one of $4$ types: tickets with $(x + y)\%$ of the price are contributed; the number of such tickets is $cXY$; tickets with $x\%$ of the price are contributed; the number of such tickets is $cX$; tickets with $y\%$ of the price are contributed; the number of such tickets is $cY$; tickets which are not in both programs. All values $cXY$, $cX$, $cY$ can be easily counted by iterating over indices $i$ from $1$ to $len$ and checking whenever $i$ is divisible by $a$ or by $b$ or both. Now we can understand that it's always optimal to choose in the first group $cXY$ maximums from $p$, in the second group next $cX$ maximums and in the third - next $cY$ maximums. Using the algorithm above we can calculate $cont(len)$ in linear time (just sort $p$ beforehand). The final step is to understand that function $cont(len)$ is non decreasing, so we can just binary search the minimal $len$ with $cont(len) \ge k$. The time complexity is $O(n \log{n})$, but $O(n \log^2{n})$ can pass too.
[ "binary search", "greedy" ]
1,600
fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 && i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x < y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf > 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) >= k) rg = mid else lf = mid } if (rg > n) rg = -1 println(rg) } }
1223
D
Sequence Sorting
You are given a sequence $a_1, a_2, \dots, a_n$, consisting of integers. You can apply the following operation to this sequence: choose some integer $x$ and move \textbf{all} elements equal to $x$ either to the beginning, or to the end of $a$. Note that you have to move all these elements in \textbf{one} direction in \textbf{one} operation. For example, if $a = [2, 1, 3, 1, 1, 3, 2]$, you can get the following sequences in one operation (for convenience, denote elements equal to $x$ as $x$-elements): - $[1, 1, 1, 2, 3, 3, 2]$ if you move all $1$-elements to the beginning; - $[2, 3, 3, 2, 1, 1, 1]$ if you move all $1$-elements to the end; - $[2, 2, 1, 3, 1, 1, 3]$ if you move all $2$-elements to the beginning; - $[1, 3, 1, 1, 3, 2, 2]$ if you move all $2$-elements to the end; - $[3, 3, 2, 1, 1, 1, 2]$ if you move all $3$-elements to the beginning; - $[2, 1, 1, 1, 2, 3, 3]$ if you move all $3$-elements to the end; You have to determine the minimum number of such operations so that the sequence $a$ becomes sorted in non-descending order. Non-descending order means that for all $i$ from $2$ to $n$, the condition $a_{i-1} \le a_i$ is satisfied. Note that you have to answer $q$ independent queries.
Let's consider two sequences of integers $m_1 < m_2 < \dots < m_k$ and $d_1 < d_2 < \dots < d_l$. Sequence $m$ contains integers which were used in some operation in the optimal answer. Sequence $d$ contains integers which were not used. For example, if $a = [2, 1, 3, 5, 4]$, then optimal answer is move all $1$-elements to the beginning and then move all $5$-elements to the end, so $m = [1, 5]$ and $d = [2, 3, 4]$. Two important conditions are held for these sequences: $maxInd(d_{i-1}) < minInd(d_i)$ for every $i$ from $2$ to $l$. $minInd(x)$ is the minimum index $i$ such that $a_i = x$, and $maxInd(x)$ is the maximum index $i$ such that $a_i = x$; for each $i$ from $2$ to $l$ there is no such integer $x$, that $d_i < x < d_{i + 1}$ and sequence $m$ contains this integer $x$. Since the answer is equal to $|m| = k$, we want to minimize this value. So we want to maximize the length of sequence $d$. For each integer $l$ we want to find the maximum integer $dp_l = len$ such that we can sort sequence $a$ without moving elements in range $l \dots l + len - 1$. We can do it with dynamic programming. Let's consider all integers occurring in sequence $a$ in descending order $s_1, s_2, \dots, s_t$ ($s_{i - 1} > s_{i}$ for each $i$ from $2$ to $t$). If $maxInd(s_i) < minInd(s_{i+1})$ then $dp_i = dp_{i + 1} + 1$, otherwise $dp_i = 1$. The answer is equal to $t - \max\limits_{i=1 \dots t} dp_i$, there $t$ is the number of distinct integers in sequence $a$.
[ "dp", "greedy", "two pointers" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf("%d", &t); for(int tc = 0; tc < t; ++tc){ scanf("%d", &n); for(int i = 0; i < n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector <int> v; for(int i = 0; i < n; ++i){ scanf("%d", a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i >= 0; --i){ if(i + 1 == v.size() || r[v[i]] >= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf("%d\n", res); } return 0; }
1223
E
Paint the Tree
You are given a weighted tree consisting of $n$ vertices. Recall that a tree is a connected graph without cycles. Vertices $u_i$ and $v_i$ are connected by an edge with weight $w_i$. Let's define the $k$-coloring of the tree as an assignment of exactly $k$ colors to \textbf{each} vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given $k$-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints). Let's also define the value of a $k$-coloring as the sum of weights of saturated edges. Please calculate the maximum possible value of a $k$-coloring of the given tree. You have to answer $q$ independent queries.
It is obvious that if we paint two vertices in the same color, they should be adjacent to each other - otherwise we could paint them in different colors, and the answer would not be worse. So we can reduce the problem to the following: choose a set of edges with maximum cost such that no vertex is adjacent to more than $k$ chosen edges. This problem is very similar to maximum weighted matching on the tree, and we can try to use some methods that allow us to solve that problem. Let's solve the problem using dynamic programming $dp_{v, f}$ - the answer to the problem for the subtree of the vertex $v$, $f$ is the flag that denotes whether the edge from $v$ to its parent is chosen. Depending on the flag $f$, we can choose $k$ or $k - 1$ edges connecting our vertex to its children (let's denote the maximum number of edges we can choose as $t$). We have to select no more than $t$ child nodes of the vertex $v$. If we choose an edge leading to node $u$, then $dp_{u, 1} + w_ {v, u}$ is added to the $dp$ value we are currently calculating; otherwise, $dp_{u, 0}$ is added. Based on this formula, you have to choose no more than $t$ child nodes of vertex $v$ for which the total sum of $dp_{u, 1} + w_{v, u} - dp_{u, 0}$ is maximum.
[ "dp", "sortings", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i < int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector<pair<int, int>> g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector<long long> adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater<long long>()); forn(i, min(sz(adds), k)) if (adds[i] > 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k <= sz(adds) && adds[k - 1] > 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf("%d%d", &n, &k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf("%d%d%d", &x, &y, &w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf("%d", &q); forn(i, q) printf("%lld\n", solve()); }
1223
F
Stack Exterminable Arrays
Let's look at the following process: initially you have an empty stack and an array $s$ of the length $l$. You are trying to push array elements to the stack in the order $s_1, s_2, s_3, \dots s_{l}$. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push the current element to the top of the stack. Otherwise, you don't push the current element to the stack and, moreover, pop the top element of the stack. If after this process the stack remains empty, the array $s$ is considered stack exterminable. There are samples of stack exterminable arrays: - $[1, 1]$; - $[2, 1, 1, 2]$; - $[1, 1, 2, 2]$; - $[1, 3, 3, 1, 2, 2]$; - $[3, 1, 3, 3, 1, 3]$; - $[3, 3, 3, 3, 3, 3]$; - $[5, 1, 2, 2, 1, 4, 4, 5]$; Let's consider the changing of stack more details if $s = [5, 1, 2, 2, 1, 4, 4, 5]$ (the top of stack is highlighted). - after pushing $s_1 = 5$ the stack turn into $[\textbf{5}]$; - after pushing $s_2 = 1$ the stack turn into $[5, \textbf{1}]$; - after pushing $s_3 = 2$ the stack turn into $[5, 1, \textbf{2}]$; - after pushing $s_4 = 2$ the stack turn into $[5, \textbf{1}]$; - after pushing $s_5 = 1$ the stack turn into $[\textbf{5}]$; - after pushing $s_6 = 4$ the stack turn into $[5, \textbf{4}]$; - after pushing $s_7 = 4$ the stack turn into $[\textbf{5}]$; - after pushing $s_8 = 5$ the stack is empty. You are given an array $a_1, a_2, \ldots, a_n$. You have to calculate the number of its subarrays which are stack exterminable. Note, that you have to answer $q$ independent queries.
Let's understand how calculate the array $nxt$, such that $nxt_l$ is equal to the minimum index $r > l$ such that subarray $a_{l \dots r}$ is stack exterminable. If there is no such index, then $nxt_l = -1$. If we calculate this array then we solve this task by simple dynamic programming. Let's calculate it in order $nxt_n, nxt_{n-1}, \dots , nxt_1$ by dynamic programming. At first consider simple case. If $a_i = a_{i + 1}$, then $nxt_i = i + 1$. Otherwise we have to "add" the block $a_{i+1} \dots a_{nxt_{i+1}}$ (of course, $nxt_{i + 1}$ should be not equal to $-1$) and check that $a_i = a_{1 + nxt_{i + 1}}$. If this ($a_i = a_{1 + nxt_{i + 1}}$) also is not true, then you have to add a new block $a_{1 + nxt_{i+1}} \dots a_{nxt_{1 + nxt_{i+1}}}$ and check the condition $a_i = a_{1 + nxt_{1 + nxt_{i+1}}}$. If this condition also is not try, then you have to add a new block and so on. It is correct solution, but it can be too slowly. Let's understand, that we add blocks to $a_i$ until condition $a_i = a_{1 + nxt_{\dots}}$ is holds. Let's assume, that we have an array $nxtX$ (this array contains a hashMaps, for example you can use map in C++), such that $nxtX_{i, x}$ is is equal to the minimum index $r > l$ such that subarray $a_{l \dots r}$ is stack exterminable and $x = a_{r + 1}$. Then we can easily calculate the value $nxt_i = nxtX_{i+1, a_i} + 1$. Remains to understand, how to calculate $nxtX_{i}$. For this we just can make an assignment $nxtX_{i} = nxtX_{nxt_i + 1}$. And then update $nxtX_{i, a_{nxt_i + 1}} = nxt_{i} + 1$. But I deceived you a little. We can't make an assignment $nxtX_{i} = nxtX_{nxt_i + 1}$ because it is to slow. Instead that you need to swap elements $nxtX_{i}$ and $nxtX_{nxt_i + 1}$, this can be done using the function $swap$ in C++ or Java (time complexity of $swap$ if $O(1)$).
[ "data structures", "divide and conquer", "dp", "hashing" ]
2,600
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map<int, int> nxtX[N]; int main() { scanf("%d", &t); for(int tc = 0; tc < t; ++tc){ scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); for(int i = 0; i < n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i >= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos < n && a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos < n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i >= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf("%lld\n", res); } return 0; }
1223
G
Wooden Raft
Suppose you are stuck on a desert island. The only way to save yourself is to craft a wooden raft and go to the sea. Fortunately, you have a hand-made saw and a forest nearby. Moreover, you've already cut several trees and prepared it to the point that now you have $n$ logs and the $i$-th log has length $a_i$. The wooden raft you'd like to build has the following structure: $2$ logs of length $x$ and $x$ logs of length $y$. Such raft would have the area equal to $x \cdot y$. Both \textbf{$x$ and $y$ must be integers} since it's the only way you can measure the lengths while being on a desert island. And both \textbf{$x$ and $y$ must be at least $2$} since the raft that is one log wide is unstable. You can cut logs in pieces but you can't merge two logs in one. What is the maximum area of the raft you can craft?
Let's iterate $y$ from $2$ to $A$, where $A = \max(a_i)$. And let's try to find the best answer for a fixed $y$ in $O(\frac{A}{y})$ time. How to do so? At first, we can quite easily calculate the total number of logs of length $y$ we can acquire (denote it as $cntY$): since all $a_i \in [ky, ky + y)$ give the same number of logs which is equal to $k$, then let's just count the number of $a_i$ in $[ky, ky + y)$ for each $k$. We can do so using frequency array and prefix sums on it. There are two cases in the problem: both logs of length $x$ lies in the same log $a_i$ or from the different logs $a_i$ and $a_j$. In the first case it's the same as finding one log of length $2x$. But in both cases we will divide all possible values of $x$ ($2x$) in segments $[ky, ky + y)$ and check each segment in $O(1)$ time. Let's suppose that $2x \in [ky, ky + y)$ and there is $a_i$ such that $a_i \ge 2x$ and $(a_i \mod y) \ge (2x \mod y)$. In that case it's optimal to cut $2x$ from $a_i$ and, moreover, it's optimal to increase $2x$ while we can. It leads us straight to the solution, let's keep $\max(a_i \mod y)$ over $a_i \ge ky$ and check only $2x = ky + \max(a_i \mod y)$ (maybe minus one in case of wrong parity). We can maintain this max iterating $k$ in descending order. And since $\max(a_i \mod y)$ for all $a_i \in [ky, ky + y)$ is just a $\max(a_i~|~a_i < ky + y)$. We can find such $a_i$ in $O(1)$ using precalc. To check the chosen $2x$ is trivial: the number of remaining logs $y$ is equal to $cntY - k$ and the plot will have the area $y \cdot \min(x, cntY - k)$. The case with cutting $x$-s from different $a_i$ and $a_j$ is based on the same idea, but we need to maintain two maximums $mx1$ and $mx2$ ($mx1 \ge mx2$). But in this case $x$ can be equal to both $mx1$ or $mx2$. If $x = ky + mx2$ then everything is trivial: the number of logs $y$ is $cntY - 2 \cdot k$ and so on. If $x = ky + mx1$ then we need to additional check the existence of $a_i \ge x$ and $a_j \ge x$. Remaining number of logs $y$ will be equal to $cntY - 2 \cdot k - 1$ and so on. In result, for each $y$ we can calculate the answer in $O(\frac{A}{y})$, so the total time complexity is $O(n + \sum_{y = 2}^{A}{O(\frac{A}{y})}) = O(n + A \log A)$. P.S.: We decided to allow the $O(A \log^2 A)$ solution which binary search $x$ for each $y$ to pass if it's carefully written. 1240F - Football
[ "binary search", "math", "number theory" ]
3,200
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector<int> a; inline bool read() { if(!(cin >> n)) return false; a.resize(n); fore(i, 0, n) cin >> a[i]; return true; } template<class A> pair<A, A> upd(const pair<A, A> &mx, const A &val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector<int> cnt, sum; vector<int> prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x < 2 || y < 2) return; if (ans >= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i > 0) prv[i] = prv[i - 1]; if(cnt[i] > 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i < sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair<pt, pt> mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf >= 0) { int cntMore = (mx.x.x >= 0) + (mx.y.x >= 0); int val1 = prv[rg - 1]; if (val1 >= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 >= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x >= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x >= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y < rg) >= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout << ans << endl; cerr << rx << " " << ry << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1225
A
Forgetting Things
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation $a + 1 = b$ with positive integers $a$ and $b$, but Kolya forgot the numbers $a$ and $b$. He does, however, remember that the first (leftmost) digit of $a$ was $d_a$, and the first (leftmost) digit of $b$ was $d_b$. Can you reconstruct any equation $a + 1 = b$ that satisfies this property? It may be possible that Kolya misremembers the digits, and there is no suitable equation, in which case report so.
The answer exists only if $d_a = d_b$, $d_b = d_a + 1$, or $d_a = 9$ and $d_b = 1$. Alternatively, one could simply check all $a$ up to 100 (or another reasoable bound).
[ "math" ]
900
null
1225
B1
TV Subscriptions (Easy Version)
\textbf{The only difference between easy and hard versions is constraints.} The BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show, the episode of which will be shown in $i$-th day. The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately. How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $d$ ($1 \le d \le n$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $d$ consecutive days in which all episodes belong to the purchased shows.
We are looking for a segment of length $d$ with the smallest number of distinct values. In small limitations one could just try all segments and count the number of distinct elements naively (for example, by sorting or with an std::set).
[ "implementation" ]
1,000
null
1225
B2
TV Subscriptions (Hard Version)
\textbf{The only difference between easy and hard versions is constraints.} The BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the show, the episode of which will be shown in $i$-th day. The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately. How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $d$ ($1 \le d \le n$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $d$ consecutive days in which all episodes belong to the purchased shows.
In larger limitations we have to use two pointers to maintain the number of distinct elements between segments. We can store a map or an array that counts the number of occurences of each element, as well as the number of distinct elements (i.e. the number of non-zero entries in the map). Moving the segment to the right involves changing two entries of the map, keeping track of which entries become/cease to be non-zero. The complexity is $O(n \log n)$ or $O(n)$ (both are acceptable).
[ "implementation", "two pointers" ]
1,300
null
1225
C
p-binary
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer $p$ (which may be positive, negative, or zero). To combine their tastes, they invented $p$-binary numbers of the form $2^x + p$, where $x$ is a \textbf{non-negative} integer. For example, some $-9$-binary ("minus nine" binary) numbers are: $-8$ (minus eight), $7$ and $1015$ ($-8=2^0-9$, $7=2^4-9$, $1015=2^{10}-9$). The boys now use $p$-binary numbers to represent everything. They now face a problem: given a positive integer $n$, what's the smallest number of $p$-binary numbers (not necessarily distinct) they need to represent $n$ as their sum? It may be possible that representation is impossible altogether. Help them solve this problem. For example, if $p=0$ we can represent $7$ as $2^0 + 2^1 + 2^2$. And if $p=-9$ we can represent $7$ as one number $(2^4-9)$. Note that negative $p$-binary numbers are allowed to be in the sum (see the Notes section for an example).
Suppose we want to represent $n$ as the sum of $k$ $p$-binary numbers. We must have $n = \sum_{i = 1}^k (2^{x_i} + p)$ for a suitable choice of $x_1, \ldots, x_k$. Moving all $p$'s to the left-hand side, we must have $n - kp = \sum_{i=1}^k 2^{x_i}$. In particular, $n - kp$ has to be at least $k$. Consider the binary representation of $n - kp$. If it has more than $k$ bits equal to $1$, there is no way we can split it into $k$ powers of two. Otherwise, we can start by taking the binary representation, and if it contains less than $k$ powers, we can always split larger powers into two smaller ones. We can now check all values of $k$ starting from the smallest. If $n \geq 31p + 31$, then the answer will not exceed $31$ since $n - 31p$ is less than $2^{31}$, hence is always representable with $31$ powers. Otherwise, we have $n - 31(p + 1) < 0$. Since $n > 0$, it means that $p + 1 < 0$, and $n - kp < k$ for all $k > 31$, thus the answer does not exist.
[ "bitmasks", "brute force", "math" ]
1,600
null
1225
D
Power Products
You are given $n$ positive integers $a_1, \ldots, a_n$, and an integer $k \geq 2$. Count the number of pairs $i, j$ such that $1 \leq i < j \leq n$, and there exists an integer $x$ such that $a_i \cdot a_j = x^k$.
Suppose that $x \cdot y$ is a $k$-th power. The sufficient and necessary condition for that is: for any prime $p$, the total number of times it divides $x$ and $y$ must be divisible by $k$. Let us factorize each number $a_i = p_1^{b_1} \ldots p_m^{b_m}$, and associate the list of pairs $L_i ((p_1, b_1 \bmod k), \ldots, (p_m, b_m \bmod k))$, omitting the entries with $b_i \bmod k = 0$. For example, for $360 = 2^3 2^2 5^1$ and $k = 2$, the corresponding list would be $((2, 1), (5, 1))$. If $a_i \cdot a_j$ is a $k$-th power the the primes in the respective lists should match, and $b_i \bmod k$ add up to $k$ for corresponding primes. Indeed, if a prime is absent from one of the lists (i.e. the exponent is divisible by $k$), then it should be absent from the other list too. Otherwise, the total exponent for this prime should be divisible by $k$, hence the remainders should add up to $k$. We now have that for every $a_i$ there is a unique possible list $L'_i$ for the other number that would give a $k$-th power product. We can now maintain the count for each of the occuring lists (e.g. with std::map), and every number we meet we add the number of occurences of $L'_i$ to the answer, and increase the count for $L_i$ by one. The total complexity comprises of factoring all the input numbers (in $O(\sqrt{max a_i})$ or in $O(\log \max a_i)$ with precomputed sieve), and maintaining a map from vectors to numbers. The total size of all vectors is roughly $O(n \log n)$, so the complexity of maintaining a map is $O(n \log ^2 n)$, or $O(n \log n)$ with a hashmap.
[ "hashing", "math", "number theory" ]
1,800
null
1225
E
Rock Is Push
You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$. Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on. The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal. Count the number of different legal paths you can take from the start to the goal modulo $10^9 + 7$. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.
Let us compute $R_{i, j}$ and $D_{i, j}$ - the number of legal ways to reach the goal assuming: we've arrived at the cell $(i, j)$; our next move is right/down respectively; our previous move (if there was a previous move) was not in the same direction. By definition, let us put $D_{n, m} = R_{n, m} = 1$. We can see that all rocks reachable from $(i, j)$ in these assumptions should be in their original places, thus the answer is independent of the way we've reached the cell $(i, j)$ in the first place. Recalculation is fairly straightforward. For example, for $D_{i, j}$ let $k$ be the number of stones directly below $(i, j)$. We can make at most $n - k - i$ moves before we make the turn to the right, thus we have $D_{i, j} = \sum_{t = 1}^{n - k - i} R_{i + t, j}$. This allows to compute $R_{i, j}$ and $D_{i, j}$ with dynamic programming starting from the cells with larger coordinates. The formula hints at some range summing techniques, like computing prefix sums or maintaing a more sophisticated RSQ structure. However, these are not needed in this problem. Indeed, as we consider summation ranges for $D_{i, j}$ and $D_{i + 1, j}$, we can see that they differ by at most one entry on each side. It follows that to compute $D_{i, j}$, we can take $D_{i, j}$ and add/subtract at most two values of $R_{i + t, j}$. The values near the goal cell may need some extra treatment since they are not always a proper range sum. Also, the case $n = m = 1$ need to be treated separately. The total complexity is $O(nm)$ (additional $\log$ for RSQ should be fine though).
[ "binary search", "dp" ]
2,200
null
1225
F
Tree Factory
Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order. The tree in question is a rooted tree with $n$ vertices labelled with distinct integers from $0$ to $n - 1$. The vertex labelled $0$ is the root of the tree, and for any non-root vertex $v$ the label of its parent $p(v)$ is less than the label of $v$. All trees at the factory are made from bamboo blanks. A bamboo is a rooted tree such that each vertex has exactly one child, except for a single leaf vertex with no children. The vertices of a bamboo blank can be labelled arbitrarily before its processing is started. To process a bamboo into another tree a single type of operation can be made: choose an arbitrary non-root vertex $v$ such that its parent $p(v)$ is not a root either. The operation consists of changing the parent of $v$ to its parent's parent $p(p(v))$. Note that parents of all other vertices remain unchanged, in particular, the subtree of $v$ does not change. Efficiency is crucial, hence you have to minimize the number of operations to make the desired tree from a bamboo blank. Construct any optimal sequence of operations to produce the desired tree. Note that the labelling of the resulting tree has to coincide with the labelling of the desired tree. Formally, the labels of the roots have to be equal, and for non-root vertices with the same label the labels of their parents should be the same. It is guaranteed that for any test present in this problem an answer exists, and further, an optimal sequence contains at most $10^6$ operations. Note that \textbf{any hack that does not meet these conditions will be invalid}.
Let's solve the problem backwards: given a tree, transform it into a bamboo with reverse operations. A reverse operation in this context looks like this: given a vertex $v$ and its two distinct children $u$ and $w$, make $w$ the parent of $u$. What's the lower bound on the number of operations we need to make? We can see that the depth of the tree, i.e. the length of the longest vertical path starting from the root, can increase by at most one per operation. On the other hand, the depth of the bamboo is $n - 1$. Therefore, we'll need to make at least $n - 1 - (\text{initial depth of the tree})$ operations. This number would always be enough if for any non-bamboo tree we could find an operation that would increase its depth. And indeed we can: consider a longest path starting from the root. If all its vertices have at most one children, the tree is a bamboo and we are done. Otherwise, take any vertex $v$ on the path with at least two children, its child $u$ on the longest path, and any other child $w$, then make $w$ the parent of $u$. One can see that there is a longer path now. One efficient way to do these operations successively is to keep track of the lowest candidate for $u$. After applying an operation, the candidate is either $u$ again, or one of its ancestors. With standard amortized analysis, we can now perform all these operations in $O(n)$ time. To output the answer, print the labelling of the final bamboo you obtain, followed by the reverse sequence of the operations you've made.
[ "constructive algorithms", "greedy", "trees" ]
2,500
null
1225
G
To Make 1
There are $n$ positive integers written on the blackboard. Also, a positive number $k \geq 2$ is chosen, and none of the numbers on the blackboard are divisible by $k$. In one operation, you can choose any two integers $x$ and $y$, erase them and write one extra number $f(x + y)$, where $f(x)$ is equal to $x$ if $x$ is not divisible by $k$, otherwise $f(x) = f(x / k)$. In the end, there will be a single number of the blackboard. Is it possible to make the final number equal to $1$? If so, restore any sequence of operations to do so.
An experienced eye will immediately spot a subset dynamic programming solution in roughly $O(3^n \sum a_i)$ time, but the time constraints will not allow this. What to do? Suppose there is a way to obtain 1 in the end. Looking at how many times each initial number $a_i$ gets divided by $k$ (including the divisions of the subsequent numbers containing it), we can obtain the expression $1 = \sum_{i = 1}^n a_i k^{-b_i}$, where $b_i$ are respective numbers of divisions. What if we were given such an expression to start with? Can we always restore a sequence of operations? As it turns out, yes! Prove by induction. If there a single number, then it must be $1$ and we are done. Otherwise, let $B = \max b_i$. We argue that there are at least two numbers $a_i$ and $a_j$ with $b_i = b_j = B$. Indeed, assume there was only one such number $a_j$. Multiply both sides of the expression to obtain $k^B = \sum_{i = 1}^n a_i k^{B - b_i}$. The left-hand side, and all but one summand of the right-hand are divisible by $k$. But since $a_j$ is not divisible by $k$, the right-hand side is not divisible by $k$, a contradiction. Since we have two numbers $a_i$ and $a_j$, let's replace them with $f(a_i + a_j) = a'$, and put $b' = B - (\text{the number of times }(a_i + a_j)\text{ is divisible by }k)$. We can see that the new set of numbers still satisfies the expression above, hence by induction hypothesis we can always finish the operation sequence. Note that this argument can be converted into an answer restoration routine: given the numbers $b_i$, group any pair of numbers $a_i$ and $a_j$ with $b_i = b_j$. The question now becomes: can we find suitable numbers $b_1, \ldots, b_n$ such that the above expression is satisfied? We can do this with a more refined subset dynamic programming. For a subset $S \subseteq \{1, \ldots, n\}$ and a number $x$, let $dp_{S, x}$ be true if and only if we can have an expression $x = \sum_{i \in S} a_i k^{-b_i}$ for suitable $b_i$. The initial state is $dp_{\varnothing, 0} = 1$. The transitions are as follows: include $a_i$ into $S$: $dp_{S, x} \implies dp_{S + a_i, x + a_i}$; increase all $b_i$ by 1: if $x$ is divisible by $k$, then $dp_{S, x} \implies dp_{S, x / k}$. By definition, we can obtain 1 as the final number iff $dp_{\{1, \ldots, n\}, 1}$. Straightforward recalculation requires $O(n 2^n \cdot \sum a_i)$ time. However, the first type of transition can be optimized using bitsets, bringing the complexity down to $O(2^n \sum a_i \cdot (1 + n / w))$, where $w$ is the size of the machine word ($32$ or $64$). To restore $b_i$, trace back from $dp_{\{1, \ldots, n\}, 1}$ to $dp_{\varnothing, 0}$ using reachable states.
[ "bitmasks", "constructive algorithms", "dp", "greedy", "number theory" ]
3,100
null
1227
A
Math Problem
Your math teacher gave you the following problem: There are $n$ segments on the $x$-axis, $[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$. The segment $[l; r]$ includes the bounds, i.e. it is a set of such $x$ that $l \le x \le r$. The length of the segment $[l; r]$ is equal to $r - l$. Two segments $[a; b]$ and $[c; d]$ have a common point (intersect) if there exists $x$ that $a \leq x \leq b$ and $c \leq x \leq d$. For example, $[2; 5]$ and $[3; 10]$ have a common point, but $[5; 6]$ and $[1; 4]$ don't have. You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $n$ segments. In other words, you need to find a segment $[a; b]$, such that $[a; b]$ and every $[l_i; r_i]$ have a common point for each $i$, and $b-a$ is minimal.
Find the left most right point for all segments, call it $r_{min}$. The right most left point for all segments, call it $l_{max}$. It's easy to see that the answer is $\max(0,l_{max} - r_{min})$.
[ "math" ]
1,100
null
1227
B
Box
Permutation $p$ is a sequence of integers $p=[p_1, p_2, \dots, p_n]$, consisting of $n$ distinct (unique) positive integers between $1$ and $n$, inclusive. For example, the following sequences are permutations: $[3, 4, 1, 2]$, $[1]$, $[1, 2]$. The following sequences are not permutations: $[0]$, $[1, 2, 1]$, $[2, 3]$, $[0, 1, 2]$. The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $p$ of length $n$. You don't know this permutation, you only know the array $q$ of prefix maximums of this permutation. Formally: - $q_1=p_1$, - $q_2=\max(p_1, p_2)$, - $q_3=\max(p_1, p_2,p_3)$, - ... - $q_n=\max(p_1, p_2,\dots,p_n)$. You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $q$ for this permutation is equal to the given array).
Obviously, if $q_{i} \neq q_{i-1}$ then $p_{i} = q_{i}$. We assume $q_{0} = 0$. Other positions can be filled with the left numbers in increasing order. Then check whether the permutation is correct or not.
[ "constructive algorithms" ]
1,200
null
1227
C
Messy
You are fed up with your messy room, so you decided to clean it up. Your room is a bracket sequence $s=s_{1}s_{2}\dots s_{n}$ of length $n$. Each character of this string is either an opening bracket '(' or a closing bracket ')'. In one operation you can choose any consecutive substring of $s$ and reverse it. In other words, you can choose any substring $s[l \dots r]=s_l, s_{l+1}, \dots, s_r$ and change the order of elements in it into $s_r, s_{r-1}, \dots, s_{l}$. For example, if you will decide to reverse substring $s[2 \dots 4]$ of string $s=$"{(\textbf{(()}))}" it will be equal to $s=$"{(\textbf{)((}))}". A regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not. A prefix of a string $s$ is a substring that starts at position $1$. For example, for $s=$"(())()" there are $6$ prefixes: "(", "((", "(()", "(())", "(())(" and "(())()". In your opinion, a neat and clean room $s$ is a bracket sequence that: - the whole string $s$ is a regular bracket sequence; - \textbf{and} there are exactly $k$ prefixes of this sequence which are regular (including whole $s$ itself). For example, if $k = 2$, then "(())()" is a neat and clean room. You want to use at most $n$ operations to make your room neat and clean. Operations are applied one after another sequentially. It is guaranteed that the answer exists. Note that you \textbf{do not need} to minimize the number of operations: find any way to achieve the desired configuration in $n$ or less operations.
It's easy to construct a valid bracket sequence, for example "()()()() ... (((...(())...))))". Now let the initial bracket sequence be $s$, the target one be $t$. For each position, if $s_{i} = t_{i}$ then we needn't do anything, otherwise find a position $j$ which $j > i$ and $s_{j} = t_{i}$ (it exists), and reverse the segment $[i \dots j]$. The number of operations is at most $n$, and the solution works in $O(n^{2})$.
[ "constructive algorithms" ]
1,700
null
1227
D2
Optimal Subsequences (Hard Version)
This is the harder version of the problem. In this version, $1 \le n, m \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. You are given a sequence of integers $a=[a_1,a_2,\dots,a_n]$ of length $n$. Its subsequence is obtained by removing zero or more elements from the sequence $a$ (they do not necessarily go consecutively). For example, for the sequence $a=[11,20,11,33,11,20,11]$: - $[11,20,11,33,11,20,11]$, $[11,20,11,33,11,20]$, $[11,11,11,11]$, $[20]$, $[33,20]$ are subsequences (these are just some of the long list); - $[40]$, $[33,33]$, $[33,20,20]$, $[20,20,11,11]$ are not subsequences. Suppose that an additional non-negative integer $k$ ($1 \le k \le n$) is given, then the subsequence is called optimal if: - it has a length of $k$ and the sum of its elements is the maximum possible among all subsequences of length $k$; - and among all subsequences of length $k$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $b=[b_1, b_2, \dots, b_k]$ is lexicographically smaller than the sequence $c=[c_1, c_2, \dots, c_k]$ if the first element (from the left) in which they differ less in the sequence $b$ than in $c$. Formally: there exists $t$ ($1 \le t \le k$) such that $b_1=c_1$, $b_2=c_2$, ..., $b_{t-1}=c_{t-1}$ and at the same time $b_t<c_t$. For example: - $[10, 20, 20]$ lexicographically less than $[10, 21, 1]$, - $[7, 99, 99]$ is lexicographically less than $[10, 21, 1]$, - $[10, 21, 0]$ is lexicographically less than $[10, 21, 1]$. You are given a sequence of $a=[a_1,a_2,\dots,a_n]$ and $m$ requests, each consisting of two numbers $k_j$ and $pos_j$ ($1 \le k \le n$, $1 \le pos_j \le k_j$). For each query, print the value that is in the index $pos_j$ of the optimal subsequence of the given sequence $a$ for $k=k_j$. For example, if $n=4$, $a=[10,20,30,20]$, $k_j=2$, then the optimal subsequence is $[20,30]$ — it is the minimum lexicographically among all subsequences of length $2$ with the maximum total sum of items. Thus, the answer to the request $k_j=2$, $pos_j=1$ is the number $20$, and the answer to the request $k_j=2$, $pos_j=2$ is the number $30$.
Let's first solve the simplified version (Easy Version) without paying attention to the efficiency of the algorithm. It is clear that the sum of the elements of the optimal subsequence is equal to the sum of $k$ maximal elements of the sequence $a$. Let the smallest (the $k$-th) of $k$ maximal elements be $x$. Obviously, all elements of $a$ that are greater than $x$ and several elements that are equal to $x$ will be included in the optimal subsequence. Among all the elements that are equal to $x$ you need to choose those that are located to the left. Thus, a simplified version solution might look like this: in order to build an optimal subsequence of length $k$, take an array $a$ and construct its copy $b$ sorted by non-increasing: $b_1 \ge b_2 \ge \dots \ge b_n$; let $x = b_k$; we take the following subsequence from $a$: all the elements $a_i > x$ and several leftmost occurrences of $a_i = x$ (you need to take such occurrences in order to get exactly $k$ elements in total). To solve the complicated version, we note that the solution above is equivalent to sorting all elements of $a$ first of all by value (non-increasing), and secondly by position (ascending). The desired optimal subsequence is simply $k$ first elements of $a$ in this order. To quickly process requests, we will use the opportunity to read all requests in the program, sort them by $k_j$ and process them in that order. Then, in order to answer the request $k_j$, $pos_j$ you need to take $k_j$ elements in this order and choose the $pos_j$-th from them (just in the order of indices). Thus, the problem is reduced to finding the $pos$-th element in a set, where only elements are added. This can be solved using a wide range of data structures (a tree of segments, a Fenwick tree, even sqrt-compositions), and using a non-standard tree built into g++ that supports the operation "quickly find the $pos$ th element of a set". Below is the solution code:
[ "data structures", "greedy" ]
1,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define forn(i, n) for (int i = 0; i < int(n); i++) typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; int main() { int n; cin >> n; vector<int> a(n); vector<pair<int,int>> b; forn(i, n) { cin >> a[i]; b.push_back({-a[i], i}); } sort(b.begin(), b.end()); int m; cin >> m; vector<pair<pair<int,int>,int>> req(m); forn(i, m) { cin >> req[i].first.first >> req[i].first.second; req[i].second = i; } sort(req.begin(), req.end()); vector<int> ans(m); ordered_set pos; int len = 0; forn(i, m) { while (len < req[i].first.first) pos.insert(b[len++].second); ans[req[i].second] = a[*pos.find_by_order(req[i].first.second - 1)]; } forn(i, m) cout << ans[i] << endl; }
1227
E
Arson In Berland Forest
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events. A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $n \times m$ rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". \textbf{You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.} The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as $0$) some trees were set on fire. At the beginning of minute $0$, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of $8$ neighboring trees. At the beginning of minute $T$, the fire was extinguished. The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of $T$ (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of $T$ (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire. Note that you'd like to maximize value $T$ but the set of trees can be arbitrary.
Let's note that if there is a possible configuration in which the forest burnt $T$ minutes then there is a configuration when the forest burnt $T - 1$ minutes. So we can binary search the answer. Now we need to check the existence of the configuration for a fixed time $T$. Let's find all trees that can be set on fire. There are two equivalent conditions for such trees: either the square of length $2T + 1$ with a center in this cell contains only X-s or a distance between the current cell and any cell with "." (or border) is more or equal to $T$. We can use any of the conditions. The first condition can be checked with prefix sums on 2D - we can precalculate them one time and use them to take a sum on a rectangle. The second condition can be checked by running bfs from all "."-s or borders (or from X-s which are neighboring to "."-s or to the borders) also one time before the binary search. The second step is to check that it's possible to cover all burnt trees starting from all set-on-fire trees. We can check it either with "add value on a rectangle" (using prefix sums) since each set-on-fire tree will burn a $(2T + 1) \times (2T + 1)$ square with center in it. Or, alternatively, we can run bfs from set-on-fire trees. Anyways, both algorithms have $O(nm)$ complexity. And, since all damaged trees are shown on the map, the answer can't be more than $\min(n, m)$. So, the total complexity is $O(nm \log(\min(n, m)))$.
[ "binary search", "graphs", "shortest paths" ]
2,200
null
1227
F1
Wrong Answer on test 233 (Easy Version)
\begin{quote} Your program fails again. This time it gets "Wrong answer on test 233" \end{quote} .This is the easier version of the problem. In this version $1 \le n \le 2000$. You can hack this problem only if you solve and lock both problems. The problem is about a test containing $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \dots, h_n$ are known to you in this problem. However, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically. Formally, the mistake moves the answer for the question $i$ to the question $i \bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$. We call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total. You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\,244\,353$. For example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.
First of all, special judge for $k = 1$, where the answer is zero. Let $d$ be the difference between the points for latest answer suit and the previous one. An valid answer suit means $d > 0$. For positions satisfying $h_{i} = h_{i \space \mod \space n + 1}$, the answer for this position will not affect $d$. Assume there's $t$ positions which $h_{i} \neq h_{i \space \mod \space n + 1}$. For a fixed position $i$ which $h_{i} \neq h_{i \space \mod \space n + 1}$, let your answer for this position is $a_{i}$ . If $a_{i} = h_{i}$, then the $d$ value will decrease by 1. We call this kind of position as a decreasing position. If $a_{i} = h_{i \space \mod \space n + 1}$, then the $d$ value increase by 1. We call this kind of position as a increasing position. Otherwise $d$ value will not be affected, we call this kind of position zero position. Obviously the number of increasing position should be exact larger then the decreasing position. So let's enumerate the number of zero positions. We can find the answer is equal to $k^{n-t} \times \sum_{0 \leq i \leq t - 1}{[(k-2)^i \times \binom{t}{i} \times \sum_{[\frac{t-i}{2}]+1 \leq j \leq t - i}{\binom{t-i}{j}}]}$. $i$ represent the number of zero positions and $j$ represent the number of increasing positions. The only problem is how to calculate $\sum_{[\frac{t-i}{2}]+1 \leq j \leq t - i}{\binom{t-i}{j}}$ quickly. Due to $\binom{n}{x} = \binom{n}{n-x}$, we can tell that when $t - i$ is odd, $\sum_{[\frac{t-i}{2}]+1 \leq j \leq t - i}{\binom{t-i}{j}} = 2^{t-i-1}$. Otherwise it is equal to $\frac{2^{t-i} - \binom{t-i}{\frac{t-i}{2}}}{2}$.
[ "dp" ]
2,200
null
1227
F2
Wrong Answer on test 233 (Hard Version)
\begin{quote} Your program fails again. This time it gets "Wrong answer on test 233" \end{quote} .This is the harder version of the problem. In this version, $1 \le n \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. The problem is to finish $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \dots, h_n$ are known to you in this problem. However, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically. Formally, the mistake moves the answer for the question $i$ to the question $i \bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$. We call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total. You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\,244\,353$. For example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.
First of all, special judge for $k = 1$, where the answer is zero. Let $d$ be the difference between the points for latest answer suit and the previous one. An valid answer suit means $d > 0$. For positions satisfying $h_{i} = h_{i \space \mod \space n + 1}$, the answer for this position will not affect $d$. Assume there's $t$ positions which $h_{i} \neq h_{i \space \mod \space n + 1}$. For a fixed position $i$ which $h_{i} \neq h_{i \space \mod \space n + 1}$, let your answer for this position is $a_{i}$ . If $a_{i} = h_{i}$, then the $d$ value will decrease by 1. We call this kind of position as a decreasing position. If $a_{i} = h_{i \space \mod \space n + 1}$, then the $d$ value increase by 1. We call this kind of position as a increasing position. Otherwise $d$ value will not be affected, we call this kind of position zero position. Obviously the number of increasing position should be exact larger then the decreasing position. So let's enumerate the number of zero positions. We can find the answer is equal to $k^{n-t} \times \sum_{0 \leq i \leq t - 1}{[(k-2)^i \times \binom{t}{i} \times \sum_{[\frac{t-i}{2}]+1 \leq j \leq t - i}{\binom{t-i}{j}}]}$. $i$ represent the number of zero positions and $j$ represent the number of increasing positions. The only problem is how to calculate $\sum_{[\frac{t-i}{2}]+1 \leq j \leq t - i}{\binom{t-i}{j}}$ quickly. Due to $\binom{n}{x} = \binom{n}{n-x}$, we can tell that when $t - i$ is odd, $\sum_{[\frac{t-i}{2}]+1 \leq j \leq t - i}{\binom{t-i}{j}} = 2^{t-i-1}$. Otherwise it is equal to $\frac{2^{t-i} - \binom{t-i}{\frac{t-i}{2}}}{2}$.
[ "combinatorics", "math" ]
2,400
null
1227
G
Not Same
You are given an integer array $a_1, a_2, \dots, a_n$, where $a_i$ represents the number of blocks at the $i$-th position. It is guaranteed that $1 \le a_i \le n$. In one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a position without blocks. All subsets that you choose should be different (unique). You need to remove all blocks in the array using at most $n+1$ operations. It can be proved that the answer always exists.
The solution can be inspired by the output format :) First of all, sort all numbers in decreasing order. Let them be $A_{1}, A_{2} \dots , A_{n}$. We will construct the answer column by column. Let us use a set of binary string to represent a series of operations. For example $\lbrace 10,10,10,11 \rbrace$ represent operations for $\lbrace 4,1\rbrace$(invalid, however). Then we compress the same operations in a operation set as the number of this operation occurs. For example, $\lbrace 10,10,10,11 \rbrace$ can be compressed as $\lbrace 3,1 \rbrace$ as there's three $10$ and one $11$. Note we do not care whether the operation is, we only care how many times it occurs. Now, as we construct the answer column by column, new numbers will be added. A new number can split some elements in the compress set. For example, we add a new $1$ in $\lbrace 4,1 \rbrace$ as it becomes $\lbrace 4,1,1 \rbrace$. We can turn the operation set $\lbrace 10,10,10,11 \rbrace$ into $\lbrace 100,100,101,11 \rbrace$, while the compress set turns $\lbrace 2,1,1 \rbrace$ from $\lbrace 3,1 \rbrace$. In general, we can turn $\lbrace X \rbrace$ into $\lbrace Y , X - Y \rbrace$ uses a number $X(1 \leq Y < X)$. Special condition: $\lbrace Y \rbrace$ can keep same but use number $Y$. Special judge for $A_{1} = 1$, thus we use one operation to erase all numbers. Obviously the first compress set is $\lbrace A_{1} \rbrace$, represent operation set $\lbrace 1,1,1,1, \dots ,1 \rbrace$. If $A_{1} = A_{2}$, turn the second compress set as $\lbrace 1,A_{1} - 1,1 \rbrace$, otherwise turn it as $\lbrace A_{2} , A_{1} - A_{2} \rbrace$. Then we maintain the compress set by keeping the sum of the elements same but the number of the elements strictly increasing. For a current compress set, let $X$ be the minimal element, and $Y$ be the new number added. If $Y < X$, split $X$ into $\lbrace Y , X - Y \rbrace$. Otherwise split $X$ into $\lbrace 1 , X - 1 \rbrace$, the left number $(Y-X+1)$ can be randomly placed. The left number can be randomly placed if and if only the sum of the elements is larger then $Y$. Obviously the sum of the elements equals to $A_{1}$ or $A_{1} + 1$. If the sum of the elements equals to $A_{1}$, then $Y \leq A_{2} < A_{1}$. After all split operations, the compress set must be $\lbrace 1,1,1 \dots ,1 \rbrace$, which means all operation differ from each other. We can construct the final answer now in $O(n^2)$ .
[ "constructive algorithms" ]
2,600
null
1228
A
Distinct Digits
You have two integers $l$ and $r$. Find an integer $x$ which satisfies the conditions below: - $l \le x \le r$. - All digits of $x$ are different. If there are multiple answers, print any of them.
Let's see how to check if all digits of $x$ are different. Since there can be only $10$ different numbers($0$ to $9$) in single digit, you can count the occurrences of $10$ numbers by looking all digits of $x$. You can count all digits by using modulo $10$ or changing whole number to string. For example, if $x = 1217$, then occurrence of each number will be $[0, 2, 1, 0, 0, 0, 0, 1, 0, 0]$, because there are two $1$s, single $2$ and single $7$ in $x$. So $1217$ is invalid number. Now do the same thing for all $x$ where $l \le x \le r$. If you find any valid number then print it. Otherwise print $-1$. Time complexity is $O((r-l) \log r)$.
[ "brute force", "implementation" ]
800
# Return if given number's digits are distinct. def is_distinct(x): return len(set(str(x))) == len(str(x)) L, R = [int(c) for c in input().split()] found = False for i in range(L, R+1): if is_distinct(i): found = True print(i) break if not found: print(-1)
1228
B
Filling the Grid
Suppose there is a $h \times w$ grid consisting of empty or full cells. Let's make some definitions: - $r_{i}$ is the number of consecutive full cells connected to the left side in the $i$-th row ($1 \le i \le h$). In particular, $r_i=0$ if the leftmost cell of the $i$-th row is empty. - $c_{j}$ is the number of consecutive full cells connected to the top end in the $j$-th column ($1 \le j \le w$). In particular, $c_j=0$ if the topmost cell of the $j$-th column is empty. In other words, the $i$-th row starts exactly with $r_i$ full cells. Similarly, the $j$-th column starts exactly with $c_j$ full cells. \begin{center} {\small These are the $r$ and $c$ values of some $3 \times 4$ grid. Black cells are full and white cells are empty.} \end{center} You have values of $r$ and $c$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $r$ and $c$. Since the answer can be very large, find the answer modulo $1000000007\,(10^{9} + 7)$. In other words, find the remainder after division of the answer by $1000000007\,(10^{9} + 7)$.
You can see some observations below; $r$ and $c$ values reserves some cells to be full, and some cells to be empty. Because they have to satisfy number of consecutive full cells in their row/column. If some cell is reserved to be full by some values and reserved to be empty by some other values, then it is impossible to fill grid. Let's call this kind of cell as invalid cell. If there is no invalid cell, then the answer is $2^{unreserved}$ where $unreserved$ means the number of unreserved cells, because setting state of unreserved cells doesn't affect validity of grid. For easier understanding, please look at the pictures below. Black cells are reserved to be full by some $r$ or $c$ value. White X cells are reserved to be empty by some $r$ or $c$ value. White ? cells are unreserved cells. Red X cells are invalid cells. This is the explanation of the first example. There is $1$ unreserved cell, so the answer is $2$. This is one of the impossible cases. That red X cell is reserved to be full by $r_{3}$, but reserved to be empty by $c_{2}$. So this is impossible. Time complexity is $O(wh)$.
[ "implementation", "math" ]
1,400
# Get input h, w = [int(z) for z in input().split()] r = [int(z) for z in input().split()] c = [int(z) for z in input().split()] mod = 10**9 + 7 # Make grid grid = [['?' for col in range(w+1)] for row in range(h+1)] def try_set(row, col, target): if grid[row][col] == '?': grid[row][col] = target elif grid[row][col] != target: raise ValueError def go(): try: for row in range(h): for col in range(r[row]): try_set(row, col, 'FULL') try_set(row, r[row], 'EMPTY') for col in range(w): for row in range(c[col]): try_set(row, col, 'FULL') try_set(c[col], col, 'EMPTY') except ValueError: return 0 answer = 1 for row in range(h): for col in range(w): if grid[row][col] == '?': answer = answer * 2 % mod return answer print(go())
1228
C
Primes and Multiplication
Let's introduce some definitions that will be needed later. Let $prime(x)$ be the set of prime divisors of $x$. For example, $prime(140) = \{ 2, 5, 7 \}$, $prime(169) = \{ 13 \}$. Let $g(x, p)$ be the maximum possible integer $p^k$ where $k$ is an integer such that $x$ is divisible by $p^k$. For example: - $g(45, 3) = 9$ ($45$ is divisible by $3^2=9$ but not divisible by $3^3=27$), - $g(63, 7) = 7$ ($63$ is divisible by $7^1=7$ but not divisible by $7^2=49$). Let $f(x, y)$ be the product of $g(y, p)$ for all $p$ in $prime(x)$. For example: - $f(30, 70) = g(70, 2) \cdot g(70, 3) \cdot g(70, 5) = 2^1 \cdot 3^0 \cdot 5^1 = 10$, - $f(525, 63) = g(63, 3) \cdot g(63, 5) \cdot g(63, 7) = 3^2 \cdot 5^0 \cdot 7^1 = 63$. You have integers $x$ and $n$. Calculate $f(x, 1) \cdot f(x, 2) \cdot \ldots \cdot f(x, n) \bmod{(10^{9} + 7)}$.
Let's say $h(x, p) = \log_{p} g(x, p)$, then $h(x, p) + h(y, p) = h(x y, p)$. Because if we describe $x = p^{h(x, p)} q_{x}$ and $y = p^{h(y, p)} q_{y}$, then $x y = p^{h(x, p) + h(y, p)} q_{x} q_{y}$. Now let's go to the main step; $\begin{aligned} \prod_{i=1}^{n} f(x, i) &= \prod_{i=1}^{n} \prod_{p \in prime(x)} g(i, p) \\ &= \prod_{i=1}^{n} \prod_{p \in prime(x)} p^{h(i,p)} \\ &= \prod_{p \in prime(x)} \prod_{i=1}^{n} p^{h(i,p)} \\ &= \prod_{p \in prime(x)} p^{\sum_{i=1}^{n} h(i, p)} \\ &= \prod_{p \in prime(x)} p^{h(n!, p)} \end{aligned}$ So we have to count $h(n!, p)$ for each $p$ in $prime(x)$, and calculate exponents. You can count $h(n!, p)$ by following formula; $h(n!, p) = \sum_{k=1}^{\infty} \Bigl \lfloor \frac{n}{p^k} \Bigr \rfloor$ Fortunately, since $h(n!, p)$ never exceeds $n$, we don't have to apply Euler's theorem here. You just have to be careful about overflow issue. Roughly calculated time complexity is $O( \sqrt{x} + \log \log x \cdot \log n)$, because you use $O(\sqrt{x})$ to get prime divisors of $x$, and the number of distinct prime divisors of $x$ is approximately $\log \log x$.
[ "math", "number theory" ]
1,700
# Prime factorization def prime_factorization(x): answer = [] i = 2 while i*i <= x: if x%i == 0: answer.append(i) while x%i == 0: x //= i i += 1 if x > 1: answer.append(x) return answer # Main def main(X: int, N: int): answer = 1 mod = 10**9 + 7 x_primes = prime_factorization(x) for prime in x_primes: power = 0 factor = prime while factor <= N: power += N // factor factor *= prime answer *= pow(prime, power, mod) answer %= mod return answer x, n = [int(c) for c in input().split()] print(main(x, n))
1228
D
Complete Tripartite
You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected. Let's make a definition. Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied: - There are no edges with both endpoints in vertex set $v_1$. - There are no edges with both endpoints in vertex set $v_2$. - For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$. Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below; - All vertex sets should not be empty. - Each vertex should be assigned to only one vertex set. - $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true. Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
You can make answer by following these steps; If two vertices $u_{1}$ and $u_{2}$ are in same vertex set, there should be no edge between them. Otherwise, there should be edge between them. If you choose any $u$ as first vertex of specific vertex set, then you can simply add all vertices which are not directly connected to $u$ in that vertex set. Make $3$ vertex sets by doing second step multiple times. If you can't make $3$ sets or there is any vertex which is not in any vertex set, then answer is impossible. If $m \ne \lvert v_{1} \rvert \cdot \lvert v_{2} \rvert + \lvert v_{2} \rvert \cdot \lvert v_{3} \rvert + \lvert v_{3} \rvert \cdot \lvert v_{1} \rvert$, then answer is impossible. $\lvert v_{i} \rvert$ means size of $i$-th vertex set. For all vertices $u_{1}$ and $u_{2}$ from different vertex sets, if there is no direct connection between $u_{1}$ and $u_{2}$, then answer is impossible. If you validated all steps, then current vertex set assignment is answer. Make sure you are doing all steps. If you forget any of these steps, your solution will print wrong answer. Time complexity is $O((n+m) \log n)$.
[ "brute force", "constructive algorithms", "graphs", "hashing", "implementation" ]
1,900
// Standard libraries #include <stdio.h> #include <vector> #include <set> // Main int main(int argc, char **argv){ #ifdef __McDic__ // Local testing I/O freopen("VScode/IO/input.txt", "r", stdin); freopen("VScode/IO/output.txt", "w", stdout); #endif // Get input int v, e; scanf("%d %d", &v, &e); std::vector<std::set<int>> edges(v+1); for(int i=0; i<e; i++){ int e[2]; scanf("%d %d", e, e+1); edges[e[0]].insert(e[1]); edges[e[1]].insert(e[0]); } // Assign groups std::vector<int> group(v+1, -1); for(int g = 0; g < 3; g++){ // Find first point of group int first; for(first=1; first<=v; first++) if(group[first] == -1) break; if(first == v+1){ printf("-1\n"); return 0;} // All are in some group // Group settings group[first] = g; for(int second = 1; second <= v; second++) if(first != second && group[second] == -1 && edges[first].find(second) == edges[first].end()) group[second] = g; } // All vertices should be in some group std::vector<std::vector<int>> groups(3); for(int now=1; now<=v; now++){ if(group[now] == -1){ printf("-1\n"); return 0;} // Non grouped vertex exist else groups[group[now]].push_back(now); } // Edge counting int found_edges = 0; for(int g1=0; g1<3; g1++){ for(int g2=g1+1; g2<3; g2++){ for(int v1: groups[g1]) for(int v2: groups[g2]){ if(edges[v1].find(v2) == edges[v1].end()){ printf("-1\n"); return 0;} // Non complete bipartite else found_edges++; } } } // Edge validation if(found_edges != e){ printf("-1\n"); return 0;} // Remaining edges detected for(int now=1; now<=v; now++) printf("%d ", group[now] + 1); // OK!! return 0; }
1228
E
Another Filling the Grid
You have $n \times n$ square grid and an integer $k$. Put an integer in each cell while satisfying the conditions below. - All numbers in the grid should be between $1$ and $k$ inclusive. - Minimum number of the $i$-th row is $1$ ($1 \le i \le n$). - Minimum number of the $j$-th column is $1$ ($1 \le j \le n$). Find the number of ways to put integers in the grid. Since the answer can be very large, find the answer modulo $(10^{9} + 7)$. \begin{center} These are the examples of valid and invalid grid when $n=k=2$. \end{center}
$O(n^{3})$ solution:Let $f(r, c)$ to be the number of filling grids of $r$ rows, $c$ incomplete columns, and $n-c$ complete columns. Incomplete columns means which doesn't contain $1$ in already filled part, and complete columns means opposite. Now you can see that the formula can be described as below; $f(r, 0) = (k^{n} - (k-1)^{n})^{r}$ ($1 \le r$), because we don't have to care about minimum value of columns. However, there should be at least one cell which has $1$. $f(1, c) = k^{n-c}$ ($1 \le c$), because we have to fill $1$ in all incomplete columns in that row. But, other cells are free. $f(r, c) = (k^{n-c} - (k-1)^{n-c}) \cdot (k-1)^{c} \cdot f(r-1, c) + k^{n-c} \cdot \sum_{c_{0}=1}^{c} \binom{c}{c_{0}} \cdot (k-1)^{c-c0} \cdot f(r-1, c-c_{0})$ ($2 \le r$, $1 \le c$). Each part means number of cases when you select $c_{0}$ incomplete columns to be complete column in this row. The answer is $f(n, n)$. Let $f(r, c)$ to be the number of filling grids of $r$ rows, $c$ incomplete columns, and $n-c$ complete columns. Incomplete columns means which doesn't contain $1$ in already filled part, and complete columns means opposite. Now you can see that the formula can be described as below; $f(r, 0) = (k^{n} - (k-1)^{n})^{r}$ ($1 \le r$), because we don't have to care about minimum value of columns. However, there should be at least one cell which has $1$. $f(1, c) = k^{n-c}$ ($1 \le c$), because we have to fill $1$ in all incomplete columns in that row. But, other cells are free. $f(r, c) = (k^{n-c} - (k-1)^{n-c}) \cdot (k-1)^{c} \cdot f(r-1, c) + k^{n-c} \cdot \sum_{c_{0}=1}^{c} \binom{c}{c_{0}} \cdot (k-1)^{c-c0} \cdot f(r-1, c-c_{0})$ ($2 \le r$, $1 \le c$). Each part means number of cases when you select $c_{0}$ incomplete columns to be complete column in this row. The answer is $f(n, n)$. $O(n^{2})$ and $O(n \log n)$ solution:Let $R[i]$ be the restriction of the i-th row having some value <= 1 and $C[i]$ the same but for columns. We want $\bigcap^n_{i=1}R[i] \cap C[i]$. Negate that expression twice, and we'll get $U - \bigcup^n_{i=1}\neg R[i] \cup \neg C[i]$. Using inclusion-exclusion this is: $\sum_{i=0}^{n} \sum_{j=0}^{n} (-1)^{i+j} \cdot {n\choose j} \cdot {n\choose i} \cdot k^{n^2 - n \cdot (i+j) + i \cdot j} \cdot (k-1)^{n \cdot (i+j) - i \cdot j}$ This is enough for $O(n^{2} \log n)$ with fast exponentiation or $O(n^{2})$ precomputing the needed powers. To get $O(n \log n)$ note that we the second sum is a binomial expansion so the answer can be simplified to: $\sum_{i=0}^{n} (-1)^i \cdot {n\choose i} \cdot (k^{n-i} \cdot (k-1)^{i} - (k-1)^{n})^n$ Let $R[i]$ be the restriction of the i-th row having some value <= 1 and $C[i]$ the same but for columns. We want $\bigcap^n_{i=1}R[i] \cap C[i]$. Negate that expression twice, and we'll get $U - \bigcup^n_{i=1}\neg R[i] \cup \neg C[i]$. Using inclusion-exclusion this is: $\sum_{i=0}^{n} \sum_{j=0}^{n} (-1)^{i+j} \cdot {n\choose j} \cdot {n\choose i} \cdot k^{n^2 - n \cdot (i+j) + i \cdot j} \cdot (k-1)^{n \cdot (i+j) - i \cdot j}$ This is enough for $O(n^{2} \log n)$ with fast exponentiation or $O(n^{2})$ precomputing the needed powers. To get $O(n \log n)$ note that we the second sum is a binomial expansion so the answer can be simplified to: $\sum_{i=0}^{n} (-1)^i \cdot {n\choose i} \cdot (k^{n-i} \cdot (k-1)^{i} - (k-1)^{n})^n$
[ "combinatorics", "dp", "math" ]
2,300
// Standard libraries #include <stdio.h> #include <vector> // Typedef typedef long long int lld; const lld mod = 1000 * 1000 * 1000 + 7; // Clean lld clean(lld x){ x %= mod; if(x<0) x += mod; return x; } // x^n lld power(lld x, lld n){ if(n==0) return 1; x = clean(x); lld half = power(x, n/2); if(n%2 == 0) return half*half%mod; else return half*half%mod*x%mod; } int main(int argc, char **argv){ #ifdef __McDic__ // Local testing I/O freopen("VScode/IO/input.txt", "r", stdin); freopen("VScode/IO/output.txt", "w", stdout); #endif // Get input lld n, k; scanf("%lld %lld", &n, &k); std::vector<std::vector<lld>> f(n+1, std::vector<lld>(n+1, -1)); // Answer if(k==1){printf("1\n"); return 0;} // edge case // nCr combination std::vector<std::vector<lld>> nCr(n+1, std::vector<lld>(n+1, -1)); for(int front=0; front<=n; front++){ nCr[front][0] = 1, nCr[front][front] = 1; for(int back=1; back<front; back++) nCr[front][back] = (nCr[front-1][back-1] + nCr[front-1][back]) % mod; } std::vector<lld> kpower = {1}, k1power = {1}; for(int i=1; i<=n; i++){ kpower.push_back(kpower.back() * k % mod); k1power.push_back(k1power.back() * (k-1) % mod); } // f(r, 0) = (k^n - (k-1)^n)^r for(int r=1; r<=n; r++) f[r][0] = clean(power(power(k, n) - power(k-1, n), r)); // f(1, c) = k^(n-c) (c>=1) for(int c=1; c<=n; c++) f[1][c] = power(k, n-c); // f(r, c) = (k^(n-c) - (k-1)^(n-c)) f(r-1, c) + for_{c0} k^(n-c) [c]C[c0] f(r-1, c-c0) for(int r=2; r<=n; r++) for(int c=1; c<=n; c++){ //if(c==n) f[r][c] = 0; //else f[r][c] = clean(power(k, n-c) - power(k-1, n-c)) * power(k-1, c) % mod * f[r-1][c] % mod; f[r][c] = clean(kpower[n-c] - k1power[n-c]) * k1power[c] % mod * f[r-1][c] % mod; for(int c0=1; c0<=c; c0++){ //f[r][c] += power(k-1, c-c0) * power(k, n-c) % mod * nCr[c][c0] % mod * f[r-1][c-c0] % mod; f[r][c] += k1power[c-c0] * kpower[n-c] % mod * nCr[c][c0] % mod * f[r-1][c-c0] % mod; f[r][c] %= mod; } } printf("%lld\n", f[n][n]); return 0; }
1228
F
One Node is Gone
You have an integer $n$. Let's define following tree generation as McDic's generation: - Make a complete and full binary tree of $2^{n} - 1$ vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. - Select a non-root vertex $v$ from that binary tree. - Remove $v$ from tree and make new edges between $v$'s parent and $v$'s direct children. If $v$ has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree.
Let me suggest this observation; Root of generated tree should be one of middle of diameter. Because only $1$ node is deleted from complete full binary tree. So there are $3$ valid cases; The removed node is child of root. In this case, there are $2$ answers($2$ center nodes), diameter is decreased by $1$ (odd), and tree looks like two complete full binary trees' roots are connected. You have to check if two center's subtrees are complete full binary tree. In this case, there are $2$ answers, which are $2$ centers of diameter. In this case, there are $2$ answers, which are $2$ centers of diameter. The removed node is leaf($n \gt 2$) or normal node. In this case, there is only $1$ answer and $1$ root node. Check if whole tree is complete full binary tree with $1$ node error toleration. You can do case-handling by degree of nodes. If non-root has degree $3$, then this node is normal. If non-root has degree $2$ (error), then this node should be parent of removed leaf. You should check if this node's child node is leaf. If non-root has degree $1$, then this node should be leaf. If non-root has degree $4$ (error), then this node should be parent of removed normal node. This is the hardest case. I did this by checking depth of each child's subtree using DFS, then consider each tree to be complete and binary tree with no error, but with different depths. If you encountered multiple error nodes, then this tree is invalid. To check my exact approach, please look at my code. In these cases, we can fix the center of whole tree by center of diameter. If non-root has degree $3$, then this node is normal. If non-root has degree $2$ (error), then this node should be parent of removed leaf. You should check if this node's child node is leaf. If non-root has degree $1$, then this node should be leaf. If non-root has degree $4$ (error), then this node should be parent of removed normal node. This is the hardest case. I did this by checking depth of each child's subtree using DFS, then consider each tree to be complete and binary tree with no error, but with different depths. If you encountered multiple error nodes, then this tree is invalid. To check my exact approach, please look at my code. In these cases, we can fix the center of whole tree by center of diameter. To check if specific subtree is complete and full binary tree, you can use top-down recursive approach. Maybe you can use bottom-up approach by collapsing leaf nodes too, but it's very hard(at least I think) to check all conditions strictly. Time complexity is $O(2^{n})$. But you can solve this in like $O(n \cdot 2^{n})$ or something bigger one.
[ "constructive algorithms", "implementation", "trees" ]
2,500
// Standard libraries #include <stdio.h> #include <vector> #include <utility> // Max2 int max2(int a, int b){return a>b ? a:b;} // Graph attributes int v; std::vector<std::vector<int>> edges; // DFS from given vertex with avoidance. Return [(previous, distance), ...] std::vector<std::pair<int, int>> DFS(int start, std::vector<int> avoidance = {}){ // Answer //printf("DFS start = %d, avoiding %d vertices\n", start, avoidance.size()); std::vector<std::pair<int, int>> result(v+1, {-1, -1}); // Avoidance settings std::vector<bool> avoidance_bool(v+1, false); // Avoidance converted to boolean array for(int avoided: avoidance) avoidance_bool[avoided] = true; if(avoidance_bool[start]) throw "undefined"; // If start is included in avoidance then raise // DFS with stack std::vector<int> stack_previous = {-1}, stack_now = {start}; result[start] = {-1, 0}; while(!stack_now.empty()){ int prev = stack_previous.back(); stack_previous.pop_back(); int now = stack_now.back(); stack_now.pop_back(); //printf("- Looking now = %d, prev = %d\n", now, prev); fflush(stdout); for(int next: edges[now]) if(prev != next && !avoidance_bool[next]){ // Visit only if visitable result[next] = {now, result[now].second + 1}; stack_previous.push_back(now); stack_now.push_back(next); } } return result; } // Find path [start, .., end]. If precomputed DFS(base on goal) is given, then don't do DFS process again. std::vector<int> path(int start, int goal, std::vector<std::pair<int, int>> dfs_result = {}){ if(dfs_result.empty()) dfs_result = DFS(goal); // this represents goal->... std::vector<int> answer; for(int now = start; now != goal; now = dfs_result[now].first) answer.push_back(now); answer.push_back(goal); return answer; } // Return diameter. std::vector<int> diameter_path(){ int max_dist = -1, diameter_first = -1, diameter_second = -1; std::vector<std::pair<int, int>> DFSresult1 = DFS(1); for(int i=1; i<=v; i++) if(max_dist < DFSresult1[i].second) max_dist = DFSresult1[i].second, diameter_first = i; std::vector<std::pair<int, int>> DFSresult2 = DFS(diameter_first); max_dist = -1; for(int i=1; i<=v; i++) if(max_dist < DFSresult2[i].second) max_dist = DFSresult2[i].second, diameter_second = i; return path(diameter_second, diameter_first, DFSresult2); } // Validate tree: prev->now->... with level. // If errored is -1, then it can tolerate error only once. void treeValidation(int now, int prev, int level, int &errored, bool &globalValidationStatus){ if(!globalValidationStatus) return; // If global validation failed then do nothing std::vector<int> childs; // Child nodes of now for(int next: edges[now]) if(next != prev) childs.push_back(next); //printf("Tree validation: now = %2d, prev = %2d, level = %2d, %2d child nodes, errored %2d\n", // now, prev, level, childs.size(), errored); fflush(stdout); if(level == 0){ // now should be leaf if(!childs.empty()) globalValidationStatus = false; return; } else if(childs.size() == 2){ // This node has no errors treeValidation(childs[0], now, level-1, errored, globalValidationStatus); treeValidation(childs[1], now, level-1, errored, globalValidationStatus); return; } else if(childs.size() == 1){ // Error: But this might be parent of removed leaf. if(errored != -1 || level != 1){ // Error can't be tolerated, or this node can't be parent of removed leaf globalValidationStatus = false; return; } errored = now; // Mark this vertex as errored treeValidation(childs[0], now, level-1, errored, globalValidationStatus); return; } else if(childs.size() == 3){ // Error: But this might be a parent of removed normal node. if(errored != -1 || level < 2){ // Error can't be tolerated, or this node can't be parent of removed normal node globalValidationStatus = false; return; } errored = now; // Mark this vertex as errored int maxdegree[3] = {-1, -1, -1}; // Find max degree of each subtree, then go further for(int i=0; i<3; i++){ std::vector<std::pair<int, int>> DFSresult = DFS(childs[i], {now}); for(int j=1; j<=v; j++) maxdegree[i] = max2(maxdegree[i], DFSresult[j].second); } for(int i=0; i<3; i++) if(maxdegree[i] == level-1){ // Validation on subtrees treeValidation(childs[i], now, level-1, errored, globalValidationStatus); for(int j=0; j<3; j++) if(i != j) // Others are one-step smaller treeValidation(childs[j], now, level-2, errored, globalValidationStatus); return; } globalValidationStatus = false; // No validation proceeded } else globalValidationStatus = false; // Undefined error: Non-toleratable } // Main int main(int argc, char **argv){ #ifdef __McDic__ // Local testing I/O freopen("VScode/IO/input.txt", "r", stdin); freopen("VScode/IO/output.txt", "w", stdout); #endif // Get input int n; scanf("%d", &n); v = (1<<n) - 2; edges.resize(v+1); for(int i=0; i<v-1; i++){ int start, end; scanf("%d %d", &start, &end); edges[start].push_back(end); edges[end].push_back(start); } // Get diameter and go validation std::vector<int> diameter = diameter_path(); int diameter_size = diameter.size(); bool validationStatus = true; if(diameter_size % 2 == 1){ // Found root; Single validation with tolerating single error int root = diameter[diameter_size / 2], errored = -1; treeValidation(root, -1, n-1, errored, validationStatus); if(validationStatus) for(int i=1; i<=v; i++) // At most 1 strange vertex if(edges[i].size() != 1 && edges[i].size() != 3 && i != root){ printf("1\n%d\n", i); return 0; } //printf("errored = %d\n", errored); } else{ // Dual validation with tolerating no error int c1 = diameter[diameter_size / 2], c2 = diameter[diameter_size / 2 - 1], errored = -2; treeValidation(c1, c2, n-2, errored, validationStatus); treeValidation(c2, c1, n-2, errored, validationStatus); if(validationStatus){ if(c1 > c2) std::swap(c1, c2); printf("2\n%d %d\n", c1, c2); return 0; } } printf("0\n"); // Invalid tree return 0; }
1230
A
Dawid and Bags of Candies
Dawid has four bags of candies. The $i$-th of them contains $a_i$ candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends.
Let's firstly sort all the bags in non-decreasing order of capacities. As the order of friends doesn't matter, it turns out that one of them should take only the biggest bag or the biggest and the smallest bag. It's easy to check if any of these possibilities works.
[ "brute force", "implementation" ]
800
null
1230
B
Ania and Minimizing
Ania has a large integer $S$. Its decimal representation has length $n$ and doesn't contain any leading zeroes. Ania is allowed to change at most $k$ digits of $S$. She wants to do it in such a way that $S$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
There are a couple of corner cases: if $k=0$, we cannot change $S$. Otherwise, if $n=1$, we can change $S$ into $0$. Now assume that $n \geq 2$ and $k \geq 1$. A simple greedy approach works here: we can iterate over the digits from left to right and change them to the lowest possible digits as long as we still can change anything. The leftmost digit can be only changed to $1$, and all the remaining digits should be changed to $0$. We need to remember not to fix the digits that are currently the lowest possible. For instance, if $k=4$, the number $S=450456450$ will be changed to $\color{blue}{\bf 10}0\color{blue}{\bf00}6450$ (the modified digits are marked blue). The algorithm can be easily implemented in $O(n)$ time.
[ "greedy", "implementation" ]
1,000
null
1234
A
Equalize Prices Again
You are both a shop keeper and a shop assistant at a small nearby shop. You have $n$ goods, the $i$-th good costs $a_i$ coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $n$ goods you have. However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $n$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices. On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one. So you need to find the minimum possible equal price of all $n$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices. You have to answer $q$ independent queries.
In this problem, we need to find the minimum possible $price$ such that $price \cdot n \ge sum$, where $sum$ is the sum of all $a_i$. $price$ equals to $\lceil \frac{sum}{n} \rceil$, where $\lceil \frac{x}{y} \rceil$ is $x$ divided by $y$ rounded up.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; int sum = 0; for (int j = 0; j < n; ++j) { int x; cin >> x; sum += x; } cout << (sum + n - 1) / n << endl; } return 0; }
1234
B1
Social Network (easy version)
\textbf{The only difference between easy and hard versions are constraints on $n$ and $k$}. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \le id_i \le 10^9$). If you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with $id_i$ on the screen): - Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen. - Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen. - The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.
The solution to this problem is just the implementation of what is written in the problem statement. Let's carry the array $q$ which shows the current smartphone screen. When we receive the new message from the friend with ID $id_i$, let's do the following sequence of moves: Firstly, let's try to find him on the screen. If he is found, just do nothing and continue. Otherwise, let's check if the current number of conversations is $k$. If it is so then let's remove the last conversation. Now the number of conversations is less than $k$ and the current friend is not shown on the screen. Let's insert him into the first position. After processing all $n$ messages the answer is just the array $q$.
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> ids; for (int i = 0; i < n; ++i) { int id; cin >> id; if (find(ids.begin(), ids.end(), id) == ids.end()) { if (int(ids.size()) >= k) ids.pop_back(); ids.insert(ids.begin(), id); } } cout << ids.size() << endl; for (auto it : ids) cout << it << " "; cout << endl; return 0; }
1234
B2
Social Network (hard version)
\textbf{The only difference between easy and hard versions are constraints on $n$ and $k$}. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \le id_i \le 10^9$). If you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with $id_i$ on the screen): - Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen. - Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen. - The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.
The idea of this solution is the same as in the easy version, but now we need to do the same sequence of moves faster. We can notice that the smartphone screen works as a queue, so let store it as a queue! When the new message appears, we have to check if the friend with this ID is in the queue already, but we need to check it somehow fast. Let's use some logarithmic structure that stores the same information as the queue but in other order to find, add and remove elements fast. In C++ this structure is std::set. So let's check if the current friend is in the queue, and if no, let's check if the size of the queue is $k$. If it is so then let's remove the first element of the queue from it and the same element from the set also. Then add the current friend to the queue and to the set. After processing all messages, the reversed queue (the queue from tail to head) is the answer to the problem. Time complexity: $O(n \log{k})$. And don't forget that std::unordered_map and other standard hashmaps can work in linear time in the worst case, so you need to redefine the hash function to use them. You can read more about this issue here: https://codeforces.com/blog/entry/62393.
[ "data structures", "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; queue<int> q; set<int> vals; for (int i = 0; i < n; ++i) { int id; cin >> id; if (!vals.count(id)) { if (int(q.size()) >= k) { int cur = q.front(); q.pop(); vals.erase(cur); } vals.insert(id); q.push(id); } } vector<int> res; while (!q.empty()) { res.push_back(q.front()); q.pop(); } reverse(res.begin(), res.end()); cout << res.size() << endl; for (auto it : res) cout << it << " "; cout << endl; return 0; }
1234
C
Pipes
You are given a system of pipes. It consists of two rows, each row consists of $n$ pipes. The top left pipe has the coordinates $(1, 1)$ and the bottom right — $(2, n)$. There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types: \begin{center} Types of pipes \end{center} You can turn each of the given pipes $90$ degrees clockwise or counterclockwise \textbf{arbitrary (possibly, zero) number of times} (so the types $1$ and $2$ can become each other and types $3, 4, 5, 6$ can become each other). You want to turn some pipes in a way that the water flow can start at $(1, 0)$ (to the left of the top left pipe), move to the pipe at $(1, 1)$, flow somehow by \textbf{connected pipes} to the pipe at $(2, n)$ and flow right to $(2, n + 1)$. Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes: \begin{center} Examples of connected pipes \end{center} Let's describe the problem using some example: \begin{center} The first example input \end{center} And its solution is below: \begin{center} The first example answer \end{center} As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $(1, 2)$ $90$ degrees clockwise, the pipe at $(2, 3)$ $90$ degrees, the pipe at $(1, 6)$ $90$ degrees, the pipe at $(1, 7)$ $180$ degrees and the pipe at $(2, 7)$ $180$ degrees. Then the flow of water can reach $(2, n + 1)$ from $(1, 0)$. You have to answer $q$ independent queries.
Let's see how the water can flow when it meets the pipe of type $1$ or $2$ and in the other case. When the water meets the pipe of type $1$ or $2$ we cannot do anything but let it flow to the right of the current cell. Otherwise (if the current pipe is curved) then there are two cases: if the pipe on the same position but in the other row is not curved then the answer is "NO" because the water has to change the row but we cannot turn the next pipe to allow it to move to the right or to the left. So, the current pipe is curved and the pipe on the same position in the other row is also curved, let's change the row and move to the right (it is obvious that we never need to move to the left). So, the answer (and the sequence of pipes) is uniquely defined by types of pipes. If after iterating over all $n$ positions we didn't meet the case of "NO" and the current row is second, then the answer is "YES".
[ "dp", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; string s[2]; cin >> n >> s[0] >> s[1]; int row = 0; int pos = 0; for (pos = 0; pos < n; ++pos) { if (s[row][pos] >= '3') { if (s[row ^ 1][pos] < '3') { break; } else { row ^= 1; } } } if (pos == n && row == 1) { cout << "YES" << endl; } else { cout << "NO" << endl; } } return 0; }
1234
D
Distinct Characters Queries
You are given a string $s$ consisting of lowercase Latin letters and $q$ queries for this string. Recall that the substring $s[l; r]$ of the string $s$ is the string $s_l s_{l + 1} \dots s_r$. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top". There are two types of queries: - $1~ pos~ c$ ($1 \le pos \le |s|$, $c$ is lowercase Latin letter): replace $s_{pos}$ with $c$ (set $s_{pos} := c$); - $2~ l~ r$ ($1 \le l \le r \le |s|$): calculate the number of distinct characters in the substring $s[l; r]$.
Let's store for each letter all positions in which it appears in some data structure. We need such a data structure that can add, remove and find the next element greater than or equal to our element, fast enough. Suddenly, this data structure is std::set again (in C++). When we meet the first type query, let's just modify two elements of corresponding sets (one remove, one add). When we meet the second type query, let's iterate over all letters. If the current letter is in the segment $[l; r]$ then the first element greater than or equal to $l$ in the corresponding set should exist and be less than or equal to $r$. If it is so, let's increase the answer by one. After iterating over all letters just print the answer. Time complexity: $O(n \log{n} AL)$, when $AL$ is the size of the alphabet.
[ "data structures" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif string s; cin >> s; vector<set<int>> poss(26); for (int i = 0; i < int(s.size()); ++i) { poss[s[i] - 'a'].insert(i); } int q; cin >> q; for (int i = 0; i < q; ++i) { int tp; cin >> tp; if (tp == 1) { int pos; char c; cin >> pos >> c; --pos; poss[s[pos] - 'a'].erase(pos); s[pos] = c; poss[s[pos] - 'a'].insert(pos); } else { int l, r; cin >> l >> r; --l, --r; int cnt = 0; for (int c = 0; c < 26; ++c) { auto it = poss[c].lower_bound(l); if (it != poss[c].end() && *it <= r) ++cnt; } cout << cnt << endl; } } return 0; }
1234
E
Special Permutations
Let's define $p_i(n)$ as the following permutation: $[i, 1, 2, \dots, i - 1, i + 1, \dots, n]$. This means that the $i$-th permutation is \textbf{almost identity} (i.e. which maps every element to itself) permutation but the element $i$ is on the first position. Examples: - $p_1(4) = [1, 2, 3, 4]$; - $p_2(4) = [2, 1, 3, 4]$; - $p_3(4) = [3, 1, 2, 4]$; - $p_4(4) = [4, 1, 2, 3]$. You are given an array $x_1, x_2, \dots, x_m$ ($1 \le x_i \le n$). Let $pos(p, val)$ be the position of the element $val$ in $p$. So, $pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1$. Let's define a function $f(p) = \sum\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|$, where $|val|$ is the absolute value of $val$. This function means the sum of distances between adjacent elements of $x$ in $p$. Your task is to calculate $f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$.
Let's calculate the answer for the first permutation $p_1(n)$ naively in $O(m)$. Then let's recalculate the answer somehow and then maybe prove that it works in linear time. Which summands will change when we try to recalculate the function $f(p_i(n))$ using $f(p_1(n))$? First of all, let's notice that each pair of adjacent elements of $x$ is the segment on the permutation. To calculate $f(p_i(n))$ fast, let's firstly notice that all segments that cover the element $i$ (but $i$ is not their endpoint) will change their length by minus one after placing $i$ at the first position (because $i$ will be removed from all such segments). This part can be calculated in $O(n + m)$. Let's use the standard trick with prefix sums and segments. Let $cnt$ be the array of length $n$. For each pair of adjacent elements $x_j$ and $x_{j+1}$ for all $j$ from $1$ to $m-1$ let's do the following sequence of moves: if $|x_j - x_{j + 1}| < 2$ then there are no points that covered by this segment not being its endpoints, so let's just skip this segment. Otherwise let's increase the value of $cnt[min(x_j, x_{j+1}) + 1]$ by one and decrease the value of $cnt[max(x_j, x_{j + 1})]$ by one. After this, let's build prefix sums on this array (make $cnt[i + 1] := cnt[i + 1] + cnt[i]$ for all $i$ from $1$ to $n-1$). And now $cnt_i$ equals to the number of segments covering the element $i$. The second part that will change is such segments that $i$ is their endpoint. Let's store the array of arrays $adj$ of length $n$ and $adj[i]$ will store all elements adjacent to $i$ in the array $x$ for all $i$ from $1$ to $n$. But one important thing: we don't need to consider such pairs $x_j$ and $x_{j + 1}$ that $x_j = x_{j + 1}$ (it broke my solution somehow so this part is important). Knowing these two parts we can easily calculate $f(p_i(n))$ using $f(p_1(n))$. Firstly, let's initialize the result as $res = f(p_1(n)) - cnt[i]$. Then we need to recalculate lengths of such segments that $i$ is their endpoint. Let's iterate over all elements $j$ in $adj[i]$, set $res := res - |j - i|$ (remove the old segment) and set $res := res + j$ (add the length of the segment from $j$ to $1$) and increase $res$ by one if $j < i$ (it means that $i$ and $j$ change their relative order and the length of the segment from $j$ to $i$ increases by one). Now we can see that after iterating over all $i$ from $1$ to $n$ we make at most $O(n + m)$ moves because each pair of adjacent elements in $x$ was considered at most twice. Total complexity: $O(n + m)$.
[ "math" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> a(m); for (int i = 0; i < m; ++i) { cin >> a[i]; --a[i]; } vector<long long> res(n); for (int j = 0; j < m - 1; ++j) { res[0] += abs(a[j] - a[j + 1]); } vector<int> cnt(n); vector<vector<int>> adj(n); for (int i = 0; i < m - 1; ++i) { int l = a[i], r = a[i + 1]; if (l != r) { adj[l].push_back(r); adj[r].push_back(l); } if (l > r) swap(l, r); if (r - l < 2) continue; ++cnt[l + 1]; --cnt[r]; } for (int i = 0; i < n - 1; ++i) { cnt[i + 1] += cnt[i]; } for (int i = 1; i < n; ++i) { res[i] = res[0] - cnt[i]; for (auto j : adj[i]) { res[i] -= abs(i - j); res[i] += j + (j < i); } } for (int i = 0; i < n; ++i) { cout << res[i] << " "; } cout << endl; return 0; }
1234
F
Yet Another Substring Reverse
You are given a string $s$ consisting only of first $20$ lowercase Latin letters ('a', 'b', ..., 't'). Recall that the substring $s[l; r]$ of the string $s$ is the string $s_l s_{l + 1} \dots s_r$. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top". You can perform the following operation \textbf{no more than once}: choose some substring $s[l; r]$ and \textbf{reverse} it (i.e. the string $s_l s_{l + 1} \dots s_r$ becomes $s_r s_{r - 1} \dots s_l$). Your goal is to maximize the length of the maximum substring of $s$ consisting of \textbf{distinct} (i.e. unique) characters. The string consists of \textbf{distinct} characters if no character in this string appears more than once. For example, strings "abcde", "arctg" and "minecraft" consist of distinct characters but strings "codeforces", "abacaba" do not consist of distinct characters.
First of all, I wanted to offer you one little challenge: I found a solution that I can't break (and I don't sure if it can be broken) and I will be so happy if anyone will give me countertest which will break it. You can see its code below. Let's notice that we can reduce our problem to the following: find two substrings of the given string that letters in them do not intersect and the total length of these substrings is the maximum possible. Why can we make such a reduction? It is so because our answer consists of at most two non-intersecting parts: one fixed substring and at most one substring that we appended to the first one. We can always append any other substring to the first one by one reverse operation (just look at some examples to understand it). Let's iterate over all possible substrings of length at most $AL$ (where $AL$ is the size of the alphabet) which contain distinct letters. We can do it in $O(n AL)$. Let the current substring containing distinct letters be $s[i; j]$. Let's create the bitmask corresponding to this substring: the bit $pos$ is $1$ if the $pos$-th letter of the alphabet is presented in the substring and $0$ otherwise (letters are $0$-indexed). Store all these masks somewhere. Notice that our current problem can be reduced to the following: we have the set of masks and we need to find a pair of masks that they do not intersect and their total number of ones in them is the maximum possible. This reduction is less obvious than the previous one but you also can understand it considering some examples. So how to solve this problem? We can do it with easy bitmasks dynamic programming! Let $dp_{mask}$ be the maximum number of ones in some mask that is presented in the given string and it is the submask of $mask$. How to calculate this dynamic programming? First of all, all values $dp_{mask}$ for all masks presented in the string are equal to the number of ones in corresponding masks. Let's iterate over all masks from $0$ to $2^{AL} - 1$. Let the current mask be $mask$. Then let's try to update the answer for this mask with the answer for one of its submasks. It is obvious that because of dynamic programming we need to remove at most one bit from our mask to cover all possible submasks that can update our answer. So let's iterate over all bits in $mask$, let the current bit be $pos$. If this bit is zero then just skip it. Otherwise update $dp_{mask} := max(dp_{mask}, dp_{mask \hat{} 2^{pos}})$, where $\hat{}$ is the xor operation. After calculating this dynamic programming we can finally calculate the answer. Let's iterate over all masks presented in the string, let the current mask be $mask$. We can update the answer with the number of ones in $mask$ plus $dp_{mask \hat{} (2^{AL} - 1)}$ ($mask \hat{} (2^{AL} - 1)$ is the completion of $mask$). Total complexity: $O(n AL + AL 2^{AL})$.
[ "bitmasks", "dp" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int tt = clock(); string s; cin >> s; vector<int> dp(1 << 20); vector<int> masks; for (int i = 0; i < int(s.size()); ++i) { vector<bool> used(20); int mask = 0; for (int j = 0; i + j < int(s.size()); ++j) { if (used[s[i + j] - 'a']) break; used[s[i + j] - 'a'] = true; mask |= 1 << (s[i + j] - 'a'); masks.push_back(mask); } } sort(masks.begin(), masks.end()); masks.resize(unique(masks.begin(), masks.end()) - masks.begin()); sort(masks.begin(), masks.end(), [](int x, int y){ return __builtin_popcount(x) > __builtin_popcount(y); }); int ans = __builtin_popcount(masks[0]); for (int i = 0; i < int(masks.size()); ++i) { if (clock() - tt > 1900) { break; } for (int j = i + 1; j < int(masks.size()); ++j) { if (!(masks[i] & masks[j])) { ans = max(ans, __builtin_popcount(masks[i]) + __builtin_popcount(masks[j])); break; } } } cout << ans << endl; return 0; }
1236
A
Stones
Alice is playing with some stones. Now there are three numbered heaps of stones. The first of them contains $a$ stones, the second of them contains $b$ stones and the third of them contains $c$ stones. Each time she can do one of two operations: - take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); - take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $0$ stones. Can you help her?
We can use many ways to solve the problem. If you just enumerate how many operations of the first and the second type, it will also pass. Of course there is a greedy solution. We make the second operation as much as possible, and then use the first operation. It takes $O(1)$ time.
[ "brute force", "greedy", "math" ]
800
null
1236
B
Alice and the List of Presents
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends. There are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind. Also, there are $m$ boxes. All of them are for different people, so they are pairwise distinct (consider that the names of $m$ friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box. Alice wants to pack presents with the following rules: - She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of $n$ kinds, empty boxes are allowed); - For each kind at least one present should be packed into some box. Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo $10^9+7$. See examples and their notes for clarification.
The answer is $(2^m-1)^n$. If we consider each present, it may contain only in the first box, in the second ... both in the first and second box, in the first and the third one ... in the first,the second and the third one ... There are $2^m-1$ ways. There are $n$ presents, so there are $(2^m-1)^n$ ways in total according to the Multiplication Principle.
[ "combinatorics", "math" ]
1,500
null
1236
C
Labs
In order to do some research, $n^2$ labs are built on different heights of a mountain. Let's enumerate them with integers from $1$ to $n^2$, such that the lab with the number $1$ is at the lowest place, the lab with the number $2$ is at the second-lowest place, $\ldots$, the lab with the number $n^2$ is at the highest place. To transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number $u$ to the lab with the number $v$ if $u > v$. Now the labs need to be divided into $n$ groups, each group should contain exactly $n$ labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group $A$ to a group $B$ is equal to the number of pairs of labs ($u, v$) such that the lab with the number $u$ is from the group $A$, the lab with the number $v$ is from the group $B$ and $u > v$. Let's denote this value as $f(A,B)$ (i.e. $f(A,B)$ is the sum of units of water that can be sent from a group $A$ to a group $B$). For example, if $n=3$ and there are $3$ groups $X$, $Y$ and $Z$: $X = \{1, 5, 6\}, Y = \{2, 4, 9\}$ and $Z = \{3, 7, 8\}$. In this case, the values of $f$ are equal to: - $f(X,Y)=4$ because of $5 \rightarrow 2$, $5 \rightarrow 4$, $6 \rightarrow 2$, $6 \rightarrow 4$, - $f(X,Z)=2$ because of $5 \rightarrow 3$, $6 \rightarrow 3$, - $f(Y,X)=5$ because of $2 \rightarrow 1$, $4 \rightarrow 1$, $9 \rightarrow 1$, $9 \rightarrow 5$, $9 \rightarrow 6$, - $f(Y,Z)=4$ because of $4 \rightarrow 3$, $9 \rightarrow 3$, $9 \rightarrow 7$, $9 \rightarrow 8$, - $f(Z,X)=7$ because of $3 \rightarrow 1$, $7 \rightarrow 1$, $7 \rightarrow 5$, $7 \rightarrow 6$, $8 \rightarrow 1$, $8 \rightarrow 5$, $8 \rightarrow 6$, - $f(Z,Y)=5$ because of $3 \rightarrow 2$, $7 \rightarrow 2$, $7 \rightarrow 4$, $8 \rightarrow 2$, $8 \rightarrow 4$. Please, divide labs into $n$ groups with size $n$, such that the value $\min f(A,B)$ over all possible pairs of groups $A$ and $B$ ($A \neq B$) is \textbf{maximal}. In other words, divide labs into $n$ groups with size $n$, such that minimum number of the sum of units of water that can be transported from a group $A$ to a group $B$ for every pair of different groups $A$ and $B$ ($A \neq B$) as big as possible. Note, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values $f$ for some division. If there are many optimal divisions, you can find any.
The maximum number is $\lfloor\frac{n^2}{2}\rfloor$. It can be proved we cannot find a larger answer. There is $n^2$ pipes between any two groups. So the valid pairs of the minimum of them does not exceed $\lfloor\frac{n^2}{2}\rfloor$. Then we try to find a way to achieve the maximum. We find if we put the first lab in the first group, the second one to the second group ... the $n$-th one to the $n$-th group. Then put the $n+1$-th one in the $n$-th group, the $n+2$-th one in the $n-1$-th group ... the $2n$-th one to the first group. And then again use the method for the $2n+1$-th to the $4n$-th lab. if $n$ is odd, then we will only use the previous half of the method.
[ "constructive algorithms", "greedy", "implementation" ]
1,300
null
1236
D
Alice and the Doll
Alice got a new doll these days. It can even walk! Alice has built a maze for the doll and wants to test it. The maze is a grid with $n$ rows and $m$ columns. There are $k$ obstacles, the $i$-th of them is on the cell $(x_i, y_i)$, which means the cell in the intersection of the $x_i$-th row and the $y_i$-th column. However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze. More formally, there exist $4$ directions, in which the doll can look: - The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x, y + 1)$; - The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x + 1, y)$; - The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x, y - 1)$; - The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x - 1, y)$. .Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: $1 \to 2$, $2 \to 3$, $3 \to 4$, $4 \to 1$. Standing in one cell, the doll can make at most one turn right. Now Alice is controlling the doll's moves. She puts the doll in of the cell $(1, 1)$ (the upper-left cell of the maze). Initially, the doll looks to the direction $1$, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Consider just simulate the whole process. We walk straight, and then turn right when meet the obstacle or the border of the grid. Then we can use set to make it faster. We can check along the direction, which is the first obstacle. To check whether any cell is covered, we can calculate the number of cells we walk across and then check if it equals to $n*m-k$. Also,we can sort the obstacles by x and y, then use binary search to find the first obstacle along the direction. Time complexity is $O(nlogn)$.
[ "brute force", "data structures", "greedy", "implementation" ]
2,300
null
1236
E
Alice and the Unfair Game
Alice is playing a game with her good friend, Marisa. There are $n$ boxes arranged in a line, numbered with integers from $1$ to $n$ from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have $m$ chances to guess where the doll is. If Alice will correctly guess the number of box, where doll is now, she will win the game, otherwise, her friend will win the game. In order to win, Marisa will use some unfair tricks. After each time Alice guesses a box, she can move the doll to the neighboring box or just keep it at its place. Boxes $i$ and $i + 1$ are neighboring for all $1 \leq i \leq n - 1$. She can also use this trick once before the game starts. So, the game happens in this order: the game starts, Marisa makes the trick, Alice makes the first guess, Marisa makes the trick, Alice makes the second guess, Marisa makes the trick, $\ldots$, Alice makes $m$-th guess, Marisa makes the trick, the game ends. Alice has come up with a sequence $a_1, a_2, \ldots, a_m$. In the $i$-th guess, she will ask if the doll is in the box $a_i$. She wants to know the number of scenarios $(x, y)$ (for all $1 \leq x, y \leq n$), such that Marisa can win the game if she will put the doll at the $x$-th box at the beginning and at the end of the game, the doll will be at the $y$-th box. Help her and calculate this number.
First there is a conclusion: each start point will be able to reach a consecutive segment of end points except for n=1. It's easy to prove, when a place is banned, we can make a move to make it reachable again. So with the conclusion then we can solve the problem. First we will come up with a greedy algorithm. We can move the doll to the left (or right) if possible, otherwise we can keep it at its place. Then we will get the left bound and the right bound of one start point. It's $O(n^2)$ and not enough to pass. Consider we try to find the left bound. We scan the array $a$ and deal with all start points together. For the first element of $a$, it will only influence one start point (that is, if we start from there, we will meet the element can then we need to keep it at its place). So we can move the start point to its right box (because when it starts from that place, we will get the same answer). Then we can delete the first element. But then there will be more than one start point in the same cell, we can use dsu to merge two set of start points. Note that the doll cannot move to $0$ or $n+1$. We can also have to deal with this using the algorithm above. And it is the same to find the right bound. Time complexity is $O(n)$. Another solution: Consider a grid that there is obstacles on $(i,a_i)$. Each time we start from $(0,y)$ and if there is no obstacle on $(x+1,y-1)$ then we move to it, otherwise we move to $(x,y-1)$. We find we may change the direction only if we reach the place $(i-1,a_i+1)$ and we will walk to $(i,a_i+1)$. So only the $O(k)$ positions are useful. We can use binary search to find the next position for each useful position and start point. Then we get a tree. Just using dfs then we will get left bound for each start points. The Time complexity is $O(nlogn)$.
[ "binary search", "data structures", "dp", "dsu" ]
2,500
null
1236
F
Alice and the Cactus
Alice recently found some cactuses growing near her house! After several months, more and more cactuses appeared and soon they blocked the road. So Alice wants to clear them. A cactus is a connected undirected graph. No edge of this graph lies on more than one simple cycle. Let's call a sequence of different nodes of the graph $x_1, x_2, \ldots, x_k$ a simple cycle, if $k \geq 3$ and all pairs of nodes $x_1$ and $x_2$, $x_2$ and $x_3$, $\ldots$, $x_{k-1}$ and $x_k$, $x_k$ and $x_1$ are connected with edges. Edges $(x_1, x_2)$, $(x_2, x_3)$, $\ldots$, $(x_{k-1}, x_k)$, $(x_k, x_1)$ lies on this simple cycle. There are so many cactuses, so it seems hard to destroy them. But Alice has magic. When she uses the magic, every node of the cactus will be removed independently with the probability $\frac{1}{2}$. When a node is removed, the edges connected to it are also removed. Now Alice wants to test her magic. She has picked a cactus with $n$ nodes and $m$ edges. Let $X[S]$ (where $S$ is a subset of the removed nodes) be the number of connected components in the remaining graph after removing nodes of set $S$. Before she uses magic, she wants to know the variance of random variable $X$, if all nodes of the graph have probability $\frac{1}{2}$ to be removed and all $n$ of these events are independent. By the definition the variance is equal to $E[(X - E[X])^2]$, where $E[X]$ is the expected value of $X$. Help her and calculate this value by modulo $10^9+7$. Formally, let $M = 10^9 + 7$ (a prime number). It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, find such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
First we consider how to calculate $E(X)$. The number of connected components equals to the number of nodes minus the number of edges and then add the number of rings in it. So we can calculate the possibility of removing one node, one edge or one single ring. Then we can split the variance, it is equals to $E(X^2)-2*E(X)^2+E(X)^2=E(X^2)-E(X)^2$. Then we can again to split $X^2$. Let the number nodes equal to $a$, the number edges equal to $b$, the number rings equal to $c$. Then $X^2=(a-b+c)^2=a^2+b^2+c^2-2ab-2bc+2ac$. We can find there is contribution between a pair of nodes, edges, rings (the two may be the same) and between a node and an edge, a node and a ring, an edge and a ring. Then we can calculate the possibility of such pair that the elements in it remains at the same time. The answer is the same when the pair is a ring and a node on it, or when it is a ring and a node not on it, or an edge with one of its end point ... If we consider all the situation of intersection and not intersection, we can get a liner algorithm. But the Time Complexity is $O(nlogn)$ since we need to calculate the multiplicative inverse of modulo.
[ "dfs and similar", "graphs", "math", "probabilities" ]
3,000
null
1237
A
Balanced Rating Changes
Another Codeforces Round has just finished! It has gathered $n$ participants, and according to the results, the expected rating change of participant $i$ is $a_i$. These rating changes are perfectly balanced — their sum is equal to $0$. Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two. There are two conditions though: - For each participant $i$, their modified rating change $b_i$ must be integer, and as close to $\frac{a_i}{2}$ as possible. It means that either $b_i = \lfloor \frac{a_i}{2} \rfloor$ or $b_i = \lceil \frac{a_i}{2} \rceil$. In particular, if $a_i$ is even, $b_i = \frac{a_i}{2}$. Here $\lfloor x \rfloor$ denotes rounding down to the largest integer not greater than $x$, and $\lceil x \rceil$ denotes rounding up to the smallest integer not smaller than $x$. - The modified rating changes must be perfectly balanced — their sum must be equal to $0$. Can you help with that?
Let $b_i = \frac{a_i}{2} + \delta_i$. It follows that if $a_i$ is even, then $\delta_i = 0$, and if $a_i$ is odd, then either $\delta_i = \frac{1}{2}$ or $\delta_i = -\frac{1}{2}$. At the same time, the sum of $b_i$ is equal to the sum of $\delta_i$, as the sum of $a_i$ is $0$. Thus, as the sum of $b_i$ must be equal to $0$, we need to have an equal number of $\delta_i$ equal to $\frac{1}{2}$ and $-\frac{1}{2}$. In simple words, we have to divide all numbers by $2$, and out of all non-integers, exactly half of them must be rounded up and the other half must be rounded down.
[ "implementation", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; int flag = 1; for (int i = 0; i < n; i++) { int x; cin >> x; if (x % 2 == 0) { cout << x / 2 << '\n'; } else { cout << (x + flag) / 2 << '\n'; flag *= -1; } } return 0; }
1237
B
Balanced Tunnel
Consider a tunnel on a one-way road. During a particular day, $n$ cars numbered from $1$ to $n$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds. A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced. Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time. Traffic regulations prohibit overtaking inside the tunnel. If car $i$ overtakes any other car $j$ inside the tunnel, car $i$ must be fined. However, each car can be fined at most once. Formally, let's say that car $i$ definitely overtook car $j$ if car $i$ entered the tunnel later than car $j$ and exited the tunnel earlier than car $j$. Then, car $i$ must be fined if and only if it definitely overtook at least one other car. Find the number of cars that must be fined.
This problem can be approached in several ways, here is one of them. Let's say that cars exit the tunnel at time moments $1, 2, \ldots, n$, and let $c_i$ be time when car $a_i$ exited the tunnel. For instance, in the first example we had $a = \langle 3, 5, 2, 1, 4 \rangle$ and $b = \langle 4, 3, 2, 5, 1 \rangle$. Then, $c = \langle 2, 4, 3, 5, 1 \rangle$: car $3$ entered first and exited at time $2$, so $c_1 = 2$; car $5$ entered second and exited and time $4$, so $c_2 = 4$; and so on. Note that $c$ is a permutation, and not only it can be found in $O(n)$, but also it can be very useful for us. It turns out that we can use $c$ to easily determine if car $a_i$ must be fined. Specifically, car $a_i$ must be fined if $c_i$ is smaller than $\max(c_1, c_2, \ldots, c_{i-1})$. Why is that? Recall that car $a_i$ must be fined if there exists a car that entered the tunnel earlier and exited the tunnel later. If a car entered the tunnel earlier, it must be $a_j$ such that $j < i$. If a car exited the tunnel later, it must be that $c_j > c_i$. Therefore, now we can just go from left to right, keeping the maximum of $c_1, c_2, \ldots, c_{i-1}$ to compare it to $c_i$. The overall complexity is $O(n)$.
[ "data structures", "sortings", "two pointers" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> a(n), b(n); for (int i = 0; i < n; i++) { cin >> a[i]; --a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; --b[i]; } vector<int> pos(n); for (int i = 0; i < n; i++) { pos[b[i]] = i; } vector<int> c(n); for (int i = 0; i < n; i++) { c[i] = pos[a[i]]; } int mx = -1, ans = 0; for (int i = 0; i < n; i++) { if (c[i] > mx) { mx = c[i]; } else { ++ans; } } cout << ans << '\n'; return 0; }
1237
C1
Balanced Removals (Easier)
This is an easier version of the problem. In this version, $n \le 2000$. There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even. You'd like to remove all $n$ points using a sequence of $\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$. Formally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$, $\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$, and $\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$. Note that the bounding box might be degenerate. Find a way to remove all points in $\frac{n}{2}$ snaps.
Pick any two points $i$ and $j$, let's say that this is our candidate pair $(i, j)$ for removal. Loop over all other points. If some point $k$ lies inside the bounding box of $i$ and $j$, change our candidate pair to $(i, k)$. Note that the bounding box of $i$ and $k$ lies inside the bounding box of $i$ and $j$, so we don't need to recheck points that we have already checked. The candidate pair we get at the end of the loop can surely be removed. Another look at the situation is that we can pick any point $i$, and then pick point $j$ that is the closest to point $i$, either by Euclidean or Manhattan metric. Pair $(i, j)$ can be removed then, as if any point $k$ lies inside the bounding box of $i$ and $j$, it's strictly closer to $i$ than $j$. Both of these solutions work in $O(n^2)$.
[ "constructive algorithms", "geometry", "greedy" ]
1,700
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<pair<int, int>, pair<int, int> > ii; int main(){ int n; cin >> n; vector<ii> v(n); for (int i = 0; i < n; i++){ cin >> v[i].first.first >> v[i].first.second >> v[i].second.first; v[i].second.second = i + 1; } while(!v.empty()){ sort(v.begin(), v.end()); int x = v.back().first.first; int y = v.back().first.second; int z = v.back().second.first; int pos = v.back().second.second; v.pop_back(); int ind = 0; ll d = 1e10; for (int i = 0; i < (int) v.size(); i++){ ll dist = abs(v[i].first.first - x); dist += abs(v[i].first.second - y); dist += abs(v[i].second.first - z); if (dist < d){ d = dist; ind = i; } } cout << pos << " " << v[ind].second.second << endl; v.erase(v.begin() + ind); } }
1237
C2
Balanced Removals (Harder)
This is a harder version of the problem. In this version, $n \le 50\,000$. There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even. You'd like to remove all $n$ points using a sequence of $\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$. Formally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$, $\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$, and $\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$. Note that the bounding box might be degenerate. Find a way to remove all points in $\frac{n}{2}$ snaps.
Consider a one-dimensional version of the problem where $n$ is not necessarily even. We can sort all points by their $x$-coordinate and remove them in pairs. This way, we'll leave at most one point unremoved. Now, consider a two-dimensional version of the problem where $n$ is not necessarily even. For each $y$, consider all points that have this $y$-coordinate and solve the one-dimensional version on them. After we do this, we'll have at most one point on each $y$ left. Now we can sort the points by $y$ and remove them in pairs in this order. Again, we'll leave at most one point unremoved. Finally, consider a three-dimensional version of the problem. Again, for each $z$, consider all points that have this $z$-coordinate and solve the two-dimensional version on them. After we do this, we'll have at most one point on each $z$ left. Now we can sort the points by $z$ and remove them in pairs in this order. We can even generalize this solution to any number of dimensions and solve the problem in $O(dn \log n)$.
[ "binary search", "constructive algorithms", "divide and conquer", "greedy", "implementation", "sortings" ]
1,900
#include <bits/stdc++.h> using namespace std; const int D = 3; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<vector<int>> p(n, vector<int>(D)); for (int i = 0; i < n; i++) { for (int j = 0; j < D; j++) { cin >> p[i][j]; } } auto Solve = [&](auto& Self, vector<int> ids, int k) { if (k == D) { return ids[0]; } map<int, vector<int>> mp; for (int x : ids) { mp[p[x][k]].push_back(x); } vector<int> a; for (auto& q : mp) { int cur = Self(Self, q.second, k + 1); if (cur != -1) { a.push_back(cur); } } for (int i = 0; i + 1 < (int) a.size(); i += 2) { cout << a[i] + 1 << " " << a[i + 1] + 1 << '\n'; } return (a.size() % 2 == 1 ? a.back() : -1); }; vector<int> t(n); iota(t.begin(), t.end(), 0); Solve(Solve, t, 0); return 0; }
1237
D
Balanced Playlist
Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of $n$ tracks numbered from $1$ to $n$. The playlist is automatic and cyclic: whenever track $i$ finishes playing, track $i+1$ starts playing automatically; after track $n$ goes track $1$. For each track $i$, you have estimated its coolness $a_i$. The higher $a_i$ is, the cooler track $i$ is. Every morning, you choose a track. The playlist then starts playing from this track in its usual cyclic fashion. At any moment, you remember the maximum coolness $x$ of already played tracks. Once you hear that a track with coolness \textbf{strictly} less than $\frac{x}{2}$ (no rounding) starts playing, you turn off the music immediately to keep yourself in a good mood. For each track $i$, find out how many tracks you will listen to before turning off the music if you start your morning with track $i$, or determine that you will never turn the music off. Note that if you listen to the same track several times, every time must be counted.
This problem allowed a lot of approaches. First, to determine if the answer is all $-1$, compare half of maximum $x_i$ and minimum $x_i$. Second, note that during the first $n$ tracks, we'll listen to the track with maximum $x_i$, and during the next $n$ tracks, we'll stop at the track with minimum $x_i$. Thus, to pretend that the cyclic playlist is linear, it's enough to repeat it three times. For each track $i$, let's find the next track $j$ with coolness more than $x_i$, and the next track $k$ with coolness less than $\frac{x_i}{2}$. Then it's easy to see that if $j < k$, we have $c_i = c_j + j - i$, and if $j > k$, we have $c_i = k - i$. Thus, all that remains is to find the next track after every track $i$ whose coolness lies in some segment of values. This can be done with binary search over segment tree in $O(n \log^2 n)$, binary search over sparse table in $O(n \log n)$, binary search over stack in $O(n \log n)$ as well... Alternatively, if we go through tracks in increasing/decreasing order of coolness, we can also answer these queries with two pointers and a structure like C++ set or Java TreeSet. Bonus: solve the problem in $O(n)$.
[ "binary search", "data structures", "implementation" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> a(3 * n); for (int i = 0; i < n; i++) { cin >> a[i]; a[i + n] = a[i + 2 * n] = a[i]; } vector<int> ans(3 * n); vector<int> st_max; vector<int> st_min; for (int i = 3 * n - 1; i >= 0; i--) { while (!st_max.empty() && a[st_max.back()] < a[i]) { st_max.pop_back(); } while (!st_min.empty() && a[st_min.back()] > a[i]) { st_min.pop_back(); } int low = 0, high = (int) st_min.size(); while (low < high) { int mid = (low + high) >> 1; if (a[st_min[mid]] * 2 < a[i]) { low = mid + 1; } else { high = mid; } } int nxt = 3 * n; if (low > 0) { nxt = min(nxt, st_min[low - 1]); } if (!st_max.empty()) { nxt = min(nxt, st_max.back()); } if (nxt < 3 * n && a[nxt] >= a[i]) { ans[i] = ans[nxt]; } else { ans[i] = nxt; } st_min.push_back(i); st_max.push_back(i); } for (int i = 0; i < n; i++) { if (i > 0) { cout << " "; } cout << (ans[i] == 3 * n ? -1 : ans[i] - i); } cout << '\n'; return 0; }
1237
E
Balanced Binary Search Trees
Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree. The depth of a vertex is the number of edges on the simple path from the vertex to the root. In particular, the depth of the root is $0$. Let's call a binary search tree perfectly balanced if there doesn't exist a binary search tree with the same number of vertices that has a strictly smaller sum of depths of its vertices. Let's call a binary search tree with integer keys striped if both of the following conditions are satisfied for every vertex $v$: - If $v$ has a \textbf{left} subtree whose root is $u$, then the parity of the key of $v$ is \textbf{different} from the parity of the key of $u$. - If $v$ has a \textbf{right} subtree whose root is $w$, then the parity of the key of $v$ is the \textbf{same} as the parity of the key of $w$. You are given a single integer $n$. Find the number of perfectly balanced striped binary search trees with $n$ vertices that have distinct integer keys between $1$ and $n$, inclusive. Output this number modulo $998\,244\,353$.
Consider perfectly balanced striped BSTs of some maximum depth $d$. Note that both the left and the right subtree of the root must be perfectly balanced striped BSTs of maximum depth $d-1$. Also note that the parity of the root must be equal to the parity of $n$, as $n$ lies on the rightmost branch of the tree; thus, the size of the right subtree must be even. Consider trees of maximum depth $2$: there is one with $n = 4$ and one with $n = 5$. A tree of maximum depth $3$ can have its right subtree of size $4$ only, and its left subtree can have size $4$ or $5$; thus, we have one tree with $n = 9$ and one with $n = 10$. Using induction, we can prove that for any maximum depth $d$, we have exactly two possible trees, of sizes $x$ and $x + 1$ for some $x$. We can enumerate these trees and check if $n$ belongs to the set of possible sizes in $O(\log n)$.
[ "dp", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; int x = 1; while (x <= n) { if (n == x || n == x + 1) { cout << 1 << '\n'; return 0; } if (x % 2 == 0) { x = x + 1 + x; } else { x = (x + 1) + 1 + x; } } cout << 0 << '\n'; return 0; }
1237
F
Balanced Domino Placements
Consider a square grid with $h$ rows and $w$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino. Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino. You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $998\,244\,353$.
Suppose we're going to place $d_h$ extra horizontal dominoes and $d_v$ extra vertical ones. Consider all rows of the grid, and mark them with $0$ if it's empty and with $1$ if it already has a covered cell. Do the same for columns. Now, let's find the number of ways $R$ to pick $d_h$ rows marked with $0$, and also $d_v$ pairs of neighboring rows marked with $0$, so that these sets of rows don't intersect. Similarly, let's find the number of ways $C$ to pick $d_h$ pairs of columns marked with $0$, and also $d_v$ columns marked with $0$. Then, the number of ways to place exactly $d_h$ horizontal dominoes and $d_v$ vertical ones is $R \cdot C \cdot d_h! \cdot d_v!$. To find $R$, let's use DP: let $f(i, j)$ be the number of ways to pick $j$ pairs of neighboring rows out of the first $i$ rows. Then, $f(i, j) = f(i - 1, j)$ if any of rows $i$ or $i-1$ is marked with $1$, and $f(i, j) = f(i - 1, j) + f(i - 2, j - 1)$ if both are marked with $0$. It follows that $R = f(h, d_v) * \binom{h - 2d_v}{d_h}$. $C$ can be found similarly. The complexity of this solution is $O((R+C)^2)$.
[ "combinatorics", "dp" ]
2,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MOD = 998244353; const int MAX = 3610; ll dp1[MAX][MAX], dp2[MAX][MAX]; int has1[MAX], has2[MAX]; ll fac[MAX], c[MAX][MAX]; int n, m, k; void make(int n){ dp1[0][0] = 1; for (int i = 1; i <= n; i++){ for (int j = 0; j <= m; j++){ dp1[i][j] = dp1[i - 1][j]; if (j && i >= 2 && has1[i] == 0 && has1[i - 1] == 0){ dp1[i][j] += dp1[i - 2][j - 1]; } dp1[i][j] %= MOD; } } } int main(){ cin >> n >> m >> k; int t = max(n, m) + 1; vector<ll> f(t); for (int i = 1; i <= k; i++){ int a, b, c, d; cin >> a >> b >> c >> d; if (has1[a] || has1[c] || has2[b] || has2[d]){ cout << 0 << endl; return 0; } has1[a] = has1[c] = has2[b] = has2[d] = 1; } int N = n, M = m; for (int i = 1; i <= n; i++){ N -= has1[i]; } for (int i = 1; i <= m; i++){ M -= has2[i]; } make(n); swap(dp1, dp2); swap(has1, has2); make(m); swap(dp1, dp2); swap(has1, has2); c[0][0] = 1; f[0] = 1; for (int i = 1; i < t; i++){ f[i] = (f[i - 1] * i) % MOD; c[i][0] = c[i][i] = 1; for (int j = 1; j < i; j++){ c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; if (c[i][j] >= MOD){ c[i][j] -= MOD; } } } ll ans = 0; for (int i = 0; (i << 1) <= N; i++){ for (int j = 0; (j << 1) <= M; j++){ int have1 = N - 2 * i; int have2 = M - 2 * j; ll res = dp1[n][i] * dp2[m][j]; res %= MOD; res *= c[have1][j]; res %= MOD; res *= c[have2][i]; res %= MOD; res *= f[i]; res %= MOD; res *= f[j]; res %= MOD; ans += res; } } ans %= MOD; cout << ans << endl; }
1237
G
Balanced Distribution
There are $n$ friends living on a circular street. The friends and their houses are numbered clockwise from $0$ to $n-1$. Initially person $i$ has $a_i$ stones. The friends want to make the distribution of stones among them perfectly balanced: everyone should possess the same number of stones. The only way to change the distribution of stones is by conducting meetings. During a meeting, people from exactly $k$ consecutive houses (remember that the street is circular) gather at the same place and bring all their stones with them. All brought stones may be redistributed among people attending the meeting arbitrarily. The total number of stones they possess before the meeting and after the meeting must stay the same. After the meeting, everyone returns to their home. Find a way to make the distribution of stones perfectly balanced conducting as few meetings as possible.
Let $A$ be the average of $a_i$, and let $p_i$ be the sum of $a_0, a_1, \ldots, a_i$ minus $A$ times $i+1$. Consider a pair of friends $i$ and $(i+1) \bmod n$ that never attend the same meeting. Then we can make a "cut" between them to transform the circle into a line. Consider some other pair of friends $j$ and $(j+1) \bmod n$ with the same property. Now we can cut our line into two segments. As these segments never interact with each other, we must have $p_i = p_j$ if we want the problem to be solvable. Similarly, for all "cuts" we do, between some pairs $k$ and $(k+1) \bmod n$, the value of $p_k$ must be the same. Now, considering some value $x$, let's make cuts at all positions $i$ with $p_i = x$. The circle is cut into several segments. For a segment of length $l$, I claim that it can always be balanced in $\lceil \frac{l-1}{k-1} \rceil$ meetings. Let's trust this for a while. If we carefully look at the formulas, we may note that if a segment has length $l$ such that $l \neq 1 (\bmod (k-1))$, it can be merged to any neighboring segment without increasing the number of meetings. It follows that we either make just one cut anywhere, or in the sequence of $i \bmod (k-1)$ for $i$ with $p_i = x$, we need to find the longest subsequence of $(0, 1, \ldots, k-2)*$ in cyclic sense. This can be done, for example, with binary lifting. The complexity of this step will be proportional to $O(c \log c)$, where $c$ is the number of positions with $p_i = x$. Thus, for any value of $x$, we can find the smallest number of meetings we need if we only make cuts at positions with $p_i = x$ in $O(n \log n)$ overall, and we can pick the minimum over these. It remains to show that we can balance any segment of length $l$ in $\lceil \frac{l-1}{k-1} \rceil$ meetings. Consider the $k$ leftmost positions. If we have at least $(k-1) \cdot A$ stones there, then we can make a meeting on these positions, send whatever remains to the $k$-th leftmost position, and proceed inductively. If we have less than $(k-1) \cdot A$ stones there, let's solve the problem for the rightmost $l-k+1$ positions first, with the goal of sending all the extra stones to the $k$-th leftmost position. This is similar to what we usually want to do, so again we can proceed inductively to reach the goal on the right first, and then conduct a meeting on the $k$ leftmost positions, this time having enough stones to satisfy the demand.
[ "data structures", "dp", "greedy" ]
3,500
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; using pii = pair<int, int>; using pli = pair<ll, int>; using pll = pair<ll, ll>; #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int maxn = 200005; const int maxk = 19; const int inf = 1e9; ll a[2 * maxn]; ll psum[2 * maxn]; pair2<int> go[maxk][2 * maxn]; map<ll, int> lst[maxn]; int id[2 * maxn]; int n, k; ll need; vector<pair<int, vector<ll>>> answer; void perform(int l) { int fn = min(l + k, n); assert(psum[fn] >= 0); ll wassum = psum[fn]; vector<ll> exchange = vector<ll>(k, need); int start = min(n - k, l); for (int i = start; i < l; i++) exchange[i - start] = need + a[i]; exchange[l - start] += -psum[l]; exchange.back() += psum[fn]; answer.pb({start, exchange}); for (int i = l; i < fn; i++) a[i] = 0; a[l] += -psum[l]; a[fn - 1] += psum[fn]; for (int i = start; i < start + k; i++) psum[i + 1] = psum[i] + a[i]; assert(wassum == psum[fn]); } void restore(int l) { if (l >= n) return; if (a[l] == 0 && psum[l] == 0) { restore(l + 1); return; } int fn = min(l + k, n); if (psum[fn] >= 0) { perform(l); restore(l + k - (psum[fn] > 0)); return; } else { restore(l + k - 1); assert(psum[fn] == 0); perform(l); } } int main() { scanf("%d%d", &n, &k); for (int i = 0; i < n; i++) scanf("%lld", &a[i]); need = accumulate(a, a + n, 0LL); assert(need % n == 0); need /= n; for (int i = 0; i < n; i++) a[i] -= need; for (int i = 0; i < n; i++) a[i + n] = a[i]; partial_sum(a, a + 2 * n, psum + 1); pair2<int> ans = {inf, -1}; for (int j = 0; j < maxk; j++) go[j][2 * n] = {2 * n, 0}; for (int i = 2 * n - 1; i >= 0; i--) { int curid = id[i + 1]; if (lst[curid].count(psum[i])) { int to = lst[curid][psum[i]]; go[0][i] = {to, (to - i - 1) / (k - 1)}; } else { int to = 2 * n; go[0][i] = {to, (to - i + k - 2) / (k - 1)}; } for (int j = 1; j < maxk; j++) go[j][i] = {go[j - 1][go[j - 1][i].fi].fi, go[j - 1][i].se + go[j - 1][go[j - 1][i].fi].se}; if (i < n) { int to = n + i; int cur = i; int curans = 0; for (int j = maxk - 1; j >= 0; j--) if (go[j][cur].fi <= to) { curans += go[j][cur].se; cur = go[j][cur].fi; } if (cur < to) curans += (to - cur - 1 + k - 2) / (k - 1); ans = min(ans, {curans, i}); } id[i] = (2 * n - i) % (k - 1); lst[id[i]][psum[i]] = i; } rotate(a, a + ans.se, a + n); partial_sum(a, a + n, psum + 1); restore(0); assert((int)answer.size() == ans.fi); printf("%d\n", (int)answer.size()); for (auto &t : answer) { printf("%d", (t.fi + ans.se) % n); for (auto tt : t.se) printf(" %lld", tt); printf("\n"); } return 0; }
1237
H
Balanced Reversals
You have two strings $a$ and $b$ of equal even length $n$ consisting of characters 0 and 1. We're in the endgame now. To finally make the universe perfectly balanced, you need to make strings $a$ and $b$ equal. In one step, you can choose any prefix of $a$ of even length and reverse it. Formally, if $a = a_1 a_2 \ldots a_n$, you can choose a positive even integer $p \le n$ and set $a$ to $a_p a_{p-1} \ldots a_1 a_{p+1} a_{p+2} \ldots a_n$. Find a way to make $a$ equal to $b$ using at most $n + 1$ reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.
Unfortunately, solutions used by most participant are different from what I expected. Here is the intended solution that works in exactly $n+1$ reversals. Let's form string $b$ from right to left at the front of string $a$. For each $i = 2, 4, 6, \ldots, n$, we'll make some reversals so that $a[1..i] = b[n-i+1..n]$. For each $i$, we need to move the first $i-2$ characters by two characters to the right, and place some correct pair of characters at the front. Consider some pair of characters at positions $x$ and $x+1$, where $x \bmod 2 = 1$ and $x > i$. What if we perform two reversals: first, reverse prefix of length $x-1$, then, reverse prefix of length $x+1$? The answer is: characters $x$ and $x+1$ will move to the beginning of $a$ in reverse order, while all the other characters will not change their relative positions. OK, what if we need to put some pair $00$ or $11$ to the front? Then we can just pick any $00$ or $11$ pair to the right of position $i$ and move it to the front in two steps, that's easy enough. It becomes harder when we need some pair $01$ or $10$ to get to the front. We might not have a suitable corresponding $10$ or $01$ pair in store, so we might need to use three steps here. Let's call this situation undesirable. Let's get back to the initial situation. Suppose that the number of $01$ pairs in $a$ matches the number of $10$ pairs in $b$. Then we'll never get into an undesirable situation. Let's call this initial situation handy. What if these counts don't match? Then we can actually make them match using just one reversal. Specifically, pick a string out of $a$ and $b$ that has higher absolute difference of counts of $01$ and $10$, and it turns out, due to some monotonicity, that we can always find a prefix to reverse to make our initial situation handy. (Note that when I say that we can reverse a prefix in $b$, that's equivalent to reversing the same prefix in $a$ as the last reversal.) Thus, we can solve the problem in $n+1$ reversals: one reversal to make the initial situation handy, and then $n/2$ times we make at most two reversals each step without ever getting into an undesirable situation.
[ "constructive algorithms" ]
3,300
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; using pii = pair<int, int>; using pli = pair<ll, int>; using pll = pair<ll, ll>; #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int maxn = 4005; vector<int> ss, tt; char s[maxn], t[maxn]; int n; vector<int> answer; int cnt[5]; vector<int> prepare(char *s) { vector<int> ans; for (int i = 0; i < 2 * n; i += 2) ans.pb((s[i] - '0') * 2 + (s[i + 1] - '0')); return ans; } inline void addanswer(int x) { if (x <= 0) return; answer.pb(x); } void doreverse(vector<int> &v, int l) { reverse(v.begin(), v.begin() + l); for (int j = 0; j < l; j++) if (v[j] >= 1 && v[j] <= 2) { v[j] = 3 - v[j]; } } int main() { int NT; scanf("%d", &NT); for (int T = 0; T < NT; T++) { scanf("%s%s", s, t); n = strlen(s) / 2; ss = prepare(s); tt = prepare(t); for (auto &t : tt) if (t == 1 || t == 2) t = 3 - t; cnt[0] = cnt[1] = cnt[2] = cnt[3] = 0; for (auto t : ss) cnt[t]++; for (auto t : tt) cnt[t]--; if (cnt[0] != 0 || cnt[3] != 0) { printf("-1\n"); continue; } bool found = cnt[1] == 0; int before = -1; int after = -1; for (int i = 1; i <= n && !found; i++) { cnt[ss[i - 1]]--; cnt[3 - ss[i - 1]]++; if (cnt[1] == 0) { before = 2 * i; doreverse(ss, i); found = true; } } if (!found) { for (int i = 1; i <= n; i++) { cnt[ss[i - 1]]++; cnt[3 - ss[i - 1]]--; } } for (int i = 1; i <= n && !found; i++) { cnt[tt[i - 1]]++; cnt[3 - tt[i - 1]]--; if (cnt[1] == 0) { after = 2 * i; doreverse(tt, i); found = true; } } assert(found); answer.clear(); addanswer(before); for (int i = n - 1; i >= 0; i--) { int wh = -1; for (int j = n - 1 - i; j < n; j++) if (ss[j] == tt[i]) wh = j; addanswer(2 * wh); doreverse(ss, wh); addanswer(2 * wh + 2); doreverse(ss, wh + 1); } addanswer(after); for (auto t : answer) reverse(s, s + t); assert(strcmp(s, t) == 0); printf("%d ", (int)answer.size()); for (auto t : answer) printf("%d ", t); printf("\n"); } return 0; }
1238
A
Prime Subtraction
You are given two integers $x$ and $y$ (it is guaranteed that $x > y$). You may choose any prime integer $p$ and subtract it any number of times from $x$. Is it possible to make $x$ equal to $y$? Recall that a prime number is a positive integer that has exactly two positive divisors: $1$ and this integer itself. The sequence of prime numbers starts with $2$, $3$, $5$, $7$, $11$. Your program should solve $t$ independent test cases.
Let's denote the difference between $x$ and $y$ as $z$ ($z = x - y$). Then, if $z$ has a prime divisor $p$, we can subtract $p$ from $x$ $\frac{z}{p}$ times. The only positive integer that doesn't have any prime divisors is $1$. So, the answer is NO if and only if $x - y = 1$.
[ "math", "number theory" ]
900
t = int(input()) for i in range(t): x, y = map(int, input().split()) if(x - y > 1): print('YES') else: print('NO')
1238
B
Kill `Em All
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point $x = 0$ is where these parts meet. The right part of the corridor is filled with $n$ monsters — for each monster, its initial coordinate $x_i$ is given (and since all monsters are in the right part, every $x_i$ is positive). The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes \textbf{less than or equal} to $0$), it gets instantly killed by a trap. The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point $c$. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be $y$, then: - if $c = y$, then the monster is killed; - if $y < c$, then the monster is pushed $r$ units to the left, so its current coordinate becomes $y - r$; - if $y > c$, then the monster is pushed $r$ units to the right, so its current coordinate becomes $y + r$. Ivan is going to kill the monsters as follows: choose some integer point $d$ and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on. What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally. You have to answer $q$ independent queries.
Notice the following fact: it's never optimal to fire a missile at such a position that there are monsters to the right of it. That suggests the next solution: sort the positions, leave only the unique ones and process to shoot at the rightmost alive monster until every monster is dead. Position of some monster after $s$ shots are made is the original position minus $r \cdot s$, because the monster could only be pushed to the left. Overall complexity: $O(n \log n)$.
[ "greedy", "sortings" ]
1,300
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) const int N = 100 * 1000 + 13; int n, r; int a[N]; void solve() { scanf("%d%d", &n, &r); forn(i, n) scanf("%d", &a[i]); sort(a, a + n); n = unique(a, a + n) - a; int ans = 0; for (int i = n - 1; i >= 0; i--) ans += (a[i] - ans * r > 0); printf("%d\n", ans); } int main() { int q; scanf("%d", &q); forn(i, q) solve(); }
1238
C
Standard Free2play
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height $h$, and there is a moving platform on each height $x$ from $1$ to $h$. Each platform is either hidden inside the cliff or moved out. At first, there are $n$ moved out platforms on heights $p_1, p_2, \dots, p_n$. The platform on height $h$ is moved out (and the character is initially standing there). If you character is standing on some moved out platform on height $x$, then he can pull a special lever, which switches the state of \textbf{two platforms: on height $x$ and $x - 1$}. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. \textbf{Note that this is the only way to move from one platform to another}. Your character is quite fragile, so it can safely fall from the height no more than $2$. In other words falling from the platform $x$ to platform $x - 2$ is okay, but falling from $x$ to $x - 3$ (or lower) is certain death. Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height $h$, which is unaffected by the crystals). After being used, the crystal disappears. What is the minimum number of magic crystal you need to buy to safely land on the $0$ ground level?
You are given the input data in compressed format, let's decompress it in binary string, where the $i$-th character is 0 if the $i$-th platform is hidden and 1 otherwise. For, example, the third query is 101110011. Let's look how our string changes: if we had ...01... then after pulling the lever it becomes ...10... and if we had ...111... then we'd get ...100... (The underlined index is the platform we are currently on). So it looks like we are standing on 1 and move it to the left until it clashes with the next one. So we can determine that we should look only at subsegments on 1-s. Now we can note, that the "good" string should have all subsegments of ones with even length except two cases: the subsegment that starts from $h$ should have odd length and subsegment, which ends in $1$ can have any length. Now we can say, that the answer is equal to number of subsegments which doesn't match the pattern of the "good string", since we can fix each subsegment with one crystal. And we can prove that it's optimal since the only way to fix two subsegments with one crystal is to merge them but it does not help. Finally, we can understand that we have no need in decompressing the input and can determine subsegments of ones straightforwardly.
[ "dp", "greedy", "math" ]
1,600
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second const int INF = int(1e9); int h, n; vector<int> p; inline bool read() { if(!(cin >> h >> n)) return false; p.resize(n); fore(i, 0, n) cin >> p[i]; return true; } inline void solve() { int ans = 0; int lf = 0; fore(i, 0, n) { if (i > 0 && p[i - 1] > p[i] + 1) { if (lf > 0) ans += (i - lf) & 1; else ans += 1 - ((i - lf) & 1); lf = i; } } if (p[n - 1] > 1) { if (lf != 0) ans += (n - lf) & 1; else ans += 1 - ((n - lf) & 1); } cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int tc; cin >> tc; while(tc--) { read(); solve(); } return 0; }
1238
D
AB-string
The string $t_1t_2 \dots t_k$ is good if each letter of this string belongs to at least one palindrome of length \textbf{greater} than 1. A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not. Here are some examples of good strings: - $t$ = AABBB (letters $t_1$, $t_2$ belong to palindrome $t_1 \dots t_2$ and letters $t_3$, $t_4$, $t_5$ belong to palindrome $t_3 \dots t_5$); - $t$ = ABAA (letters $t_1$, $t_2$, $t_3$ belong to palindrome $t_1 \dots t_3$ and letter $t_4$ belongs to palindrome $t_3 \dots t_4$); - $t$ = AAAAA (all letters belong to palindrome $t_1 \dots t_5$); You are given a string $s$ of length $n$, consisting of \textbf{only} letters A and B. You have to calculate the number of good substrings of string $s$.
Instead of counting the number of good substrings, let's count the number of bad substrings $cntBad$, then number of good substrings is equal to $\frac{n(n+1)}{2} - cntBad$. Let's call a character $t_i$ in string $t_1t_2 \dots t_k$ is bad if there is no such palindrome $t_lt_{l+1} \dots t_r$ that $l \le i \le r$. Any character in substring $t_2t_3 \dots t_{k-1}$ is good. It can be proven as follows. If $t_i = t_{i+1}$ or $t_i = t_{i-1}$ then $t_i$ belong to a palindrome of length 2. If $t_i \neq t_{i+1}$ and $t_i \neq t_{i-1}$ then $t_i$ belong to a palindrome $t_{i-1} \dots t_{i+1}$. So only characters $t_1$ and $t_k$ can be bad. But at the same time character $t_1$ is bad if there is no character $t_i$ such that $i > 1$ and $t_i = t_1$. It is true because substring $t_1t_2 \dots t_i$ is palindrome (index $i$ is minimum index such that $t_i = t_1$). So, there are only 4 patterns of bad strings: $ABB \dots BB$; $BAA \dots AA$; $AA \dots AAB$; $BB \dots BBA$; All that remains is to count the number of substrings of this kind.
[ "binary search", "combinatorics", "dp", "strings" ]
1,900
n = int(input()) s = input() res = n * (n - 1) // 2 for x in range(2): cur = 1 for i in range(1, n): if s[i] == s[i - 1]: cur += 1 else: res -= cur - x cur = 1 s = s[::-1] print(res)