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
1801
G
A task for substrings
Philip is very fond of tasks on the lines. He had already solved all the problems known to him, but this was not enough for him. Therefore, Philip decided to come up with his own task.To do this, he took the string $t$ and a set of $n$ strings $s_1$, $s_2$, $s_3$, ..., $s_n$. Philip has $m$ queries, in the $i$th of them, Philip wants to take a substring of the string $t$ from $l_i$th to $r_i$th character, and count the number of its substrings that match some string from the set. More formally, Philip wants to count the number of pairs of positions $a$, $b$, such that $l_i \le a \le b \le r_i$, and the substring of the string $t$ from $a$th to $b$th character coincides with some string $s_j$ from the set. A substring of the string $t$ from $a$th to $b$th character is a string obtained from $t$ by removing the $a - 1$ character from the beginning and $|t| - b$ characters from the end, where $|t|$ denotes the length of the string $t$. Philip has already solved this problem, but can you?
Let's use the Aho-Korasik structure to store strings from $S$. Let's build compressed suffix links on it. This way it is a little more optimal to find all the lines from $S$ ending in this position $t$. Denote by $pref[i]$ the number of substrings of $S$ in the prefix $t$ of length $i$. Denote by $suf[i]$ the number of substrings of $S$ in the suffix $t$ starting from the position $i$. Note that $pref[r] + suf[l] - priv[|T|]$ is equal to the number of substrings of the string for $t$ from $S$ on the segment $[l, p]$ minus the number of substrings of $t$ from $S$ that begin before $l$ and end later than $r$. For each query, we will find a substring $t$ that matches $s_i$, which covers the string $t[l, r]$ and ends as close as possible to $r$. If there is no such thing, then the answer can be calculated using the previous formula. Otherwise, $t[l, r]$ is invested in $s_i[l', r']$. At the same time, there are no substrings of $S$ in the string $s_i$ that begin before $l'$ and end later than $r'$. To get the answer, we apply the previous formula with the string $s_i$ and the sub-section $[l', r']$. Asymptotics: $O(S+ t +m \log m)$
[ "data structures", "string suffix structures", "strings" ]
3,400
#include <bits/stdc++.h> #define x first #define y second using namespace std; struct node { int nx[26]; int p; int pp; int len; int id; int cnt; bool term; node() : p(-1), pp(-1), len(0), id(-1), term(false), cnt(0) { for (int i = 0; i < 26; i++) { nx[i] = -1; } } }; vector<node> g; vector<string> s[2]; string t[2]; vector<vector<long long>> c[2], pid[2]; vector<long long> tc[2]; int add(int a, char c) { c -= 'a'; if (g[a].nx[c] == -1) { g[a].nx[c] = g.size(); g.emplace_back(); g.back().len = g[a].len + 1; } return g[a].nx[c]; } void build_aho(int a) { vector<pair<int, int>> q; for (int i = 0; i < 26; i++) { if (g[a].nx[i] == -1) { g[a].nx[i] = a; } else { q.emplace_back(a, i); } } int qb = 0; while (qb < q.size()) { int b = q[qb].x; int i = q[qb].y; qb++; int v = g[b].nx[i]; int c = g[b].p; if (g[v].term) { // bug in c != -1 g[v].cnt = 1; } if (c == -1) { g[v].p = a; g[b].pp = -1; } else { g[v].p = g[c].nx[i]; if (g[v].term) { g[v].pp = v; } else { g[v].pp = g[g[v].p].pp; } g[v].cnt += g[g[v].p].cnt; } for (int i = 0; i < 26; i++) { if (g[v].nx[i] == -1) { g[v].nx[i] = g[g[v].p].nx[i]; } else { q.emplace_back(v, i); } } } } vector<vector<pair<int, int>>> ts; vector<int> qlen; priority_queue<pair<int, int>> h; vector<long long> ans; long long get_ans(int rdst, int len, vector<long long>& a, vector<long long>& b, bool substr) { int l = a.size() - 1 - rdst; int r = l + len; long long cnt = a[r] + b[a.size() - 1 - l] - a.back(); if (substr && l == 0 && r == a.size() - 1) { cnt++; } return cnt; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; g.emplace_back(); g.emplace_back(); s[0].resize(n); s[1].resize(n); c[0].resize(n); c[1].resize(n); pid[0].resize(n); pid[1].resize(n); ans.resize(m); cin >> t[0]; t[1] = t[0]; reverse(t[1].begin(), t[1].end()); ts.resize(t[0].size()); for (int i = 0; i < n; i++) { cin >> s[0][i]; } sort(s[0].begin(), s[0].end(), \ [](const string& a, const string& b) { return a.size() < b.size(); }); for (int i = 0; i < n; i++) { s[1][i] = s[0][i]; reverse(s[1][i].begin(), s[1][i].end()); for (int e = 0; e < 2; e++) { int a = e; for (auto j : s[e][i]) { a = add(a, j); } g[a].term = true; g[a].id = i; } } build_aho(0); build_aho(1); for (int e = 0; e < 2; e++) { tc[e].resize(t[0].size() + 1); int a = e; for (int i = 0; i < t[0].size(); i++) { a = g[a].nx[t[e][i] - 'a']; tc[e][i + 1] = tc[e][i] + g[a].cnt; } for (int i = 0; i < n; i++) {; c[e][i].resize(s[0][i].size() + 1); pid[e][i].resize(s[0][i].size() + 1, -1); int a = e; for (int j = 0; j < s[e][i].size(); j++) { a = g[a].nx[s[e][i][j] - 'a']; c[e][i][j + 1] = c[e][i][j] + g[a].cnt; if (g[a].term) { // bug always pid[e][i][j + 1] = g[a].id; } } for (int j = (int)s[e][i].size() - 1; j >= 0; j--) { // bug forget if (pid[e][i][j] == -1) { pid[e][i][j] = pid[e][i][j + 1]; } } c[e][i].back()--; // bug forget string itself } } for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; a--; ts[b - 1].emplace_back(a, i); qlen.emplace_back(b - a); } int a = 0; for (int i = 0; i < t[0].size(); i++) { // cout << i << ' ' << t[0][i] << '\n'; for (auto j : ts[i]) { h.emplace(j); } a = g[a].nx[t[0][i] - 'a']; if (g[a].pp != -1) { // bug ignore int id = g[g[a].pp].id; int bg = i + 1 - (int)s[0][id].size(); while (h.size() > 0 && h.top().x >= bg) { int rdst = i - h.top().x + 1; int nid = pid[1][id][rdst]; // bug forget // cout << h.top().x << ' ' << h.top().y << ' ' << rdst << ' ' << nid << '\n'; ans[h.top().y] = get_ans(rdst, qlen[h.top().y], c[0][nid], c[1][nid], true); h.pop(); } } } while (h.size() > 0) { // cout << h.top().x << ' ' << h.top().y << '\n'; ans[h.top().y] = get_ans(t[0].size() - h.top().x, qlen[h.top().y], tc[0], tc[1], false); h.pop(); } for (auto i : ans) { cout << i << ' '; } cout << '\n'; }
1802
A
Likes
Nikita recently held a very controversial round, after which his contribution changed very quickly. The announcement hung on the main page for $n$ seconds. In the $i$th second $|a_i|$th person either liked or removed the like (Nikita was lucky in this task and there are no dislikes). If $a_i > 0$, then the $a_i$th person put a like. If $a_i < 0$, then the person $-a_i$ removed the like. \textbf{Each person put and removed the like no more than once. A person could not remove a like if he had not put it before.} Since Nikita's contribution became very bad after the round, he wanted to analyze how his contribution changed while the announcement was on the main page. He turned to the creator of the platform with a request to give him the sequence $a_1, a_2, \ldots, a_n$. But due to the imperfection of the platform, the sequence $a$ was shuffled. You are given a shuffled sequence of $a$ that describes user activity. You need to tell for each moment from $1$ to $n$ what the maximum and minimum number of likes could be on the post at that moment.
Let's show a construction that maximizes the number of likes. We need to first leave all the likes that we can put, and only then delete them. To minimize the number of likes, we need to delete the like (if we can) immediately after we post it. The code below implements these constructs.
[ "greedy", "implementation" ]
800
#include "bits/stdc++.h" using namespace std; void solve() { int n; cin >> n; int likes = 0, dislikes = 0; for (int i = 0; i < n; i++) { int x; cin >> x; if (x > 0) likes++; else dislikes++; } for (int i = 1; i <= n; ++i) { if (i <= likes) cout << i << ' '; else cout << likes * 2 - i << ' '; } cout << '\n'; for (int i = 1; i <= n; ++i) { if (i <= dislikes * 2) cout << i % 2 << ' '; else cout << (i - dislikes * 2) << ' '; } cout << '\n'; } signed main() { int t = 1; cin >> t; for (int i = 1; i <= t; ++i) { solve(); } return 0; }
1804
A
Lame King
You are given a checkerboard of size $201 \times 201$, i. e. it has $201$ rows and $201$ columns. The rows of this checkerboard are numbered from $-100$ to $100$ from bottom to top. The columns of this checkerboard are numbered from $-100$ to $100$ from left to right. The notation $(r, c)$ denotes the cell located in the $r$-th row and the $c$-th column. There is a king piece at position $(0, 0)$ and it wants to get to position $(a, b)$ as soon as possible. In this problem our king is lame. Each second, the king makes exactly one of the following five moves. - Skip move. King's position remains unchanged. - Go up. If the current position of the king is $(r, c)$ he goes to position $(r + 1, c)$. - Go down. Position changes from $(r, c)$ to $(r - 1, c)$. - Go right. Position changes from $(r, c)$ to $(r, c + 1)$. - Go left. Position changes from $(r, c)$ to $(r, c - 1)$. King is \textbf{not allowed} to make moves that put him outside of the board. The important consequence of the king being lame is that he is \textbf{not allowed} to make the same move during two consecutive seconds. For example, if the king goes right, the next second he can only skip, go up, down, or left.What is the minimum number of seconds the lame king needs to reach position $(a, b)$?
Observation 1. Let $|a| = |b|$. The king can reach $(a, b)$ in $2 \cdot |a|$ moves by alternating moves along rows and moves along columns. Observation 2. Let $|a| \ne |b|$, in particular $a > b \geq 0$ (without loss of generality due to the board symmetry). The king can reach $(a, b)$ in $2a - 1$ moves. He moves towards $a$ on turns $1, 3, 5, \ldots, 2a - 1$. The remaining $a - 1$ moves are enough to reach $b$. Finally, the remaining slots can be filled with "skip" moves. Thus, the answer is $|a| + |b|$ if $|a| = |b|$ and $2 \cdot \max(|a|, |b|) - 1$ otherwise.
[ "greedy", "math" ]
800
null
1804
B
Vaccination
Ethan runs a vaccination station to help people combat the seasonal flu. He analyses the historical data in order to develop an optimal strategy for vaccine usage. Consider there are $n$ patients coming to the station on a particular day. The $i$-th patient comes at the moment $t_i$. We know that each of these patients can be asked to wait for no more than $w$ time moments. That means the $i$-th patient can get vaccine at moments $t_i, t_i + 1, \ldots, t_i + w$. Vaccines come in packs, each pack consists of $k$ doses. Each patient needs exactly one dose. Packs are stored in a special fridge. After a pack is taken out of the fridge and opened, it can no longer be put back. The lifetime of the vaccine outside the fridge is $d$ moments of time. Thus, if the pack was taken out of the fridge and opened at moment $x$, its doses can be used to vaccinate patients at moments $x, x + 1, \ldots, x + d$. At moment $x + d + 1$ all the remaining unused doses of this pack are thrown away. Assume that the vaccination station has enough staff to conduct an arbitrary number of operations at every moment of time. What is the minimum number of vaccine packs required to vaccinate all $n$ patients?
Observation 1. There exists an optimal answer where each pack of vaccine is used for a consecutive segment of patients. Indeed, if there are three patients $a < b < c$ such that $a$ and $c$ are vaccinated using the dose from one pack and $b$ is vaccinated using the dose from the other pack we can swap the packs used for $b$ and $c$ and the answer will still be valid. Observation 2. It always makes sense to ask new patients to wait as long as possible before opening a new pack. From these two observations we derive a very easy strategy. Consider patients one by one in order of non-decreasing $t_i$. If we consider some patient $i$ and there is an open pack that still valid and still has some doses remaining, use it immediately. If there is no valid open pack of vaccines and there is no one waiting, ask patient $i$ to wait till $t_i + w$ moment of time. If there is no valid pack of vaccines, but there is someone already waiting for moment $x$, ask patient $i$ to wait for moment $x$ as well. As a courtesy to our participants the values of $d$ and $w$ are limited by $10^6$ to avoid a potential overflow of a signed 32-bit integer type.
[ "greedy", "implementation" ]
1,000
null
1804
C
Pull Your Luck
While James is gone on business, Vesper takes her time and explores what the legendary Casino Royale has to offer to people who are fond of competitive programming. Her attention was grabbed by the very new "Pull Your Luck" roulette which functions in a pretty peculiar way. The roulette's wheel consists of $n$ sectors number from $0$ to $n - 1$. There is no ball and the winning sector is determined by a static arrow pointing to one of the sectors. Sectors' indexes go in the natural order and the wheel always spins in the direction of indexes increment. That means that sector $i + 1$ goes right after sector $i$ for all $i$ from $0$ to $n - 2$, and sector $0$ goes right after sector $n - 1$. After a bet is made, the player is allowed to pull the triggering handle herself and cause the wheel to spin. If the player's initial pull is made with the force equal to positive integer $f$, the wheel will spin for $f$ seconds. During the first second it will advance $f$ sectors, the next second it will advance $f - 1$ sectors, then $f - 2$ sectors, and so on until it comes to a complete stop. After the wheel comes to a complete stop, the sector which the arrow is pointing to is the winning one. The roulette's arrow currently points at sector $x$. Vesper knows that she can pull the handle with any integer force from $1$ to $p$ inclusive. Note that it is not allowed to pull the handle with force $0$, i. e. not pull it all. The biggest prize is awarded if the winning sector is $0$. Now Vesper wonders if she can make sector $0$ win by pulling the triggering handle exactly once?
Assuming the constraint on the the sum of $n$ over all test cases we might want to simulate the process for each test case. However, we need an $O(n)$ (or other quasilinear complexity) solution. The key observation is that the sum of all integers from $1$ to $2n$ inclusive is divisible by $n$. Indeed, $\sum_{i = 1}^{2n} i = \frac{(2n + 1) \cdot 2n}{2} = (2n + 1) \cdot n$. As the remainders of $x$ of modulo $n$ will repeat after $2n$ steps there is no point in trying values of $x$ for more than $\min(2n, p)$. Question, can you build the test that required Vesper to use $x$ more than $100k$? There is exactly one such test.
[ "brute force", "greedy", "math", "number theory" ]
1,500
null
1804
D
Accommodation
Annie is an amateur photographer. She likes to take pictures of giant residential buildings at night. She just took a picture of a huge rectangular building that can be seen as a table of $n \times m$ windows. That means that the building has $n$ floors and each floor has exactly $m$ windows. Each window is either dark or bright, meaning there is light turned on in the room behind it. Annies knows that each apartment in this building is either one-bedroom or two-bedroom. Each one-bedroom apartment has exactly one window representing it on the picture, and each two-bedroom apartment has exactly two \textbf{consecutive} windows on the same floor. Moreover, the value of $m$ is guaranteed to be divisible by $4$ and it is known that each floor has exactly $\frac{m}{4}$ two-bedroom apartments and exactly $\frac{m}{2}$ one-bedroom apartments. The actual layout of apartments is unknown and can be different for each floor. Annie considers an apartment to be occupied if \textbf{at least one} of its windows is bright. She now wonders, what are the minimum and maximum possible number of occupied apartments if judged by the given picture? Formally, for each of the floors, she comes up with some particular apartments layout with exactly $\frac{m}{4}$ two-bedroom apartments (two consecutive windows) and $\frac{m}{2}$ one-bedroom apartments (single window). She then counts the total number of apartments that have at least one bright window. What is the minimum and maximum possible number she can get?
The number of one-bedroom and two-bedroom apartments is the same for each floor and each floor can have its own independent apartments layout. Thus, we can independently solve the problem for each floor and then just sum the results. Below is given the solution for one floor in $O(m)$ time. First, lets introduce some variables. $B$ is the total number of bright windows. $D$ is the total number of dark windows. $O_0$ is the number of one-bedroom apartments that are not occupied ($0$ bright windows). $O_1$ is the number of one-bedroom apartments that are occupied ($1$ bright window). $T_0$ is the number of two-bedroom apartments that are not occupied ($0$ bright windows). $T_1$ is the number of two-bedroom apartments that are occupied and have $1$ bright window. $T_2$ is the number of two-bedroom apartments that are occupied and have $2$ bright windows. $A$ is the total number of occupied apartments. We know that $A = O_1 + T_1 + T_2$ and $B = O_1 + T_1 + 2 \cdot T_2$. Thus, $A = B - T_2$, so in order to minimize the number of occupied apartments we need to maximize $T_2$ and vice versa. Maximizing $T_2$ is easier, you just determine the length of all maximal segments of bright windows, denote these lengths as $l_0, l_1, l_2, \ldots, l_x$. Then you pack each segment with as many two-bedroom apartments as possible. So, the maximum possible value of $T_2 = \min(\sum_{i = 0}^{x} \lfloor \frac{l_i}{2} \rfloor, \frac{m}{4}$. Here we must note the importance of having exactly $\frac{m}{4}$ two-bedroom apartments and exactly $\frac{m}{2}$ one-bedroom apartments. If the actual number of apartments of each type was given in the input we won't be able to guarantee the value of $T_2$ defined above. It could be the case that it is not actually possible to place all the remaining apartments and close the gaps between the placement of two-bedroom apartments with two bright windows. However, as we have $\frac{m}{2}$ one-bedroom apartments we can guarantee that such a placement is always possible. Now we would like to minimize $T_2$. Actually, we will do it in exactly the same way as the maximization, but instead of taking maximal segments of bright windows, we will find and use maximal segments that have at least one dark window and do not have two consecutive bright windows. Denote the lengths of such maximal segments as $l'_0, l'_1, l'_2, \ldots, l'_y$. Then, the minimum possible $T_2 = \min(0, \frac{m}{4} - \sum_{i=0}^{y} \lfloor \frac{l'_i}{2} \rfloor)$. Again, thanks to $\frac{m}{2}$ one-bedroom apartments we will be able to fill all the gaps and achieve the desired placement.
[ "brute force", "dp", "greedy", "implementation" ]
2,000
null
1804
E
Routing
Ada operates a network that consists of $n$ servers and $m$ direct connections between them. Each direct connection between a pair of distinct servers allows bidirectional transmission of information between these two servers. Ada knows that these $m$ direct connections allow to directly or indirectly transmit information between any two servers in this network. We say that server $v$ is a neighbor of server $u$ if there exists a direct connection between these two servers. Ada needs to configure her network's WRP (Weird Routing Protocol). For each server $u$ she needs to select exactly one of its neighbors as an auxiliary server $a(u)$. After all $a(u)$ are set, routing works as follows. Suppose server $u$ wants to find a path to server $v$ (different from $u$). - Server $u$ checks all of its direct connections to other servers. If it sees a direct connection with server $v$, it knows the path and the process terminates. - If the path was not found at the first step, server $u$ asks its auxiliary server $a(u)$ to find the path. - Auxiliary server $a(u)$ follows this process starting from the first step. - After $a(u)$ finds the path, it returns it to $u$. Then server $u$ constructs the resulting path as the direct connection between $u$ and $a(u)$ plus the path from $a(u)$ to $v$. As you can see, this procedure either produces a correct path and finishes or keeps running forever. Thus, it is critically important for Ada to configure her network's WRP properly. Your goal is to assign an auxiliary server $a(u)$ for each server $u$ in the given network. Your assignment should make it possible to construct a path from any server $u$ to any other server $v$ using the aforementioned procedure. Or you should report that such an assignment doesn't exist.
A directed graph where each node has an out-degree equal to $1$ (exactly one arc starts at this node) is called functional. By setting auxiliary servers $a(v)$ for each server $v$ we define a functional graph. The following condition is necessary and sufficient. The answer exists if and only if there exists a functional graph defined by $a(v)$ that contains a cycle $C$ such that $N_G(C) = V(G)$. That means that each node should be neighbouring to at least one node of this cycle in the original graph. Note that cycles of length $1$ are not allowed as $a(v) \ne v$ by definition. The proof is easy. If such a cycle $C$ exists we can reconstruct all other $a(v)$ to lead to this cycle. This will allow WRP to construct a path to each server after the procedure gets to the cycle. If such a cycle doesn't exists, we can pick any node of any cycle (functional graph always has at least one) and some servers will be unreachable from it. Wow we need to find a cycle of length $\geq 2$ such that each server belongs to this cycle or is directly connected to at least one server of the cycle. First we run a dynamic programming similar to Hamiltonian path and identify all the subsets of servers that can form a cycle. This will take $O(2^n \cdot n^2)$ if we use the following meaning of $d(m, v)$. $d(m, v) = 0$ if there exists a path that starts from node $u$, visits all nodes of a subset defined by bitmask $m$ and ends in node $v$. Here node $u$ is the node with minimum index in subset $m$, as you can always pick the minimum-indexed node as the beginning of the cycle. After we compute $d(m, v)$ we take all $m$ such that there exists $d(m, v) = 1$ and check whether $N_G(m) = V(G)$. This can be done in $O(2^n \cdot n^2)$ as well. Thus, the overall complexity is $O(2^n \cdot n^2)$.
[ "bitmasks", "brute force", "dfs and similar", "dp", "graphs" ]
2,400
null
1804
F
Approximate Diameter
Jack has a graph of $n$ vertices and $m$ edges. All edges are bidirectional and of unit length. The graph is connected, i. e. there exists a path between any two of its vertices. There can be more than one edge connecting the same pair of vertices. The graph can contain self-loops, i. e. edges connecting a node to itself. The distance between vertices $u$ and $v$ is denoted as $\rho(u, v)$ and equals the minimum possible number of edges on a path between $u$ and $v$. The diameter of graph $G$ is defined as the maximum possible distance between some pair of its vertices. We denote it as $d(G)$. In other words, $$d(G) = \max_{1 \le u, v \le n}{\rho(u, v)}.$$ Jack plans to consecutively apply $q$ updates to his graph. Each update adds exactly one edge to the graph. Denote as $G_i$ the graph after exactly $i$ updates are made. Jack wants to calculate $q + 1$ values $d(G_0), d(G_1), d(G_2), \ldots, d(G_q)$. However, Jack suspects that finding the exact diameters of $q + 1$ graphs might be a difficult task, so he is fine with approximate answers that differ from the correct answers no more than twice. Formally, Jack wants to find a sequence of positive integers $a_0, a_1, a_2, \ldots, a_q$ such that $$\left\lceil \frac{d(G_i)}{2} \right\rceil \le a_i \le 2 \cdot d(G_i)$$ for each $i$. \textbf{Hacks} You cannot make hacks in this problem.
Let's recall some definitions to start with. $\rho_G(u, v)$ is the length of the shortest path between vertices $u$ and $v$ in graph $G$. Define as $c_G(u)$ the maximum distance from vertex $u$ to some other vertex of graph $G$. $c_G(u) = \max_{v \in V(G)} \rho(u, v)$. $d(G) = \max_{u, v \in V(G)} \rho(u, v) = \max_{u \in V(G)} c_G(u)$ is called the diameter of graph $G$. It is the maximum distance between some pair of vertices of graph $G$. $r(G) = \min_{u \in V(G)} \max_{v \in V(G)} \rho(u, v) = \min_{u \in V(G)} c(u)$ is called the radius of graph $G$. It is the minimum possible distance from one vertex of the graph to the farthest from it vertex of this graph. The key inequality we will use for this problem solution is the following. Let $v$ be arbitrary vertex of graph $G$. $\frac{d(G)}{2} \leq r(G) \leq c_G(v) \leq d(G) \leq 2 \cdot r(G) \leq 2 \cdot c_G(v) \leq 2 \cdot d(G)$ $r(G) \leq c_G(v) \leq d(G)$ by definition. $d(G) \leq 2 \cdot r(G)$ because of triangle inequality. All other inequalities are derived from the first two items. The good thing is that we can compute $c_G(v)$ in linear time using BFS algorithm. Now we can solve the problem in $O(q \cdot (n + m + q))$ time. It is important to note that the task tolerates errors both ways, so any value between $c_{G_i}(v)$ and $2 \cdot c_{G_i}(v)$ will be a correct approximation of $d(G_i)$. The next key observation is that the sequence of $d_i(G)$ is non-increasing. If $i < j$ and $c_{G_i}(v) \leq 2 \cdot c_{G_j}(v)$ we can use $2 \cdot c_{G_j}(v)$ as an approximation for $d(G_{i + 1}), d(G_{i + 2}), \ldots, d(G_{j - 1})$. Using the idea above we can do one of the following. Having the correct value of $c_{G_i}(v)$ we can use the binary search to find the maximum $j$ such that $c_{G_i}(v) \leq 2 \cdot c_{G_j}(v)$ in $\log{q}$ iterations. Use divide&conquer with the stop condition $c_{G_l}(v) \leq 2 \cdot c_{G_r}(v)$. That would actually work a way more faster (up to five times) as it re-uses the information very efficiently. Thus, we have a solion that runs BFS no more than $\log{n} \cdot \log{q}$ times. The overall complexity is $O(\log{n} \cdot \log{q} \cdot (n + m + q))$. How did we get the correct answers for the checker? We precomputed them using the power of distributed computing. We are a cloud technology company after all! Bonus question, can you guess the total number of cpu-days we have used to compute all the answers? Post you version in the comments!
[ "binary search", "divide and conquer", "graphs", "shortest paths" ]
2,700
null
1804
G
Flow Control
Raj has a single physical network line that connects his office to the Internet. This line bandwidth is $b$ bytes per millisecond. There are $n$ users who would like to use this network line to transmit some data. The $i$-th of them will use the line from millisecond $s_i$ to millisecond $f_i$ inclusive. His initial data rate will be set to $d_i$. That means he will use data rate equal to $d_i$ for millisecond $s_i$, and then it will change according to the procedure described below. The flow control will happen as follows. Suppose there are $m$ users trying to transmit some data via the given network line during millisecond $x$. Denote as $t_i$ the data rate that the $i$-th of these $m$ users has at the beginning of this millisecond. All $t_i$ are non-negative integer values. - If $m = 0$, i. e. there are no users trying to transmit data during this millisecond, nothing happens. - If the sum of all $t_i$ is less than or equal to $b$, each active user successfully completes his transmission (the $i$-th active user transmits $t_i$ bytes). After that, the data rate of each active user grows by $1$, i. e. each $t_i$ is increased by $1$. - If the sum of all $t_i$ is greater than $b$, the congestion occurs and no data transmissions succeed this millisecond at all. If that happens, each $t_i$ decreases twice, i. e. each $t_i$ is replaced with $\lfloor \frac{t_i}{2} \rfloor$. Raj knows all the values $n$, $b$, $s_i$, $f_i$, and $d_i$, he wants to calculate the total number of bytes transmitted by all the users in the aggregate.
The problem is inspired by AIMD algorithm for TCP flow and congestion control. The key solution idea comes from a real-world networking, every time the congestion happens the difference between the maximum active $t_i$ and the minimum active $t_i$ halves. Thus, if all users were to start and to stop at the same time there will be no more than two distinct values of $t_i$ in just $\log C$ congestions. Here $C$ stands for the upper limit on values $d_i$ and $b$. Let's store all the unique values of active $t_i$ in a hash-map together with a supplementary information. Information we need is the sum of all $t_i$ right after the last congestion, the number of milliseconds past since the last congestion and so on. Using this information we can compute the time of the next congestion in $O(1)$. The processing of one congestion will work in $O(d)$ time where $d$ is the current number of distinct values of $t_i$. We also need to be able to merge two groups when congestion happens, this information will be used to process delete operations. That can be done using DSU with path compression and doesn't add much to the total complexity. We will call the period between two consecutive congestions an epoch. There are epochs of two types: general and repetitive. A repetitive epoch is an epoch that goes in exactly the same way as the previous epoch. That means no new users appear, no users turn off, the epoch starts with exactly the same values of $t_i$ as the previous epoch and gets to exactly the same state after the closest congestion happens. All other epochs are called general. Though the total number of epochs can be large (up to $\max(f_i)$), there will be no more than $n \log{C}$ general epochs. Indeed, if no users start or finish data transmission, the process will converge to a repetitive epoch in no more than $\log{C}$ congestions. Here, $C$ is the upper bound for $b$ and values $d_i$. Repetitive epochs contain no more than two distinct value of $t_i$, they can be identified and simulated efficiently. How do we simulate general epochs? There is no need to this efficiently, doing this in $O(d)$ ($d$ is the number of distinct $t_i$) will be efficient enough. One can prove this using amortized analysis with the following potential function. Let $d$ be the number of distinct values of $t_i$ and $t_0 < t_1 < \ldots < t_{d - 1}$ be the sequence of these values. $P(epoch) = d + \sum_{i = 0}^{d - 2} \log{(t_{i + 1} - t_i)}$. The total complexity is $O(n \log C + n \log n)$.
[ "data structures", "dsu", "implementation" ]
3,500
null
1804
H
Code Lock
Lara has a safe that is locked with a circle-shaped code lock that consists of a rotating arrow, a static circumference around the arrow, an input screen, and an input button. The circumference of the lock is split into $k$ equal sections numbered from $1$ to $k$ in clockwise order. Arrow always points to one of the sections. Each section is marked with one of the first $k$ letters of the English alphabet. No two sections are marked with the same letter. Due to the lock limitations, the safe's password is a string of length $n$ that consists of first $k$ letters of the English alphabet only. Lara enters the password by rotating the lock's arrow and pressing the input button. Initially, the lock's arrow points to section $1$ and the input screen is empty. In one second she can do one of the following actions. - Rotate the arrow one section clockwise. If the arrow was pointing at section $x < k$ it will now point at section $x + 1$. If the arrow was pointing at section $k$ it will now point at section $1$. - Rotate the arrow one section counter-clockwise. If the arrow was pointing at section $x > 1$ it will now point at section $x - 1$. If the arrow was pointing at section $1$ it will now point at section $k$. - Press the input button. The letter marked on the section that the arrow points to will be added to the content of the input screen. As soon as the content of the input screen matches the password, the safe will open. Lara always enters her password in the minimum possible time.Lara has recently found out that the safe can be re-programmed. She can take the first $k$ letters of the English alphabet and assign them to the sectors in any order she likes. Now she wants to re-arrange the letters in a way that will minimize the number of seconds it takes her to input the password. Compute this minimum number of seconds and the number of ways to assign letters, for which this minimum number of seconds is achieved. Two ways to assign letters to sectors are considered to be distinct if there exists at least one sector $i$ that is assigned different letters.
First, let's solve the task for the case of linear arrangement of letters instead of a circle. Then we will upgrade the solution. Let $c(x, y)$ be the number of positions $i$ of the password string $s$ such that $s_i = x$ and $s_{i + 1} = y$. In other words, $c(x, y)$ is the number of times Lara has to enter letter $y$ after entering letter $x$. We need to find any permutation of letters $p_0, p_1, p_2, \ldots, p_{k-1}$ of minimum cost. Integer $p_i$ stands for the index of the letter that will be placed at position $i$. The cost of a permutation is computed as $w(p) = \sum_{0 \leq i, j < k, i \ne j} c(p_i, p_j) \cdot |i - j|$. Pointwise weights are much more convenient to use rather than pairwise weights. Re-write the cost function as follows. $w(p) = \sum_{0 \leq i, j < k, i \ne j} c(p_i, p_j) \cdot |i - j| = \sum_{0 \leq i < j < k} (c(p_i, p_j) + c(p_j, p_i)) \cdot (j - i) = \sum_{i = 0}^{i < k} i \cdot (\sum_{j = 0}^{j < i} (c(p_j, p_i) + c(p_i, p_j)) - \sum_{j = i + 1}^{j < k} (c(p_j, p_i) + c(p_i, p_j)))$ Usage of pointwise weights allows us to obtain the permutation step by step from left to right. When we place the new element $x$ we only need to know the subset of all already placed elements and the optimal cost of the prefix. Define $d(mask)$ as the minimum total cost of a permutation prefix containing first $|mask|$ elements. The update function looks as follows. $d(mask) = \min_{x \in mask} (d(mask - x) + |mask| \cdot (\sum_{y \in mask, y \ne x} (c(y, x) + c(x, y)) - \sum_{y \not\in mask} (c(y, x) + c(x, y))))$ The above solution works in $O(2^n \cdot n)$. However, in can be updated to $O(2^n \cdot n)$ with some precomputations of the sums in the formula above. Now we need to learn how to apply the similar idea for a positioning on a circle. The cost function now looks as follows. $w(p) = \sum_{0 \leq i, j < k, i \ne j} c(p_i, p_j) \cdot \min(|i - j|, k - |i - j|) = \sum_{i = 0}^{k - 1} pw(p, i)$ In order to write the cost function using pointwise weights we need to distinguish between two halves. The pointwise cost of an element in the first half is: $pw(p, i) = i \cdot \sum_{j = 0}^{j < i} (c(p_i, p_j) + c(p_j, p_i)) - i \cdot \sum_{j = i + 1}^{j \leq i + \lfloor \frac{k}{2} \rfloor} (c(p_i, p_j) + c(p_j, p_i)) + (i + n) \cdot \sum_{j = i + \lfloor \frac{k}{2} \rfloor + 1}^{k - 1} (c(p_i, p_j) + c(p_j, p_i))$ Similarly, the poinwise cost of an element in the second half is: $pw(p, i) = -i \cdot \sum_{j = 0}^{j < i - \lfloor \frac{k}{2} \rfloor} (c(p_i, p_j) + c(p_j, p_i)) + i \cdot \sum_{j = i - \lfloor \frac{k}{2} \rfloor}^{j < i} (c(p_i, p_j) + c(p_j, p_i)) - i \cdot \sum_{j = i + 1}^{k - 1} (c(p_i, p_j) + c(p_j, p_i))$ The above formulas show that it makes sense to first split all elements in two parts: left and right halves of the circle. Then we will alternate steps in adding one element to the first unoccupied position of the left part, then to the first unoccupied position of the right part. This way we will always be able to compute the value of a pointwise cost function. So we compute the dynamic programming $d(S, M)$, where $S$ is the subset identifying the way to split the set of all letters in two equal (or almost equal for the case of odd size) parts, and $M$ is the subset of already added elements. Elements $S \cap M$ are placed at the beginning of the first half and elements $\overline{S} \cap M$ are placed at the beginning of the second half. The simpliest complexity estimation is $O(4^n \cdot n)$. However, we should consider the following optimizations. We only use $|S| = \lceil \frac{k}{2} \rceil$. We only use states such that $|S \cap M| = |\overline{S} \cap M|$ or $|S \cap M| = |\overline{S} \cap M| + 1$. The character $s_0$ is always located at the first sector of the code lock, so Lara doesn't have to make any moves to enter the first character of her password. Thus, we only consider $s_0 \in S$ and $s_0 \in M$. Considering all the above optimizations we end up with only $82818450 \approx 83 \cdot 10^6$ states. The problem statement asks you to compute the number of permutations as well. That doesn't add anything to the difficulty of this dynamic programming solution and is just used to cut away all the heuristic optimizations like annealing simulation.
[ "bitmasks", "dp" ]
3,300
null
1805
A
We Need the Zero
There is an array $a$ consisting of non-negative integers. You can choose an integer $x$ and denote $b_i=a_i \oplus x$ for all $1 \le i \le n$, where $\oplus$ denotes the bitwise XOR operation. Is it possible to choose such a number $x$ that the value of the expression $b_1 \oplus b_2 \oplus \ldots \oplus b_n$ equals $0$? It can be shown that if a valid number $x$ exists, then there also exists $x$ such that ($0 \le x < 2^8$).
Note that $(a_1 \oplus x) \oplus (a_2 \oplus x) \oplus ...$ equals $a_1 \oplus a_2 \oplus \ldots \oplus a_n$ if $n$ is even, or $a_1 \oplus a_2 \oplus \ldots \oplus a_n \oplus x$ if $n$ is odd. Then, if the length of the array is odd, you must print $\oplus$ of the whole array. And if the length is even, we can't change the value of the expression with our operation. It turns out that if $\oplus$ of the whole array is $0$, we can output any number, but otherwise there is no answer.
[ "bitmasks", "brute force" ]
800
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) xor = 0 for x in a: xor ^= x if xor == 0: print(0) else: if n % 2 == 1: print(xor) else: print(-1)
1805
B
The String Has a Target
You are given a string $s$. You can apply this operation to the string exactly once: choose index $i$ and move character $s_i$ to the beginning of the string (removing it at the old position). For example, if you apply the operation with index $i=4$ to the string "abaacd" with numbering from $1$, you get the string "aabacd". What is the lexicographically minimal$^{\dagger}$ string you can obtain by this operation? $^{\dagger}$A string $a$ is lexicographically smaller than a string $b$ of the same length if and only if the following holds: - in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
At first, note that the operation should be applied only to the position of the minimal element of the string (since the 1st position in the final string should always contain the minimal letter). Next, let the positions of the minimum letter are $a_1, a_2, \ldots, a_k$. Then we must apply the operation to the last position ($a_k$). Indeed, let us apply the operation to another occurrence: then the prefixes will coincide, and after that there will be a character that is equal to the minimal one if we applied the operation to $a_k$ and will not be equal to it otherwise, which contradicts the minimal string.
[ "greedy", "strings" ]
800
for _ in range(int(input())): n = int(input()) s = input() ind = s.rfind(min(s)) # Find the last ind such that s[ind] = min(s) print(s[ind] + s[:ind] + s[ind + 1:])
1805
C
Place for a Selfie
The universe is a coordinate plane. There are $n$ space highways, each of which is a straight line $y=kx$ passing through the origin $(0, 0)$. Also, there are $m$ asteroid belts on the plane, which we represent as open upwards parabolas, i. e. graphs of functions $y=ax^2+bx+c$, where $a > 0$. You want to photograph each parabola. To do this, for each parabola you need to choose a line that does not intersect this parabola and does not touch it. You can select the same line for different parabolas. Please find such a line for each parabola, or determine that there is no such line.
Let's find the answers for the parabolas one at a time. Suppose we are given a parabola $ax^2+bx+c$ and a line $kx$. Then their difference is the parabola $ax^2+(b-k)x+c$. In order for the line and the parabola not to intersect, the difference must never equal $0$, that is, the parabola $ax^2+(b-k)x+c$ must have no roots. And this is true only when the discriminant is less than $0$, that is, $(b-k)^2<4ac$. In this case, $a, b$ and $c$ are given to us, and we need to choose $k$. $(b-k)^2<4ac \Longrightarrow |b - k| < \sqrt{4ac} \Longrightarrow b - \sqrt{4ac} < k < b+\sqrt{4ac}$. Now let us have a list of straight line coefficients sorted in increasing order. We need to check if there is a coefficient that belongs to $[b - \sqrt{4ac}; b + \sqrt{4ac}]$. To do this, check the smallest number greater than $b$, and the largest number less than $b$. If one of these numbers satisfies the condition, then we have found the answer. If not, then there are definitely no suitable coefficients, because we took $2$ closest coefficients to the center of the segment. Note that in this solution, we don't need to use non-integer numbers, which is good for both the time and the absence of errors due to precision.
[ "binary search", "data structures", "geometry", "math" ]
1,400
#include <bits/stdc++.h> #define int long long using namespace std; void solve() { int n, m; cin >> n >> m; vector <int> lines(n); for (int i = 0; i < n; i++) { cin >> lines[i]; } sort(lines.begin(), lines.end()); for (int i = 0; i < m; i++) { int a, b, c; cin >> a >> b >> c; int ind = lower_bound(lines.begin(), lines.end(), b) - lines.begin(); if (ind < n && (lines[ind] - b) * (lines[ind] - b) < 4 * a * c) { cout << "YES\n" << lines[ind] << "\n"; continue; } if (ind > 0 && (lines[ind - 1] - b) * (lines[ind - 1] - b) < 4 * a * c) { cout << "YES\n" << lines[ind - 1] << "\n"; continue; } cout << "NO\n"; } } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); int q = 1; cin >> q; while (q--) { solve(); } return 0; }
1805
D
A Wide, Wide Graph
You are given a tree (a connected graph without cycles) with $n$ vertices. Consider a fixed integer $k$. Then, the graph $G_k$ is an undirected graph with $n$ vertices, where an edge between vertices $u$ and $v$ exists if and only if the distance between vertices $u$ and $v$ in the given tree is \textbf{at least} $k$. For each $k$ from $1$ to $n$, print the number of connected components in the graph $G_k$.
Find the diameter (the longest path) in the original tree. Now if the number $k$ is greater than the length of the diameter, then there will be no edges in the graph. Otherwise, the ends of this diameter are connected to each other, and possibly to other vertices as well. Then we can pre-calculate the answer for each $k$ in descending order. Let's maintain the set of vertices already reachable. Then for updating the answer for $k=x$ only vertices at a distance $x$ from one end of the diameter can be added to the answer.
[ "dfs and similar", "dp", "graphs", "greedy", "trees" ]
1,800
#include <bits/stdc++.h> #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() using namespace std; const int N = 1e5 + 228; vector<int> G[N]; void dfs(int v, int par, int h, vector<int> &d) { d[v] = h; for (int i : G[v]) { if (i != par) { dfs(i, v, h + 1, d); } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; G[a - 1].push_back(b - 1); G[b - 1].push_back(a - 1); } vector<int> d1(n), d2(n); dfs(0, -1, 0, d1); int a = max_element(all(d1)) - d1.begin(); dfs(a, -1, 0, d1); int b = max_element(all(d1)) - d1.begin(); dfs(b, -1, 0, d2); for (int i = 0; i < n; ++i) { d2[i] = max(d2[i], d1[i]); } sort(all(d2)); int ans = 0; for (int i = 1; i <= n; ++i) { while (ans < n && d2[ans] < i) { ++ans; } cout << min(n, ans + 1) << ' '; } cout << '\n'; }
1805
E
There Should Be a Lot of Maximums
You are given a tree (a connected graph without cycles). Each vertex of the tree contains an integer. Let's define the $\mathrm{MAD}$ (maximum double) parameter of the tree as the maximum integer that occurs in the vertices of the tree \textbf{at least} $2$ times. If no number occurs in the tree more than once, then we assume $\mathrm{MAD}=0$. Note that if you remove an edge from the tree, it splits into two trees. Let's compute the $\mathrm{MAD}$ parameters of the two trees and take the maximum of the two values. Let the result be the value of the deleted edge. For each edge, find its value. Note that we don't actually delete any edges from the tree, the values are to be found independently.
First, find $MAD$ of the initial tree. If each number in the tree occurs no more than once, then for each query the answer is $0$. Then, if $MAD$ occurs at least $3$ times in the tree, then for each query the answer will be $MAD$, because by pigeonhole principle there will be at least $2$ $MAD$ in one of the two trees. At last, in the case where $MAD$ occurs exactly $2$ times in the tree: if the deleted edge is not on the path between two occurrences of $MAD$, then the answer - $MAD$ of the whole tree. And for edges between entries, you need to maintain sets of values in each tree and traverse the edges, changing the sets accordingly.
[ "brute force", "data structures", "dfs and similar", "dp", "trees", "two pointers" ]
2,300
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 100; vector <pair <int, int>> g[N]; int val[N]; vector <int> ans; map <int, int> cnt1, cnt2; set <int> mad1, mad2; vector <int> path, path_ind; bool used[N]; bool dfs(int v, int tar) { used[v] = true; path.push_back(v); if (v == tar) { return true; } for (auto [i, ind] : g[v]) { if (!used[i]) { path_ind.push_back(ind); if (dfs(i, tar)) { return true; } path_ind.pop_back(); } } path.pop_back(); return false; } int mad() { int mx = 0; if (!mad1.empty()) { mx = max(mx, *mad1.rbegin()); } if (!mad2.empty()) { mx = max(mx, *mad2.rbegin()); } return mx; } void recalc(int v, int ban1, int ban2) { cnt1[val[v]]++; if (cnt1[val[v]] == 2) { mad1.insert(val[v]); } cnt2[val[v]]--; if (cnt2[val[v]] == 1) { mad2.erase(val[v]); } for (auto [i, _] : g[v]) { if (i != ban1 && i != ban2) { recalc(i, v, -1); } } } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; for (int i = 0; i < n - 1; i++) { int a, b; cin >> a >> b; a--, b--; g[a].emplace_back(b, i); g[b].emplace_back(a, i); } map <int, vector <int>> ind; for (int i = 0; i < n; i++) { cin >> val[i]; ind[val[i]].push_back(i); cnt2[val[i]]++; if (cnt2[val[i]] == 2) { mad2.insert(val[i]); } } while (!ind.empty() && ind.rbegin() -> second.size() == 1) { ind.erase(prev(ind.end())); } if (ind.empty()) { for (int i = 0; i < n - 1; i++) { cout << "0\n"; } return 0; } else if (ind.rbegin()->second.size() > 2) { for (int i = 0; i < n - 1; i++) { cout << ind.rbegin() -> first << "\n"; } return 0; } int a = ind.rbegin()->second[0], b = ind.rbegin()->second[1]; dfs(a, b); ans.assign(n - 1, ind.rbegin() -> first); recalc(path[0], path[1], -1); ans[path_ind[0]] = mad(); for (int i = 1; i + 1 < path.size(); i++) { recalc(path[i], path[i - 1], path[i + 1]); ans[path_ind[i]] = mad(); } for (int i : ans) { cout << i << "\n"; } return 0; }
1805
F2
Survival of the Weakest (hard version)
\textbf{This is the hard version of the problem. It differs from the easy one only in constraints on $n$. You can make hacks only if you lock both versions.} Let $a_1, a_2, \ldots, a_n$ be an array of non-negative integers. Let $F(a_1, a_2, \ldots, a_n)$ be the sorted in the non-decreasing order array of $n - 1$ smallest numbers of the form $a_i + a_j$, where $1 \le i < j \le n$. In other words, $F(a_1, a_2, \ldots, a_n)$ is the sorted in the non-decreasing order array of $n - 1$ smallest sums of all possible pairs of elements of the array $a_1, a_2, \ldots, a_n$. For example, $F(1, 2, 5, 7) = [1 + 2, 1 + 5, 2 + 5] = [3, 6, 7]$. You are given an array of non-negative integers $a_1, a_2, \ldots, a_n$. Determine the single element of the array $\underbrace{F(F(F\ldots F}_{n-1}(a_1, a_2, \ldots, a_n)\ldots))$. Since the answer can be quite large, output it modulo $10^9+7$.
Firstly, we will sort the array $a_1, a_2, \ldots, a_n$, and in the future we will always assume that all arrays in this problem are sorted. Let's solve the problem for $n \leq 200$. It may seem that with such constraints, the problem is solved quite trivially: we implement the function $F$ for $\mathcal{O}(n^2 \log n)$, and run it $n - 1$ times to get an answer. But there is one nuance, with each iteration of $F$, the numbers in the array can increase by $2$ times (for example, if the array consists entirely of identical numbers), which means that after only $40$ operations, we may have an overflow. Note that it is impossible to take the numbers by modulo in the function $F$ itself, since then the sorted order will be lost, and it will be impossible (or very difficult) to restore it using the remainder when dividing by $10^9 + 7$ instead of the numbers themselves. To avoid this, we note an important property of the function $F$: $F([a_1, a_2, \ldots, a_n]) = F([a_1 - x, a_2 - x, \ldots, a_n - x]) + x \cdot 2^{n-1}$ The intuition of this property is that if you subtract the same number from all the elements, then the relative order of the elements will not change, and will not change when using the $F$ function. Just after the first iteration of $F$, $2x$ will be subtracted from all the numbers, then $4x$, $8x$, etc., in the end, the original answer will be minus $x\cdot 2^{n-1}$. This property can be proved more strictly by induction on $n$. What does this wonderful property give us? Now we can subtract the same number $x$ from all the elements by first adding $x \cdot 2^{n-1}$ to the answer. It would be logical enough in any situation to subtract the minimum of the array from all its elements. Thanks to this, the minimum of the array will always be $0$, and now we can work only with arrays whose minimum element is $0$, which greatly simplifies our life. This is one of the two key ideas in this problem. So let's notice something interesting about the array $F([0, a_1, a_2, \ldots, a_n])$. Observation: $(F([0, a_1, a_2, \ldots, a_n]))_1 = a_1$. The proof is obvious (let me remind you that the array is sorted). Observation: $(F([0, a_1, a_2, \ldots, a_n]))_n \leq a_n$. Proof: since $[0, a_1, a_2, \ldots, a_n]$ has length $n + 1$, $F([0, a_1, a_2, \ldots, a_n])$ has length $n$. Among all pairs of array elements $[0, a_1, a_2, \ldots, a_n]$ there are $n$ pairs of the form $0 + a_i$, and $a_1 \leq a_2 \leq \ldots \leq a_n$. This means that the original array has $n$ pairs in which the sum is $\leq a_n$. So, observation is proved. These two observations give us that $F([0, a_1, a_2, \ldots, a_n]) = [a_1, \ldots, \leq a_n]$. And after subtracting the minimum $(a_1)$ $\rightarrow [0, \ldots, \leq a_n - a_1]$. Thus, if we always subtract the minimum, each time after applying the $F$ function, the maximum in the array will be not increase. Which allows us to work only with arrays of numbers from $0$ to $10^9$, where there naturally can be no problems with overflow. So, we got the solution for $\mathcal{O}(n^3 \log n)$. Let's improve it to $\mathcal{O}(n^2 \log n)$. The cornerstone in our previous solution is that we implement the function $F$ for $\mathcal{O}(n^2 \log n)$, which is pretty slow. Let's learn how to implement it for $\mathcal{O}(n \log n)$. This is a fairly standard problem. Note that if some pair of the form $a_i + a_j$ is included in the array $F([a_1, a_2, \ldots, a_n])$, then all pairs $a_i + a_{i+1}, a_i + a_{i+2}, \ldots, a_i + a_{j-1}$ will also be included in the array $F([a_1, a_2, \ldots, a_n])$, since the sum in these pairs is no more than $a_i + a_j$. We will build the array $F([a_1, a_2, \ldots, a_n])$ one element at a time, starting with the smallest. Let's denote the array in which we will add these numbers for $B$, initially $B$ is empty. For each index $i$, we will store the minimum index $j_i > i$ such that the pair $a_i + a_j$ is still not taken in $B$. Initially, $j_i = i+1$. We will mantain all numbers of the form $a_i + a_{j_i}$ in std::priority_queue. Then to add the next element to $B$, we will remove the minimum element from the queue, then increase the corresponding $j_i$ by one and add the element $a_i + a_{j_i}$ to the queue again. After $n - 1$ of such iteration we will get $F([a_1, a_2, \ldots, a_n])$. Each iteration takes $\mathcal{O}(\log n)$, which means that the asymptotics of finding the function $F$ is $\mathcal{O}(n \log n)$. In total, we learned how to solve the problem in $\mathcal{O}(n^2 \log n)$. Now we move on to the full solution, for $n \leq 2 \cdot 10^5$. First we will show what the solution looks like and intuition behind it, and a more strict proof will be at the end. Let's ask ourselves: when does the last element of the array $0, a_1, a_2, \ldots, a_n$ affect the answer to the problem? Very often we will lose any mention of the $a_n$ element after the first transition: $[0, a_1, \ldots, a_n] \rightarrow F([0, a_1, \ldots, a_n])$. The minimum sum of a pair of elements including $a_n$ is $0 + a_n$. And there is an $n - 1$ pair with not bigger sum: $0 + a_1$, $0 + a_2$, ..., $0 + a_{n-1}$. So the only case when $a_n$ will enter the array $F([0, a_1, \ldots, a_n])$ is if $a_1 + a_2 \geq a_n$, because otherwise the pair $a_1 + a_2$ will be less than $0 + a_n$, and there will be $n$ pairs with a sum less than $a_n$ - $n-1$ pairs of the form $0 + a_i$ and the pair $a_1 + a_2$. Well, let's assume it really happened that $a_1 + a_2 \geq a_n$. Then $F([0, a_1, \ldots, a_n]) = [0 + a_1, 0 + a_2, \ldots, 0 + a_n]$. After subtracting the minimum: $[0, a_2 - a_1, a_3 - a_1, \ldots, a_n - a_1]$. If we run $F$ on this array again, we get: $[a_2 - a_1, \ldots, \le a_n - a_1]$. After subtracting the minimum: $[0, \ldots, \le a_n - a_2]$. But remember that $a_1 + a_2 \geq a_n$. Which means $2 \cdot a_2 \geq a_n$. Which means $a_n - a_2 \leq \frac{a_n}{2}$. It turns out that if $a_n$ somehow remains in the array after two applications of the $F$ functions, then the last element of the array will be reduced by at least half! This means that after just $2 \cdot \log_2{a_n}$ iterations of the $F$ function, either the $a_n$ element will be completely evicted from the array, or the array will shrink into $[0, 0, \ldots, 0]$! In both cases, the original element $a_n$ in no way will be taken into account in the final answer. In no way! The total number of times when the maximum is halved is no more than $\log_2{a_n}$, which means intuitively it is approximately clear that elements with indexes greater than $2 \cdot \log_2{a_n}$ will not affect the answer in any way. Therefore, the full solution would be to leave the first $K = 64$ elements of the array $a$. (a little more than $2 \cdot \log_2{10^9}$). Then apply the function $F$ to this array $n - K$ times, but writing out $K$ minimal elements, not $K - 1$. After that, the length of the real array will also be equal to $K$, and it remains only to run the function $F$ $K - 1$ times to get the final answer. Final asymptotics: $\mathcal{O}(n \cdot (K \log K))$, where $K = 2 \log_2{a_n} + 2 \leq 64$. Now let's give a strict proof that this solution works. We are following $K$ minimal elements -$[0, a_1, \ldots, a_{K-1}]$. Technically, there are also $[a_K, \ldots, a_{len}]$ elements in the array. But we have no information about their values. However, we know that all these elements are $\geq a_{K-1}$ since we maintain sorted order. This means that the minimum sum of a pair of elements about which we have no information is also $\geq a_{K-1}$. The whole proof is based on this simple observation. Firstly, it is not difficult to understand that $K$ minimum elements are exactly enough to recalculate $K - 1$ minimum element in $F(a)$. Since we have pairs of elements $0 + a_1$, $0 + a_2$, ..., $0 + a_{K-1}$. And the sum in each of these pairs is no more than $a_{K-1}$, which means no more than the sum in any pair about which we have no information. Therefore, in any incomprehensible situation, we can recalculate with the loss of one of the elements. Let's see when it is possible to recalculate all $K$ minimal elements. Again, the minimum element about which we have no information from $[0, a_1, \ldots, a_{K-1}]$ is $0 + a_K \geq 0 + a_{K-1}$. So if we find $K$ elements that $\leq a_{K-1}$, then we can recalculate $K$ minimal elements of $F(a)$ through $K$ minimal elements of $a$. We have a $K - 1$ pair of the form $0 + a_i$, as well as a pair $a_1 + a_2$. So if $a_1 + a_2 < a_{K-1}$, then we can recalculate all $K$ minimal elements. And if recalculation is not possible, then $a_1 + a_2 \geq a_{K-1}$ is executed. Then, having encountered such a situation, we will recalculate twice with the loss of the last element, thus reducing $K$ by $2$. After such a recalculation, the last element will be at least half as small as it was before (this is part of the main tutorial). So after $2 \log_2(A)$ of such element removals, the array will slide into $[0, 0, \ldots, 0]$ and everything is clear. And if the number of removals is less than $2 \log_2(A)$, then one of the $K$ elements will certainly live to the end, and will be the answer to the problem. Thus, the correctness of the solution has been successfully proved. Bonus for those who are still alive: find a more accurate estimate for $K$ and build a test on which this solution, but keeping track of the $K - 1$ minimum element (one less than necessary), will give the wrong answer.
[ "greedy", "math", "sortings", "two pointers" ]
3,100
#include <bits/stdc++.h> #define all(x) x.begin(), (x).end() using namespace std; const int M = 1000000007; long long ans = 0; int real_len = 0; long long binpow(long long a, int x) { long long ans0 = 1; while (x) { if (x % 2) { ans0 *= a; ans0 %= M; } a *= a; a %= M; x /= 2; } return ans0; } void chill(vector<int> &b) { int mn = b[0]; ans += (int) ((long long) mn * binpow(2, real_len - 1) % M); if (ans >= M) { ans -= M; } for (auto &x : b) { x -= mn; } } void F(vector<int> &b, int sub = 0) { --real_len; vector<int> cnd; for (int i = 0; i < b.size(); i++) { for (int j = i + 1; j < b.size(); j++) { if (i * j >= b.size()) break; cnd.push_back(b[i] + b[j]); } } sort(all(cnd)); vector<int> b2((int) b.size() - sub); for (int i = 0; i < (int) b.size() - sub; i++) { b2[i] = cnd[i]; } chill(b2); b = b2; } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(all(a)); int L = 64; vector<int> b(min(n, L)); for (int i = 0; i < min(n, L); i++) { b[i] = a[i]; } real_len = n; chill(b); while (b.size() < real_len) { if (b[1] + b[2] > b.back()) { F(b, 1); F(b, 1); } else { F(b); } } while (real_len > 1) { F(b, 1); } ans += b[0]; ans %= M; cout << ans << '\n'; }
1806
A
Walking Master
YunQian is standing on an infinite plane with the Cartesian coordinate system on it. In one move, she can move to the diagonally adjacent point on the top right or the adjacent point on the left. That is, if she is standing on point $(x,y)$, she can either move to point $(x+1,y+1)$ or point $(x-1,y)$. YunQian initially stands at point $(a,b)$ and wants to move to point $(c,d)$. Find the minimum number of moves she needs to make or declare that it is impossible.
Hint 1: The value of $b$ is always non-decreasing, and the value of $a-b$ is always non-increasing. It is possible to move from $(a,b)$ to $(c,d)$ if and only if $d\ge b$ and $a-b\ge c-d$, since the value of $b$ is always non-decreasing and the value of $a-b$ is always non-increasing. If it is possible, the answer is $(d-b)+((a+d-b)-c)$. One possible way is $(a,b)\to (a+d-b,d)\to (c,d)$. Another way to understand this: $(a,b)\to (a+d-b,d)\to (c,d)$ is always a valid path if it is possible to move from $(a,b)$ to $(c,d)$. So first let $a\leftarrow a+(d-b)$ and $b\leftarrow d$, then the answer only depends on $a$ and $c$.
[ "geometry", "greedy", "math" ]
800
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=500005; const int inf=0x3f3f3f3f; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int a,b,c,d; cin>>a>>b>>c>>d; if(b<=d&&c<=a+d-b) { cout<<(d-b)+(a+d-b-c)<<"\n"; } else { cout<<"-1\n"; } } }
1806
B
Mex Master
You are given an array $a$ of length $n$. The score of $a$ is the MEX$^{\dagger}$ of $[a_1+a_2,a_2+a_3,\ldots,a_{n-1}+a_n]$. Find the minimum score of $a$ if you are allowed to rearrange elements of $a$ in any order. Note that you are \textbf{not required} to construct the array $a$ that achieves the minimum score. $^{\dagger}$ The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: - The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array. - The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not. - The MEX of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.
Hint 1: $ans\le 2$. First, let's determine if $ans$ can be $0$. That means we can't place two $0$s next to each other. This is achievable when the number of $0$s is not greater than $\lceil\frac{n}{2}\rceil$. Then determine if $ans$ can be $1$. That means we can't place $0$ and $1$ next to each other. Therefore, if there is no $1$ in $a$ or there exist an element $x\ge 2$ in $a$, we can simply rearrange $a$ as $[0,0,\ldots,0,x,1,1,\ldots]$ to make $ans=1$. The last case:there are only $0$ and $1$ in $a$ and the number of $0$s is greater than $\lceil\frac{n}{2}\rceil$. We want to make $ans=2$ which is the minimum. Since the number of $1$s is not greater than the number of $0$s, we can rearrange $a$ as $[0,1,0,1,\ldots,0,1,0,0,\ldots]$ to make $ans=2$.
[ "constructive algorithms", "greedy" ]
900
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=200005; const int inf=0x3f3f3f3f; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int n; cin>>n; int sum0=0; bool f=false; for(int i=1;i<=n;i++) { int x; cin>>x; if(x==0) { sum0++; } else if(x>=2) { f=true; } } if(sum0<=(n+1)/2) { cout<<"0\n"; } else if(f||sum0==n) { cout<<"1\n"; } else { cout<<"2\n"; } } }
1806
C
Sequence Master
For some positive integer $m$, YunQian considers an array $q$ of $2m$ (possibly negative) integers good, if and only if for every possible subsequence of $q$ that has length $m$, the product of the $m$ elements in the subsequence is equal to the sum of the $m$ elements that are \textbf{not} in the subsequence. Formally, let $U=\{1,2,\ldots,2m\}$. For all sets $S \subseteq U$ such that $|S|=m$, $\prod\limits_{i \in S} q_i = \sum\limits_{i \in U \setminus S} q_i$. Define the distance between two arrays $a$ and $b$ both of length $k$ to be $\sum\limits_{i=1}^k|a_i-b_i|$. You are given a positive integer $n$ and an array $p$ of $2n$ integers. Find the minimum distance between $p$ and $q$ over all good arrays $q$ of length $2n$. It can be shown for all positive integers $n$, at least one good array exists. Note that you are \textbf{not required} to construct the array $q$ that achieves this minimum distance.
Hint 1: The number of good sequences is small. Hint 2: Consider two cases: all elements in $q$ are (not) equal. In case that all elements in $q$ are equal, we have $q_1^n=nq_1$. The integer solutions to this equation is $q_1=0$, $n=1$ or $(q_1,n)=(2,2)$. In the other case, we can see that the constraints are strong, so let's list some equations to find good sequences, using the property that not all elements are equal. Let $q$ be such a good sequence. WLOG $q_1\neq q_2$. Then we have: $q_1\cdot q_3q_4\cdots q_{n+1}=q_2+q_{n+2}+q_{n+3}+\cdots+q_{2n}\tag{1}$ $q_2\cdot q_3q_4\cdots q_{n+1}=q_1+q_{n+2}+q_{n+3}+\cdots+q_{2n}\tag{2}$ Substract $(2)$ from $(1)$: $(q_1-q_2)q_3q_4\cdots q_{n+1}=q_2-q_1\\ \iff (q_1-q_2)(q_3q_4\cdots q_{n+1}+1)=0$ Since $q_1-q_2\neq 0$, there must be $q_3q_4\cdots q_{n+1}=-1$. Similarly, for each exactly $n-1$ numbers in $q_3,q_4,\cdots,q_{2n}$, their product will be $-1$, which leads to $q_3=q_4=\cdots =q_{2n}$. Therefore, we have $q_3^{n-1}=-1$, which leads to $2\mid n$ and $q_3=q_4=\cdots=q_{2n}=-1$. Bringing it back to $(1)$, we have $q_1+q_2=n-1$. Since $q_1q_2\cdots q_n=q_{n+1}+\cdots q_{2n}$, we know $q_1q_2=-n$. The only solution is $\{q_1,q_2\}=\{-1,n\}$. Q.E.D. Back to the problem. For the first case, it is easy to calculate the distance. For the second case, let $S=\sum_{i=1}^n |q_i-(-1)|$, the answer is $\min_{1\le j\le n}\{S-|q_j-(-1)|+|q_j-n|\}$.
[ "brute force", "constructive algorithms", "math" ]
1,600
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=400005; const ll inf=0x3f3f3f3f3f3f3f3f; ll a[maxn]; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int n; cin>>n; ll ans=0,sum=0; for(int i=1;i<=n*2;i++) { cin>>a[i]; ans+=abs(a[i]); sum+=abs(a[i]-(-1)); } if(n==1) { ans=min(ans,abs(a[1]-a[2])); } if(n==2) { ans=min(ans,abs(a[1]-2)+abs(a[2]-2)+abs(a[3]-2)+abs(a[4]-2)); } if(n%2==0) { for(int i=1;i<=n*2;i++) { ans=min(ans,sum-abs(a[i]-(-1))+abs(a[i]-n)); } } cout<<ans<<"\n"; } }
1806
D
DSU Master
You are given an integer $n$ and an array $a$ of length $n-1$ whose elements are either $0$ or $1$. Let us define the value of a permutation$^\dagger$ $p$ of length $m-1$ ($m \leq n$) by the following process. Let $G$ be a graph of $m$ vertices labeled from $1$ to $m$ that does not contain any edges. For each $i$ from $1$ to $m-1$, perform the following operations: - define $u$ and $v$ as the (unique) vertices in the weakly connected components$^\ddagger$ containing vertices $p_i$ and $p_i+1$ respectively with only incoming edges$^{\dagger\dagger}$; - in graph $G$, add a directed edge from vertex $v$ to $u$ if $a_{p_i}=0$, otherwise add a directed edge from vertex $u$ to $v$ (if $a_{p_i}=1$). Note that after each step, it can be proven that each weakly connected component of $G$ has a unique vertex with only incoming edges.Then, the value of $p$ is the number of incoming edges of vertex $1$ of $G$. For each $k$ from $1$ to $n-1$, find the sum of values of all $k!$ permutations of length $k$. Since this value can be big, you are only required to compute this value under modulo $998\,244\,353$. \begin{center} {\small Operations when $n=3$, $a=[0,1]$ and $p=[1,2]$} \end{center} $^\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). $^\ddagger$ The weakly connected components of a directed graph is the same as the components of the undirected version of the graph. Formally, for directed graph $G$, define a graph $H$ where for all edges $a \to b$ in $G$, you add an undirected edge $a \leftrightarrow b$ in $H$. Then the weakly connected components of $G$ are the components of $H$. $^{\dagger\dagger}$ Note that a vertex that has no edges is considered to have only incoming edges.
We record an operation of adding edge as $(i,i+1,a_i)$. Hint 1: Only operation $(i,i+1,0)$ can contribute. Hint 2: Using dynamic programming, let $f_i$ denote the number of ways to let vertices $1\sim i$ form a tree with root $1$, considering only the first $i-1$ operations. We can observe: Only operation $(i,i+1,0)$ can contribute. If vertices $1\sim i$ have already formed a tree with root $1$, then operation $(i,i+1,0)$ can contribute. Using dynamic programming, let $f_i$ denote the number of ways to let vertices $1\sim i$ form a tree with root $1$, considering only the first $i-1$ operations. For $f$, we have $f_1=1$ and $f_{i+1}=f_i\cdot (i-a_i)$. Explanation: Consider inserting the operation $(i,i+1,a_i)$ in the sequence of the first $i-1$ operations. If $a_i=0$, no matter where it is inserted, it will always form a tree with root $1$, so $f_{i+1}=f_i\cdot i$. If $a_i=1$, only inserting at the end is invalid, so $f_{i+1}=f_i\cdot (i-1)$. This is because, if you insert $(i,i+1,1)$ at the end of the operations, we will add a edge from $1$ to $i+1$, which won't form a tree of root $1$. For computing the answer, we have $ans_i=i\cdot ans_{i-1}+[a_i=0]f_{i}$. Explanation: $i\cdot ans_{i-1}$ represents the contribution of previous $i-1$ operations. No matter where operation $(i,i+1,a_i)$ is inserted, the contribution of previous $i-1$ operations won't change. $[a_i=0]f_{i}$ means the contribution of operation $(i,i+1,a_i)$.
[ "combinatorics", "dp", "dsu", "math" ]
2,500
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=500005; const int inf=0x3f3f3f3f; const int mod=998244353; int a[maxn]; int f[maxn]; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int n; cin>>n; for(int i=1;i<=n-1;i++) { cin>>a[i]; } f[1]=1; for(int i=1;i<=n-1;i++) { f[i+1]=1ll*f[i]*(i-a[i])%mod; } int ans=0; for(int i=1;i<=n-1;i++) { ans=(1ll*ans*i+(!a[i])*f[i])%mod; cout<<ans<<" "; } cout<<"\n"; } }
1806
E
Tree Master
You are given a tree with $n$ weighted vertices labeled from $1$ to $n$ rooted at vertex $1$. The parent of vertex $i$ is $p_i$ and the weight of vertex $i$ is $a_i$. For convenience, define $p_1=0$. For two vertices $x$ and $y$ \textbf{of the same depth$^\dagger$}, define $f(x,y)$ as follows: - Initialize $\mathrm{ans}=0$. - While both $x$ and $y$ are not $0$: - $\mathrm{ans}\leftarrow \mathrm{ans}+a_x\cdot a_y$; - $x\leftarrow p_x$; - $y\leftarrow p_y$. - $f(x,y)$ is the value of $\mathrm{ans}$. You will process $q$ queries. In the $i$-th query, you are given two integers $x_i$ and $y_i$ and you need to calculate $f(x_i,y_i)$. $^\dagger$ The depth of vertex $v$ is the number of edges on the unique simple path from the root of the tree to vertex $v$.
Hint 1: The time complexity of the solution is $O(n\sqrt{n})$. Hint 2: Brute force with something to store the answer. The solution turns out quite easy: just store the answer to each pair of $(x,y)$ when computing the answer by climbing up on the tree. If we see the time complexity of hash table as $O(1)$, then the time complexity and memory complexity are both $O(n\sqrt{n})$. Let's prove it. We will see $n=q$ in the following proof. It is clear that the above solution's time complexity depends on the number of different pairs $(x,y)$ which we encounter when climbing. Assume the $i$-th depth of the tree has $s_i$ nodes, then its contribution to things above is $\min(s_i^2,n)$. It's easy to discover that when $s_i>\sqrt{n}$, the contribution of it will equal to the contribution when $s_i=\sqrt{n}$. So, making all $s_i$ not greater than $\sqrt{n}$ will contribute more. Therefore, the time complexity is $O(\sum_{i=1}^k s_i^2)$. When $s_i=\sqrt{n}$, the formula above has a maximum value of $n\sqrt{n}$, because $(a+b)^2\ge a^2+b^2$. In fact, we don't need to use hash table in this problem. If there exists a pair of $(x,y)$ of depth $i$ such that $s_i> \sqrt{n}$, then we don't need to store $(x,y)$. Since the amount of $i$ such that $s_i>\sqrt{n}$ are not greater than $\sqrt{n}$, the time complexity won't change. For other pairs of $(x,y)$ we can simply store them in an array, then the memory complexity won't change.
[ "brute force", "data structures", "dfs and similar", "trees" ]
2,200
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=100005; const int sqrtn=325; const int B=320; const int inf=0x3f3f3f3f; int n,q; int a[maxn]; int h[maxn]; int fa[maxn]; int cnt[maxn]; int depth[maxn]; ll f[maxn][sqrtn]; vector<int> tree[maxn]; void dfs(int x,int d) { h[x]=++cnt[d],depth[x]=d; for(int to:tree[x]) { dfs(to,d+1); } } ll ask(int x,int y) { if(!x&&!y) { return 0; } if(cnt[depth[y]]<=B&&f[x][h[y]]) { return f[x][h[y]]; } ll ans=ask(fa[x],fa[y])+1ll*a[x]*a[y]; if(cnt[depth[y]]<=B) { f[x][h[y]]=ans; } return ans; } signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); cin>>n>>q; for(int i=1;i<=n;i++) { cin>>a[i]; } for(int i=2;i<=n;i++) { cin>>fa[i]; tree[fa[i]].push_back(i); } dfs(1,0); while(q--) { int x,y; cin>>x>>y; cout<<ask(x,y)<<"\n"; } }
1806
F2
GCD Master (hard version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $m$. You can make hacks only if both versions of the problem are solved.} You are given an array $a$ of length $n$ and two integers $m$ and $k$. Each element in $a$ satisfies $1\le a_i \le m$. In one operation, you choose two indices $i$ and $j$ such that $1 \le i < j \le |a|$, then append $\gcd(a_i,a_j)$ to the back of the array and delete $a_i$ and $a_j$ from the array. Note that the length of the array decreases by one after this operation. Find the maximum possible sum of the array after performing \textbf{exactly} $k$ operations.
Hint 1: There is a easy strategy for dealing with repeated elements. Suppose that all elements in $a$ are pairwise distinct in the following hints. Hint 2: We will always perform an operation on the minimum element. Hint 3: The best way is to choose $k+1$ elements, delete them, and add the gcd of them to the sequence. Hint 4: After sorting the sequence, you may guess that choosing a prefix is optimal. But actually it is wrong. Try fixing the strategy! Solution for F1: First, suppose that all elements in $a$ are pairwise distinct. The problem can be rewritten as: Divide the sequence into $n-k$ groups to maximize the sum of the gcd of each group. Let $S_i$ represent the elements of a group. Lemma $1$: When $k>0$, the group which the minimum element of the original sequence belongs to satisfies $|S_a|>1$. Proof: If $|S_a|=1$, we can find a group $S_x$ such that $|S_x|>1$. Then replacing the maximum element of $S_x$ with the minimum element of the original sequence makes the answer greater. Let $a$ be the minimum of the sequence and $b$ be the maximum of $S_x$. the original answer is $a+\gcd(S_x)$. replacing the maximum element of $S_x$ with the minimum element, the answer is $b+\gcd(S_x \setminus \{b\}\cup\{a\}) >b$. $\gcd(S_x) \le \max{S_x} - \min S_x = b-\min S_x < b-a$, so $a+\gcd(S_x)< a+b-a=b<b+\gcd(S_x \setminus \{b\}\cup\{a\})$. Q.E.D. Tips: When $\max S_x = \min S_x$, $\gcd(S_x) \not\le \max{S_x} - \min S_x$. That's why all elements in $a$ need to be pairwise distinct. Lemma $2$: When $k>0$, there's only one $S_x$ such that $|S_x| >1$ . Proof: Let $S_a$ be the group with the minimum element. Referring to Lemma $1$, we know $|S_a| >1$. Then we remove all the elements of $S_a$ from the sequence, add $\gcd({S_a})$ to the sequence and subtract $|S_a| - 1$ from $k$. It's obvious that $\gcd(S_a)$ is the minimum element of the newly formed sequence. We can continue the process until $k=0$, which tells us that only $|S_a|=k+1>1$. Q.E.D. We can enumerate $\gcd(S_a)$ to solve it in $O(n+m\ln m)$ so far. How about repeated elements? We can find that for those repeated elements, the best strategy is to merge them with the same element. In other word, a repeated element $x$ only decreases the answer by $x$. So it's independent of the previous part. We just need to enumerate the number of operations we perform for repeated elements. Solution for F2: Still suppose that all elements in $a$ are pairwise distinct. Suppose $a$ is sorted. Lemma $3$: When $k>0$, we will choose the first $k$ elements, and an element from the remaining elements. That is, $S=\{a_1,a_2,\ldots,a_k,a_x\}$, where $k < x \le n$, is the only group with more than one element. Proof: Suppose $T=\{a_1,a_2,\ldots, a_{p}, a_{c_1}, a_{c_2}, \ldots, a_{c_t}\}$, where $p+1<c_1<c_2<\cdots<c_t$, $t\ge 2$ and $p+t=k+1$. Then we can prove that $T'=\{a_1,a_2,\ldots, a_{p},a_{p+1}, a_{c_1}, a_{c_2}, \ldots, a_{c_{t-1}}\}$ is always a better choice. Let $g=\gcd(T)$ and $g'=\gcd(T')$. We have $a_{c_t}-a_{p+1}> a_{c_t}-a_{c_{t-1}}\ge g$. $\Delta=ans(T')-ans(T)=a_{c_t}-a_{p+1}+g'-g> g'>0$. So repeating the process, finally we will know that $S=\{a_1,a_2,\ldots,a_k,a_x\}$, where $k < x \le n$. Q.E.D. When there're repeated elements, we need to calculate the answer for $k$ prefixes. Note that there're only $O(\log m)$ different prefix gcd. So we can do it in $O(n \log^2 m)$ (another $O(\log m)$ comes from calculating gcd). Let $g_i$ be the prefix gcd. When finding the best pair, we calculate $\gcd(g_i,a_j)$, which leads to $O(n \log^2 m)$. $g_i\mid g_{i-1}$, so $\gcd(g_i,a_j)=\gcd(g_i,\gcd(g_{i-1},a_j))$. The gcd is non-increasing so the total complexity is $O(n \log m)$.
[ "greedy", "math", "sortings" ]
2,900
#include<bits/stdc++.h> #define ll long long #define int128 __int128 #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=1000005; const ll inf=9e18; const int128 inf128=(int128)(inf)*(int128)(inf); ll a[maxn]; ll b[maxn]; ll g[maxn]; ll ra[maxn]; int128 suma[maxn]; int128 sumb[maxn]; int128 ans[maxn]; ll gcd(ll x,ll y) { return !y?x:gcd(y,x%y); } void print(int128 x) { if(!x) { return ; } print(x/10); cout<<(int)(x%10); } signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int n,k; ll m; cin>>n>>m>>k; for(int i=1;i<=n;i++) { cin>>a[i]; } sort(a+1,a+n+1); int t=0,r=0; for(int i=1;i<=n;i++) { if(i>1&&a[i]==a[i-1]) { b[++r]=a[i]; } else { ra[++t]=a[i]; } } n=t; for(int i=1;i<=n;i++) { a[i]=ra[i]; g[i]=gcd(g[i-1],a[i]); suma[i]=suma[i-1]+a[i]; } for(int i=0;i<=k;i++) { ans[i]=-inf128; } for(int l=1;l<=n;) { int r=l; while(r<=n&&g[r]==g[l]) { r++; } r--; ll Max=-inf; for(int i=r+1;i<=n;i++) { a[i]=gcd(a[i],g[l]); Max=max(Max,a[i]-ra[i]); } for(int i=r;i>=l;i--) { ans[i]=suma[n]-suma[i]+Max; a[i]=gcd(a[i],g[l]); Max=max(Max,a[i]-ra[i]); } l=r+1; } for(int i=1;i<=r;i++) { sumb[i]=sumb[i-1]+b[i]; } int128 final=-inf128; if(k<=r) { final=suma[n]+sumb[r]-sumb[k]; } for(int i=0;i<=r&&i<=k;i++) { final=max(final,sumb[r]-sumb[i]+ans[k-i]); } print(final); cout<<"\n"; } }
1807
A
Plus or Minus
You are given three integers $a$, $b$, and $c$ such that \textbf{exactly one} of these two equations is true: - $a+b=c$ - $a-b=c$ Output + if the first equation is true, and - otherwise.
You need to implement what is given in the statement; for example, you can use an if-statement to output + if $a+b=c$, and - otherwise.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int a, b, c; cin >> a >> b >> c; if (a + b == c) {cout << "+\n";} else {cout << "-\n";} } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
1807
B
Grab the Candies
Mihai and Bianca are playing with bags of candies. They have a row $a$ of $n$ bags of candies. The $i$-th bag has $a_i$ candies. The bags are given to the players in the order from the first bag to the $n$-th bag. If a bag has an even number of candies, Mihai grabs the bag. Otherwise, Bianca grabs the bag. Once a bag is grabbed, the number of candies in it gets added to the total number of candies of the player that took it. Mihai wants to show off, so he wants to reorder the array so that at any moment (except at the start when they both have no candies), Mihai will have \textbf{strictly more} candies than Bianca. Help Mihai find out if such a reordering exists.
Let $s_e$ be the total number of candies with all bags with an even number of candies, and $s_o$ - the total of all bags with an odd number of candies. If $s_e \leq s_o$, then the answer is NO, because at the end Mihai (who takes only even numbers of candies) will have less candies than Bianca. Otherwise if $s_e > s_o$ the answer is YES. The construction is to simply put all even bags first, and then all odd bags: since all even bags come before all odd bags and $s_e>s_o$, at any point in time Mihai will have more candies than Bianca. The time complexity is $\mathcal{O}(n)$.
[ "greedy" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int x, odd = 0, even = 0; for(int i = 0; i < n; i++) { cin >> x; if(x%2 == 0) { even+=x; } else { odd+=x; } } if(even > odd) { cout << "YES" << endl; } else { cout << "NO" << endl; } } int32_t main(){ int t = 1; cin >> t; while (t--) { solve(); } }
1807
C
Find and Replace
You are given a string $s$ consisting of lowercase Latin characters. In an operation, you can take a character and replace \textbf{all} occurrences of this character with $0$ or replace \textbf{all} occurrences of this character with $1$. Is it possible to perform some number of moves so that the resulting string is an alternating binary string$^{\dagger}$? For example, consider the string $abacaba$. You can perform the following moves: - Replace $a$ with $0$. Now the string is $\textcolor{red}{0}b\textcolor{red}{0}c\textcolor{red}{0}b\textcolor{red}{0}$. - Replace $b$ with $1$. Now the string is ${0}\textcolor{red}{1}{0}c{0}\textcolor{red}{1}{0}$. - Replace $c$ with $1$. Now the string is ${0}{1}{0}\textcolor{red}{1}{0}{1}{0}$. This is an alternating binary string. $^{\dagger}$An alternating binary string is a string of $0$s and $1$s such that no two adjacent bits are equal. For example, $01010101$, $101$, $1$ are alternating binary strings, but $0110$, $0a0a0$, $10100$ are not.
Let's solve a harder problem: given a string $s$ and a binary string $t$, can we make $s$ into $t$ using the find and replace operations? We can simply iterate through each character of $s$ and see the bit it has turned to in $t$ (that is, $s_i \to t_i$ for each $i$). Keep track of each change, and see if there is some letter that needs to be turned into both $\texttt{0}$ and $\texttt{1}$. If there is some letter, it is impossible, since each operation requires changing all occurrences of a letter into the same bit. Otherwise, it is possible, and we can directly change each letter into the bit it needs to be. (See the implementation for a better understanding.) Now for this problem, since there are only two alternating binary strings of length $n$ ($\texttt{01010...}$ and $\texttt{10101...}$), we can simply check both. (Actually, we only have to check one - do you see why?) The time complexity is $\mathcal{O}(n)$.
[ "greedy", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s; cin >> s; int mp[26]; for (int i = 0; i < 26; i++) { mp[i] = -1; } for (int i = 0; i < n; i++) { int curr = (s[i] - 'a'); if (mp[curr] == -1) { mp[curr] = (i % 2); } else { if (mp[curr] != (i % 2)) {cout << "NO\n"; return;} } } cout << "YES\n"; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
1807
D
Odd Queries
You have an array $a_1, a_2, \dots, a_n$. Answer $q$ queries of the following form: - If we change all elements in the range $a_l, a_{l+1}, \dots, a_r$ of the array to $k$, will the sum of the entire array be odd? Note that queries are \textbf{independent} and do not affect future queries.
Note that for each question, the resulting array is $[a_1, a_2, \dots, a_{l-1}, k, \dots, k, a_{r+1}, a_{r+2}, \dots, a_n].$ So, the sum of the elements of the new array after each question is $a_1 + \dots + a_{l-1} + (r-l+1) \cdot k + a_{r+1} + \dots + a_n.$ We can compute $a_1 + \dots + a_{l-1}$ and $a_{r+1} + \dots + a_n$ in $\mathcal{O}(1)$ time by precomputing the sum of all prefixes and suffixes, or alternatively by using the prefix sums technique. So we can find the sum each time in $\mathcal{O}(1)$ per question, and just check if it's odd or not. The time complexity is $\mathcal{O}(n+q)$.
[ "data structures", "implementation" ]
900
#include <iostream> using namespace std; long long n,a[200005],q,sum=0,pref[200005],t; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>t; while(t--) { sum = 0; cin >> n >> q; for(int i=1;i<=n;i++){ cin >> a[i]; sum+=a[i]; pref[i]=pref[i-1]; pref[i]+=a[i]; } for(int i = 0; i < q; i++){ long long l,r,k; cin >> l >> r >> k; long long ans = pref[n]-(pref[r]-pref[l-1])+k*(r-l+1); if(ans%2==1){ cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } } } }
1807
E
Interview
This is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants. Before the last stage of the exam, the director conducted an interview. He gave Gon $n$ piles of stones, the $i$-th pile having $a_i$ stones. Each stone is identical and weighs $1$ grams, except for one special stone that is part of an unknown pile and weighs $2$ grams. \begin{center} {\small A picture of the first test case. Pile $2$ has the special stone. The piles have weights of $1,3,3,4,5$, respectively.} \end{center} Gon can only ask the director questions of one kind: he can choose $k$ piles, and the director will tell him the total weight of the piles chosen. More formally, Gon can choose an integer $k$ ($1 \leq k \leq n$) and $k$ unique piles $p_1, p_2, \dots, p_k$ ($1 \leq p_i \leq n$), and the director will return the total weight $m_{p_1} + m_{p_2} + \dots + m_{p_k}$, where $m_i$ denotes the weight of pile $i$. Gon is tasked with finding the pile that contains the special stone. However, the director is busy. Help Gon find this pile in at most $\mathbf{30}$ queries.
Consider this question: if we take some range $[a_l, \dots, a_r]$ of piles, how do we know if it contains the special pile? If it doesn't contain the special pile, then the total weight should be $a_l + a_{l+1} + \dots + a_r$ grams, since each stone weighs one gram. If it does contain the special pile, then the total weight should be $a_l + a_{l+1} + \dots + a_r + 1$ grams, since each stone weighs one gram except for the special stone, which weighs two grams. Now we can binary search for the answer: first check the range $[a_1, \dots, a_{\frac{n}{2}}]$. If it has the special pile, then split it into two parts and check if one of them has the special stone; otherwise, check the other half. This will take at most $\lceil \log_2(2 \cdot 10^5) \rceil = 18$ queries, which is well below the limit of $30$. The time complexity is $\mathcal{O}(n)$ (for reading the input).
[ "binary search", "implementation", "interactive" ]
1,300
#include <bits/stdc++.h> using ll=long long; using ld=long double; int const INF=1000000005; ll const LINF=1000000000000000005; ll const mod=1000000007; ld const PI=3.14159265359; ll const MAX_N=3e5+5; ld const EPS=0.00000001; #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #define f first #define s second #define pb push_back #define mp make_pair #define endl '\n' #define sz(a) (int)a.size() #define CODE_START ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); using namespace std; ll t,n,a[2000005],pref[2000005]; int32_t main(){ //CODE_START; #ifdef LOCAL //ifstream cin("input.txt"); #endif cin>>t; while(t--){ cin>>n; for(ll i=1;i<=n;i++) { cin>>a[i]; pref[i]=pref[i-1]+a[i]; } ll l=1,r=n,ans=0; while(l<=r){ ll mid=(l+r)/2; cout<<"? "<<(mid-l+1)<<' '; for(ll i=l;i<=mid;i++) { cout<<i<<' '; } cout<<endl<<flush; ll x=0; cin>>x; if(x==pref[mid]-pref[l-1]){ l=mid+1; }else { r=mid-1; ans=mid; } } cout<<"! "<<ans<<endl<<flush; } }
1807
F
Bouncy Ball
You are given a room that can be represented by a $n \times m$ grid. There is a ball at position $(i_1, j_1)$ (the intersection of row $i_1$ and column $j_1$), and it starts going diagonally in one of the four directions: - The ball is going down and right, denoted by $DR$; it means that after a step, the ball's location goes from $(i, j)$ to $(i+1, j+1)$. - The ball is going down and left, denoted by $DL$; it means that after a step, the ball's location goes from $(i, j)$ to $(i+1, j-1)$. - The ball is going up and right, denoted by $UR$; it means that after a step, the ball's location goes from $(i, j)$ to $(i-1, j+1)$. - The ball is going up and left, denoted by $UL$; it means that after a step, the ball's location goes from $(i, j)$ to $(i-1, j-1)$. After each step, the ball maintains its direction unless it hits a wall (that is, the direction takes it out of the room's bounds in the next step). In this case, the ball's direction gets flipped along the axis of the wall; if the ball hits a corner, both directions get flipped. Any instance of this is called a bounce. The ball never stops moving. In the above example, the ball starts at $(1, 7)$ and goes $DL$ until it reaches the bottom wall, then it bounces and continues in the direction $UL$. After reaching the left wall, the ball bounces and continues to go in the direction $UR$. When the ball reaches the upper wall, it bounces and continues in the direction $DR$. After reaching the bottom-right corner, it bounces \textbf{once} and continues in direction $UL$, and so on. Your task is to find how many bounces the ball will go through until it reaches cell $(i_2, j_2)$ in the room, or report that it never reaches cell $(i_2, j_2)$ by printing $-1$. Note that the ball first goes in a cell and only after that bounces if it needs to.
We can see that there are at most $4\cdot n \cdot m$ states the ball can be in, because there are $n \cdot m$ cells and $4$ states of direction. We can simulate the bouncing process, keeping count of the bounces until we arrive at the finish cell when we can output the answer, or we arrive at a previously visited state and end up in a loop, then we can output -1. Bonus: Can you prove there are at most $2\cdot n \cdot m$ states for any given starting position?
[ "brute force", "dfs and similar", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; void solve() { int n, m, x1, y1, x2, y2; string d_string; cin >> n >> m >> x1 >> y1 >> x2 >> y2; x1--;x2--;y1--;y2--; cin >> d_string; int d = (d_string[0] == 'U' ? 1+(d_string[1] == 'R' ? 2 : 0) : 0+(d_string[1] == 'R' ? 2 : 0)); bool vis[n][m][4]; memset(vis, false, sizeof(vis)); int i = x1, j = y1; int bounces = 0; while(!vis[i][j][d]) { if(i == x2 && j == y2){cout << bounces << endl; return;} int na = 0; if(d%2 == 1 && i == 0){d-=1;na++;} if(d%2 == 0 && i == n-1){d+=1;na++;} if(d >= 2 && j == m-1){d-=2;na++;} if(d < 2 && j == 0){d+=2;na++;} bounces+=min(1, na); if(vis[i][j][d]) { break; } vis[i][j][d] = true; if(d%2 == 1){i--;}else{i++;} if(d >= 2){j++;}else{j--;} } cout << -1 << endl; } int32_t main(){ int t = 1; cin >> t; while (t--) { solve(); } }
1807
G1
Subsequence Addition (Easy Version)
The only difference between the two versions is that in this version, the constraints are lower. Initially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\dagger}$ of $a$ and add into $a$ an element equal to the sum of all elements of the subsequence. You are given a final array $c$. Check if $c$ can be obtained from the initial array $a$ by performing some number (possibly 0) of operations on the initial array. $^{\dagger}$ A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly zero, but not all) elements. In other words, select $k$ ($1 \leq k \leq |a|$) distinct indices $i_1, i_2, \dots, i_k$ and insert anywhere into $a$ a new element with the value equal to $a_{i_1} + a_{i_2} + \dots + a_{i_k}$.
Firstly, let's note that it doesn't matter in what order we add the elements to the array, since if we can add an element in any position, if it's possible to get the said elements of the array, then we can obtain them in any order. Now, let's note that it's always optimal to obtain the needed elements in sorted order (since we only use smaller values in order to obtain the current one), so we will consider the array $c$ as sorted. If the first element of the array isn't $1$ then we immediately know such an array doesn't exist. Otherwise, we can use dynamic programming for finding out if the remaining $n - 1$ elements are obtainable. Let's denote $dp_s$ a boolean array which tells us whether sum $s$ is obtainable. Initially, $dp_1 = 1$ (since the first element is guaranteed to be $1$). We will go in increasing order of $c_i$ and if we calculated an element to be obtainable in the past, we update all obtainable values with the new $c_i$ value. We do this in $O(n \cdot 5000)$, by going through all sums $s$ and updating $dp_s = dp_s | dp_{s - c_i}$ ($dp_s$ is true if it already was true, or if $dp_{s - c_i}$ was true and we add to that sum the new value $c_i$. The total time complexity of this solution is $O(n \cdot 5000)$.
[ "brute force", "data structures", "dp", "greedy", "implementation", "sortings" ]
1,100
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() void solve() { int n; cin >> n; vector<int> a(n); for(int i = 0; i < n; ++i) { cin >> a[i]; } sort(all(a)); if(a[0] != 1) { cout << "NO\n"; return; } vector<int> dp(5005, 0); dp[1] = 1; for(int i = 1; i < n; ++i) { if(!dp[a[i]]) { cout << "NO\n"; return; } for(int j = 5000; j >= a[i]; --j) { dp[j] |= dp[j - a[i]]; } } cout << "YES\n"; } int32_t main() { ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t = 1; cin >> t; while(t--) { solve(); } }
1807
G2
Subsequence Addition (Hard Version)
The only difference between the two versions is that in this version, the constraints are higher. Initially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\dagger}$ of $a$ and add into $a$ an element equal to the sum of all elements of the subsequence. You are given a final array $c$. Check if $c$ can be obtained from the initial array $a$ by performing some number (possibly 0) of operations on the initial array. $^{\dagger}$ A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly zero, but not all) elements. In other words, select $k$ ($1 \leq k \leq |a|$) distinct indices $i_1, i_2, \dots, i_k$ and insert anywhere into $a$ a new element with the value equal to $a_{i_1} + a_{i_2} + \dots + a_{i_k}$.
Let's prove that for an array $a$ that was created by using a number of operations, with a sum of elements $s$ we can add into $a$ any number $x$ ($1 \leq x \leq s$). Suppose that it is true that in the array $a$ with some length $l$ we introduce a number $x$ ($1 \leq x \leq sum_a$). Then after introducing we can create using the initial elements of the array any number $b$ ($1 \leq b \leq sum_a$) and using the element $x$ and some subset of the initial elements we can create any number $b$ ($x \leq b \leq sum_a+x$), and because $x \leq sum_a$ we proved that for the new array of length $l+1$ we can still create any number between $1$ and $sum_a+x$. Since it is true for the initial array, we can use induction and this fact to prove it is true for all arrays. So we just need to verify if our array satisfies this condition. We should sort the array and check for each $i$ ($2 \leq i \leq n$) if $c_i \leq \sum_{j = 1}^{i-1}c_j$.
[ "bitmasks", "dp", "greedy", "implementation", "sortings" ]
1,100
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() void solve() { int n; cin >> n; vector<int> a(n); for(int i = 0; i < n; ++i) { cin >> a[i]; } sort(all(a)); if(a[0] != 1) { cout << "NO\n"; return; } long long sum = a[0]; for(int i = 1; i < n; ++i) { if(sum < a[i]) { cout << "NO\n"; return; } sum += a[i]; } cout << "YES\n"; } int32_t main() { ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t = 1; cin >> t; while(t--) { solve(); } }
1808
A
Lucky Numbers
Olympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively. Each starship has a number —some positive integer $x$. Let's define the luckiness of a number $x$ as the difference between the largest and smallest digits of that number. For example, $142857$ has $8$ as its largest digit and $1$ as its smallest digit, so its luckiness is $8-1=7$. And the number $111$ has all digits equal to $1$, so its luckiness is zero. Hateehc is a famous Martian blogger who often flies to different corners of the solar system. To release interesting videos even faster, he decided to buy himself a starship. When he came to the store, he saw starships with numbers from $l$ to $r$ inclusively. While in the store, Hateehc wanted to find a starship with the luckiest number. Since there are a lot of starships in the store, and Hateehc can't program, you have to help the blogger and write a program that answers his question.
Let $r - l \geq 100$. Then it is easy to see that there exists a number $k$ such that $l \le k \le r$, and $k \equiv 90 \mod 100$. Then the number $k$ is the answer. If $r - l < 100$, you can find the answer by trying all the numbers. Despite the impressive constant, from the theoretical point of view we obtain a solution with asymptotics $O(1)$ for the answer to the query.
[ "brute force", "implementation" ]
900
null
1808
B
Playing in a Casino
Galaxy Luck, a well-known casino in the entire solar system, introduces a new card game. In this game, there is a deck that consists of $n$ cards. Each card has $m$ numbers written on it. Each of the $n$ players receives exactly one card from the deck. Then all players play with each other in pairs, and each pair of players plays exactly once. Thus, if there are, for example, four players in total, then six games are played: the first against the second, the first against the third, the first against the fourth, the second against the third, the second against the fourth and the third against the fourth. Each of these games determines the winner in some way, but the rules are quite complicated, so we will not describe them here. All that matters is how many chips are paid out to the winner. Let the first player's card have the numbers $a_1, a_2, \dots, a_m$, and the second player's card — $b_1, b_2, \dots, b_m$. Then the winner of the game gets $|a_1 - b_1| + |a_2 - b_2| + \dots + |a_m - b_m|$ chips from the total pot, where $|x|$ denotes the absolute value of $x$. To determine the size of the total pot, it is necessary to calculate the winners' total winnings for all games. Since there can be many cards in a deck and many players, you have been assigned to write a program that does all the necessary calculations.
You may notice that the problem can be solved independently for each column of the input matrix. The answer is then the sum $\sum\limits_{i = 1}^n \sum\limits_{j = i + 1}^n |a_i - a_j|$, where $a$ - array representing a column. Let's try to calculate this sum for each column. Let's sort all elements of the current column. Let's calculate the answer for some element in the sorted list. The answer for it will be $a_i \cdot i - sum$, where $sum$ is the sum on the prefix. Why is this so? Because we say that this number is larger than the others and the modulus will then decompose as $a_i - a_j$, and this is already easy to count.
[ "math", "sortings" ]
1,200
null
1808
C
Unlucky Numbers
{In this problem, unlike problem A, you need to look for \textbf{unluckiest number}, not the luckiest one.} \textbf{Note that the constraints of this problem differ from such in problem A.} Olympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively. Each starship has a number —some positive integer $x$. Let's define the luckiness of a number $x$ as the difference between the largest and smallest digits of that number. For example, $142857$ has $8$ as its largest digit and $1$ as its smallest digit, so its luckiness is $8-1=7$. And the number $111$ has all digits equal to $1$, so its luckiness is zero. Hateehc is a famous Martian blogger who often flies to different corners of the solar system. To release interesting videos even faster, he decided to buy himself a starship. When he came to the store, he saw starships with numbers from $l$ to $r$ inclusively. While in the store, Hateehc wanted to find a starship with the \textbf{unluckiest} number. Since there are a lot of starships in the store, and Hateehc can't program, you have to help the blogger and write a program that answers his question.
Check all pairs ($l$, $r$) - the minimum and maximum digits of the number from the answer. Discard the common prefix of $l$ and $r$. Now we are left with some digits $a$ and $b$ as the leftmost digits of the number, with $a$ < $b$. If $b - a \geq 2$, then we can put $a + 1$ at the beginning of the number, and then put any digit from the interval $[l, r]$. Otherwise, we try $a$, and then always put the largest digit of $[l, r]$ that we can. Similarly, then try putting $b$, and then always put the smallest digit of $[l, r]$ you can. Of all $l$ and $r$, for which it is possible to construct a given number, choose such that $r - l$ is minimal, and the number constructed at these $l$ and $r$.
[ "brute force", "dp", "greedy", "implementation" ]
1,900
null
1808
D
Petya, Petya, Petr, and Palindromes
Petya and his friend, the robot Petya++, have a common friend — the cyborg Petr#. Sometimes Petr# comes to the friends for a cup of tea and tells them interesting problems. Today, Petr# told them the following problem. A palindrome is a sequence that reads the same from left to right as from right to left. For example, $[38, 12, 8, 12, 38]$, $[1]$, and $[3, 8, 8, 3]$ are palindromes. Let's call the palindromicity of a sequence $a_1, a_2, \dots, a_n$ the minimum count of elements that need to be replaced to make this sequence a palindrome. For example, the palindromicity of the sequence $[38, 12, 8, 38, 38]$ is $1$ since it is sufficient to replace the number $38$ at the fourth position with the number $12$. And the palindromicity of the sequence $[3, 3, 5, 5, 5]$ is two since you can replace the first two threes with fives, and the resulting sequence $[5, 5, 5, 5, 5]$ is a palindrome. Given a sequence $a$ of length $n$, and an \textbf{odd} integer $k$, you need to find the sum of palindromicity of all subarrays of length $k$, i. e., the sum of the palindromicity values for the sequences $a_i, a_{i+1}, \dots, a_{i+k-1}$ for all $i$ from $1$ to $n-k+1$. The students quickly solved the problem. Can you do it too?
Let us see when $1$ is added to the palindrome. Let there be some string $s$ of odd length $k$, consider the index $i$ to the left of the central one. If this character and the corresponding one on the right side of the string are different, we can replace one of the characters with the other and get $+1$ to the answer. Now the problem is as follows: count the number of indices on all substring of length $k$ such that they differ from the corresponding character in that substring. Let's solve the inverse problem: count the number of indices for all substring of length $k$ such that the given symbol and its corresponding one are equal. Then simply subtract from the maximum possible number of differences the required number of matches. Try some symbol $c$ and count for it the number of matches in all substring. Create a new array $a$ of length $n$, that $a_i=1$ when $s_i=c$, otherwise $a_i=0$. Now we have to count the number of indices $i$ and $j$ such that $i<j$, $a_i \cdot a_j=1$, $j-i < k$ and $(j-i)$ mod $2=0$ (i.e. the distance between indices is even). Let's fix some $j$ where $a_j=1$, then indexes $j-2$, $j-4$, etc. fit the parity condition. Then we can calculate prefix sums for each parity of indices. That is, $pf_{i,par}$ means the sum on prefix length $i$ over all indices with parity equal to $par$. Then $pf_{j-2,par}$, where $par=j$ $mod$ $2$ is subtracted from the answer for some fixed $j$. Total we get the solution for $O(n\cdot maxA)$, where $maxA$ is the number of different characters of the string. To solve the problem faster, we will use the work from the previous solution. Write out separately for each character all its occurrences in the string. Let's go through the symbol and write out all positions with even and odd indices. Solve the problem for even ones (odd ones are solved similarly). We will maintain a sliding window, where the difference between right and left elements is no more than $k$. When we finish iterating after removing the left element, we will subtract the window length $-1$ from the answer, because for the left element of the window exactly as many elements have the same parity on the right at a distance of no more than $k$. P.S. The solution for $O(n\cdot maxA)$ can also be reworked into $O(n \sqrt{n})$ using the trick with <<heavy>> and <<light>> numbers.
[ "binary search", "brute force", "data structures", "two pointers" ]
2,100
null
1808
E1
Minibuses on Venus (easy version)
\textbf{This is the easy version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} Maxim is a minibus driver on Venus. To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of $n$ digits. However, as we know, the residents of Venus use a numeral system with base $k$, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of $n$ integers from $0$ to $k-1$, inclusive. The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo $k$. For example, if $k=10$, then the ticket $7135$ is lucky because $7 + 1 + 5 \equiv 3 \pmod{10}$. On the other hand, the ticket $7136$ is not lucky because no digit is equal to the sum of the others modulo $10$. Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number $m$.
First, let's rephrase the problem condition a bit. A ticket number is lucky if ($a_i$ - the digit that stands at position $i$ in the number) is satisfied: $a_i \equiv (a_1 + a_2 + \ldots + a_{i-1} + a_{i+1} + \ldots + a_{n-1} + a_n) \pmod{k}$ Let $S$ be the sum of all digits of the number. Then we can rewrite the surprise condition: $a_i \equiv S - a_i \pmod{k}$ $2 \cdot a_i \equiv S \pmod{k}$ Thus, if among the digits of the ticket there is such a digit $x$ that: $2 \cdot x \equiv S \pmod{k}$ Then the ticket is lucky. Also note that there are $k^n$ numbers of tickets in total. Let's count how many nosurprising tickets exist. Then, by subtracting this number from $k^n$, we will get the answer to the original problem. So now our goal is to count the number of non-surprising tickets. Given a fixed sum $S$, there are numbers $x$ that: $2 \cdot x \equiv S \pmod{k}$ Therefore, in order for a number with sum $S$ to be unlucky, it must not contain these digits. Let us fix what $S$ modulo $k$ will equal. Now, let's make a DP $f[i][sum]$, where: $i$ - index of the digit to be processed in the ticket $sum$ - the current sum of digits of the ticket, modulo $k$ The basis of DP - $f[0][0] = 1$. We will build transitions from the state $f[i][sum]$ by going through the digit $y$, which we will put at position $i$. Keep in mind that we cannot use such $y$ that: $2 \cdot y \equiv S \pmod{k}$ Depending on $y$ we recalculate $sum$. The number of unlucky ticket numbers, with sum $S$ modulo $k$ will be stored in $f[n][S]$.
[ "combinatorics", "divide and conquer", "dp" ]
2,200
null
1808
E2
Minibuses on Venus (medium version)
\textbf{This is the medium version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} Maxim is a minibus driver on Venus. To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of $n$ digits. However, as we know, the residents of Venus use a numeral system with base $k$, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of $n$ integers from $0$ to $k-1$, inclusive. The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo $k$. For example, if $k=10$, then the ticket $7135$ is lucky because $7 + 1 + 5 \equiv 3 \pmod{10}$. On the other hand, the ticket $7136$ is not lucky because no digit is equal to the sum of the others modulo $10$. Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number $m$.
First, read the editorial of problem E1. This section is a continuation and improvement of ideas from the previous section. Let us improve the solution for $O(nk^3)$. To do this, note that the transitions from $i$ to $i + 1$ can be given by a matrix $g$ of size $k \times k$. Then by multiplying $f[i]$ (i.e., multiplying exactly $1 \times k$ matrix of the form $[f[i][0], f[i][1], \ldots, f[i][k - 1]]$) by this $g$ matrix, we get $f[i + 1]$. Now note that for a fixed sum $S$ modulo $k$, the matrix $g$ will be the same for any $i$. Then let us take $g$ to the power of $n$. Then $f[n]$ can be obtained by calculating $f[0] \cdot g^n$. We can use multiplication algorithm for $O(k^3 \log n)$ to get the matrix powered $n$.
[ "combinatorics", "divide and conquer", "dp", "matrices" ]
2,500
null
1808
E3
Minibuses on Venus (hard version)
\textbf{This is the hard version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} Maxim is a minibus driver on Venus. To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of $n$ digits. However, as we know, the residents of Venus use a numeral system with base $k$, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of $n$ integers from $0$ to $k-1$, inclusive. The residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo $k$. For example, if $k=10$, then the ticket $7135$ is lucky because $7 + 1 + 5 \equiv 3 \pmod{10}$. On the other hand, the ticket $7136$ is not lucky because no digit is equal to the sum of the others modulo $10$. Once, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number $m$.
First read the editorial for problems E1 and E2. This section is a continuation and improvement of ideas from previous sections. Let's calculate how many such digits $x$ can exist in total for a fixed $S$ modulo $k$ that: $2 \cdot x \equiv S \pmod{k}$ $k$ is odd. Then there can exist exactly one such digit $x$ from $0$ to $k - 1$, provided that $S$ - is odd (and it will equal exactly $\frac{S + k}{2}$). $k$ is even. Then there can be two such digits $x_1, x_2$ from $0$ to $k - 1$, provided that $S$ - is even (with $x_1 = \frac{k}{2}, x_2 = \frac{S + k}{2}$). Let's solve the problem when $k$ is odd. Calculate how many different $S$ exist that for them there exists a digit $x$ (denote the set of such $S$ as $cnt_1$), and calculate how many different $S$ exist that for them there is no such digit $x$ (denote the set of such $S$ as $cnt_0$). If $S$ enters $cnt_0$, then the number of unsurprising ticket numbers will be $k^{n-1}$ (Since the total numbers $k^n$ are exactly $\frac{1}{k}$ of them will have some $S$ from $0$ to $k - 1$ modulo $k$). So it is sufficient to add $|cnt_0| \cdot k^{n-1}$ to the number of unsurprising tickets. If $S$ enters $cnt_1$, let's use the following trick: subtract from each digit in the number $x$. Now we have reduced the original problem to the case where $x = 0$. Now let's count the DP $f[i][flag]$ - the number of unlucky numbers, where: $i$ - how many digits of the ticket we've already looked at $flag = 1$ if the current sum of digits is greater than zero, and $flag = 0$ otherwise. This DP can be counted in $O(\log n)$, again using the binary exponentiation of the matrix $2 \times 2$ (the content of the matrix is justified by the fact that the numbers must not contain $x = 0$): $\begin{pmatrix} 0 & k - 1\\ 1 & k - 2 \end{pmatrix}$ After calculating the DP, it is necessary to enumerate all possible variants of $x$ and variants of $S'$. If the condition is satisfied: $2 \cdot x \equiv (S' + x \cdot n) \pmod{k}$ Then we can add to the number of unsurprising numbers: $f[n][0]$ if $S' = 0$ $\frac{f[n][1]}{k - 1}$ if $S' \neq 0$ (note that division must be done modulo $m$). The reason for division is that $f[n][1]$ is the number of all numbers with $S' \neq 0$, and we need the number of numbers with some particular sum of $S'$. The approach to solving for even $k$ will be almost identical to the approach for odd $k$. The difference will be that we can now have either two $x_1, x_2$ when $S$ is fixed, or none. When there are no $x$-ones, the solution is the same as the solution for $cnt_0$ of odd $k$. When there is $x_1, x_2$, we can see that they differ by $\frac{k}{2}$. So let's again subtract $x_1$ from each digit in the number and then double each digit after that. That is, we now work with the numbers $0, 2, \ldots, 2\cdot (k - 2), 0, 2, \ldots (k - 2)$. The matrix for DP transitions will now have the form: $\begin{pmatrix} 0 & k - 2\\ 2 & k - 4 \end{pmatrix}$ After calculating the DP, it is necessary to enumerate all matching pairs $x_1, x_2$ and variants of $S'$. If the condition is satisfied: $2 \cdot x_1 \equiv (S' + x_1 \cdot n) \pmod{k}$ Then we can add to the number of unsurprising numbers: $\frac{f[n][0]}{2}$ if $S' = 0$ (note that division must be done modulo $m$). The division is justified by the fact that $f[n][0]$ is the number of all numbers with $S' = 0$, but now we have two different "zero" sums (since we have dominated all numbers by 2). $\frac{f[n][1]}{k - 2}$ if $S' \neq 0$ (note that division must be done modulo $m$). The reason for division is that $f[n][1]$ is the number of all numbers with $S' \neq 0$, and we need the number of numbers with some particular sum of $S'$.
[ "brute force", "combinatorics", "dp", "math" ]
2,800
null
1809
A
Garland
You have a garland consisting of $4$ colored light bulbs, the color of the $i$-th light bulb is $s_i$. Initially, all the light bulbs are turned off. Your task is to turn all the light bulbs on. You can perform the following operation any number of times: select a light bulb and switch its state (turn it on if it was off, and turn it off if it was on). The only restriction on the above operation is that you can apply the operation to a light bulb only if the previous operation was applied to a light bulb of a different color (the first operation can be applied to any light bulb). Calculate the minimum number of operations to turn all the light bulbs on, or report that this is impossible.
Note that there are only a few configuration classes: 1111, 1112, 1122, 1123 and 1234. Let's discuss each of them. If all $4$ bulbs are of the same color, then it is impossible to turn all the bulbs on, because after you switch one light bulb, it is impossible to turn the others on. If there is a color with $3$ bulbs, then it is impossible to turn all the bulbs on in $4$ operations, which means there is a bulb that turns on, turns off and then turns on again, i.e. the answer is at least $6$ operations. And there is a sequence of exactly $6$ operations (such an example was shown in the problem notes). For configurations like 1122 and 1123, it is enough to turn on the $1$ color bulbs not in a row (i.e. in order $[1, 2, 1, 2]$ for the first case and $[1, 2, 1, 3]$ for the second one). So the answer for such configurations is $4$. If all the bulbs are of different colors, then nothing prevents you from turning them all on in $4$ operations.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int tc; cin >> tc; while (tc--) { string s; cin >> s; vector<int> cnt(10); for (auto c : s) ++cnt[c - '0']; int mx = *max_element(cnt.begin(), cnt.end()); if (mx == 4) cout << -1; else if (mx == 3) cout << 6; else cout << 4; cout << '\n'; } }
1809
B
Points on Plane
You are given a two-dimensional plane, and you need to place $n$ chips on it. You can place a chip only at a point with integer coordinates. The cost of placing a chip at the point $(x, y)$ is equal to $|x| + |y|$ (where $|a|$ is the absolute value of $a$). The cost of placing $n$ chips is equal to the \textbf{maximum} among the costs of each chip. You need to place $n$ chips on the plane in such a way that the Euclidean distance between each pair of chips is \textbf{strictly greater} than $1$, and the cost is the minimum possible.
Suppose, the answer is $k$. What's the maximum number of chips we can place? Firstly, the allowed points $(x, y)$ to place chips are such that $|x| + |y| \le k$. We can group them by $x$-coordinate: for $x = k$ there is only one $y = 0$, for $x = k - 1$ possible $y$ are $-1, 0, 1$; for $x = k - 2$ possible $y$ are in segment $[-2, \dots, 2]$ and so on. For $x = 0$ possible $y$ are in $[-k, \dots, k]$. The negative $x$-s are the same. Let's calculate the maximum number of chips we can place at each "row": for $x = k$ it's $1$; for $x = k - 1$ there are three $y$-s, but since we can't place chips at the neighboring $y$-s, we can place at most $2$ chips; for $x = k - 2$ we have $5$ places, but can place only $3$ chips; for $x = 0$ we have $2k + 1$ places, but can occupy only $k + 1$ points. In total, for $x \in [0, \dots, k]$ we can place at most $1 + 2 + \dots + (k + 1) = \frac{(k + 1)(k + 2)}{2}$ chips. Analogically, for $x \in [-k, \dots, -1]$ we can place at most $1 + 2 + \dots + k = \frac{k (k + 1)}{2}$ chips. In total, we can place at most $\frac{(k + 1)(k + 2)}{2} + \frac{k (k + 1)}{2} = (k + 1)^2$ chips with cost at most $k$. Note that $(k + 1)^2$ can actually be reached since the distance between chips on the different rows is greater than $1$. So, to solve our task, it's enough to find minimum $k$ such that $(k + 1)^2 \ge n$ that can be done with Binary Search. Or we can calculate $k = \left\lceil \sqrt{n} \right\rceil - 1$. Note that $\sqrt{n}$ can lose precision, since $n$ is cast to double before taking the square root (for example, $975461057789971042$ transforms to $9.754610577899711 \cdot 10^{17} = 975461057789971100$ when converted to double). So you should either cast long long to long double (that consists of $80$ bits in some C++ compilers) or check value $k + 1$ as a possible answer.
[ "binary search", "greedy", "math" ]
1,000
import kotlin.math.sqrt fun main() { repeat(readln().toInt()) { val n = readln().toLong() var ans = sqrt(n.toDouble()).toLong() while (ans * ans > n) ans-- while (ans * ans < n) ans++ println(ans - 1) } }
1809
C
Sum on Subarrays
For an array $a = [a_1, a_2, \dots, a_n]$, let's denote its subarray $a[l, r]$ as the array $[a_l, a_{l+1}, \dots, a_r]$. For example, the array $a = [1, -3, 1]$ has $6$ non-empty subarrays: - $a[1,1] = [1]$; - $a[1,2] = [1,-3]$; - $a[1,3] = [1,-3,1]$; - $a[2,2] = [-3]$; - $a[2,3] = [-3,1]$; - $a[3,3] = [1]$. You are given two integers $n$ and $k$. Construct an array $a$ consisting of $n$ integers such that: - all elements of $a$ are from $-1000$ to $1000$; - $a$ has exactly $k$ subarrays with positive sums; - the rest $\dfrac{(n+1) \cdot n}{2}-k$ subarrays of $a$ have negative sums.
There are many ways to solve this problem. I will describe the following recursive solution: if $k < n$, let's compose an array where every segment ending with the $k$-th element is positive, and every other segment is negative. This array can be $[-1, -1, -1, \dots, 200, -400, -1, -1, -1]$, where $200$ is the $k$-th element of the array (note that when $k = 0$, $200$ doesn't belong to the array, so it consists of only negative numbers). but if $k \ge n$, solve the same problem with $n-1$ and $k-n$ recursively, get an array of length $n-1$ with $k-n$ positive subarrays, and append $1000$ to it to make all $n$ segments ending with the last element positive.
[ "constructive algorithms", "greedy", "math" ]
1,500
def solve(n, k): if n == 0: return [] if k < n: a = [-1 for i in range(n)] if k > 0: a[k - 1] = 200 a[k] = -400 else: a = solve(n - 1, k - n) a.append(1000) return a t = int(input()) for i in range(t): n, k = map(int, input().split()) b = solve(n, k) print(*b)
1809
D
Binary String Sorting
You are given a binary string $s$ consisting of only characters 0 and/or 1. You can perform several operations on this string (possibly zero). There are two types of operations: - choose two consecutive elements and swap them. In order to perform this operation, you pay $10^{12}$ coins; - choose any element from the string and remove it. In order to perform this operation, you pay $10^{12}+1$ coins. Your task is to calculate the minimum number of coins required to sort the string $s$ in non-decreasing order (i. e. transform $s$ so that $s_1 \le s_2 \le \dots \le s_m$, where $m$ is the length of the string after applying all operations). An empty string is also considered sorted in non-decreasing order.
Note that the price of operations is much greater than the difference between them. Therefore, first of all, we have to minimize the number of operations, and then maximize the number of operations of the first type. Swapping two elements if at least one of them will be deleted later is not optimal. Therefore, first let's delete some elements of the string, and then sort the remaining elements using swaps. The number of swaps for sorting is equal to the number of inversions (i. e. the number of pairs such that $s_j > s_i$ and $j < i$). From here we can notice that if the number of inversions is greater than $1$, then there is an element that produces at least $2$ inversions. So it is more profitable for us to remove it, to minimize the number of operations. From the above we get that the number of operations of the first type is at most $1$. If all operations are only of the second type, then we need to find a subsequence of the maximum length of the form 0000111111. To do this, we can iterate over the number of zeros that we include in the final string, and then add the number of ones from the remaining suffix of the string (that goes after the fixed number of zeros). If there is an operation of the first type, then it is enough to iterate over the pair that creates the inversion, to the left of it take all zeros, and to the right of it take all ones (you can notice that in fact it is enough to iterate over only a pair of neighboring elements of the string).
[ "constructive algorithms", "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; const long long pw10 = 1e12; int main() { ios::sync_with_stdio(false); cin.tie(0); int tc; cin >> tc; while (tc--) { string s; cin >> s; int n = s.size(); int cnt0 = 0, cnt1 = count(s.begin(), s.end(), '1'); long long ans = 1e18; if (n == 1) ans = 0; for (int i = 0; i < n - 1; ++i) { cnt0 += s[i] == '0'; cnt1 -= s[i] == '1'; int k = cnt0 + cnt1 + (s[i] == '1') + (s[i + 1] == '0'); long long cur = (n - k) * (pw10 + 1); if (s[i] > s[i + 1]) cur += pw10; ans = min(ans, cur); } cout << ans << '\n'; } }
1809
E
Two Tanks
There are two water tanks, the first one fits $a$ liters of water, the second one fits $b$ liters of water. The first tank has $c$ ($0 \le c \le a$) liters of water initially, the second tank has $d$ ($0 \le d \le b$) liters of water initially. You want to perform $n$ operations on them. The $i$-th operation is specified by a single non-zero integer $v_i$. If $v_i > 0$, then you try to pour $v_i$ liters of water from the first tank into the second one. If $v_i < 0$, you try to pour $-v_i$ liters of water from the second tank to the first one. When you try to pour $x$ liters of water from the tank that has $y$ liters currently available to the tank that can fit $z$ more liters of water, the operation only moves $\min(x, y, z)$ liters of water. For all pairs of the initial volumes of water $(c, d)$ such that $0 \le c \le a$ and $0 \le d \le b$, calculate the volume of water in the first tank after all operations are performed.
Consider a naive solution. Iterate over all pairs $(c, d)$ and apply all operations. The complexity is $O(a \cdot b \cdot n)$. The constraints obviously imply that it's too much. What can we cut from it? Well, surely $O(n)$ will still remain there. Both of $a$ and $b$ also should. So we can probably only hope to turn this $O(ab)$ into $O(a + b)$. Let's try that. Notice that no matter what operations are applied, $c + d$ never changes. You can also peek at the examples and see that the patterns are suspiciously diagonal-shaped in the matrix. Let's try to solve the problem by fixing $c + d$ and calculating the answer for all values of $c$. I will call the fixed $c + d$ variable $\mathit{cd}$. Consider case where $\mathit{cd} \le a$ and $\mathit{cd} \le b$. Here, all $\mathit{cd}$ can fit into both $a$ and $b$, so we can avoid caring about one restriction on the operations. We'll think what to do with large volumes later. If there are no operations, the answer for each initial $c$ is $c$ for all $c$ from $0$ to $\mathit{cd}$. Now consider an operation $x$ for some $x > 0$. For $c = 0$, nothing changes. Actually, for all $c \le x$ the result of the operation is the same as for $c = 0$. Hmm, but if the result is the same, it will remain the same until the end. Same from the other side. The answers for $x < 0$ and $d \le -x$ also get merged together. To me it kind of looks like a primitive form of DSU on these volume states: you merge some prefix of the answers together and merge some suffix of the answers together. If the state was merged to either $c = 0$ or $d = 0$, then it's easy to calculate the actual answer for that state. What happens to the remaining states? Well, since they weren't merged anywhere, the operation for them was applied fully: if $x$ was requested, all $x$ was poured. How to deal with multiple operations then? I propose the following idea. When applying an operation, we only want to know which of the previously non-merged states become merged. Basically, we can squish all previous operations into one: just sum up the signed amounts of water. Since they all were applied fully to the non-merged states, it's completely valid. After the squish, check for the new merges. You can actually study the structure of the answers and see that they go like that: $[l, l, \dots, l, l + 1, l + 2, \dots, r - 1, r, \dots, r, r]$ for some values of $l$ and $r$ such that $l \le r$. It isn't that important, but it makes the code easier. You can basically calculate the length of the merged prefix, the length of the merged suffix, then calculate the answer at the end of the prefix in $O(n)$ and restore all answers from it. We neglected larger values of $\mathit{cd}$ earlier, time to return to them. Another kind of limit to each operation is added: when $x$ extra water doesn't fit in another tank. Well, it doesn't change that much. It only makes more prefix/suffix merges. To come up with the exact formulas, I followed these points. Something merges on an operation $x$, when any of these holds: $c < x$ (not enough water in the first tank); $b - d < x$ (not enough space in the second tank); $d < -x$ (not enough water in the second tank); $a - c < -x$ (not enough space in the first tank). Replace all $d$ with $\mathit{cd} - c$, and you get the constraints for prefix and suffix merges. Overall complexity: $O(n \cdot (a + b))$.
[ "binary search", "dp", "implementation", "math" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int n, a, b; scanf("%d%d%d", &n, &a, &b); vector<int> v(n); forn(i, n) scanf("%d", &v[i]); vector<vector<int>> ans(a + 1, vector<int>(b + 1)); forn(cd, a + b + 1){ int l = max(0, cd - b), r = min(a, cd); int sum = 0; for (int x : v){ sum += x; l = max({l, sum, cd + sum - b}); r = min({r, a + sum, sum + cd}); } if (l > r) l = r = max(0, cd - b); int res = l; for (int x : v){ if (x > 0) res -= min({res, x, b - (cd - res)}); else res += min({cd - res, -x, a - res}); } forn(c, cd + 1) if (c <= a && cd - c <= b){ ans[c][cd - c] = (c < l ? res : (c > r ? res + r - l : res + c - l)); } } forn(i, a + 1){ forn(j, b + 1) printf("%d ", ans[i][j]); puts(""); } return 0; }
1809
F
Traveling in Berland
There are $n$ cities in Berland, arranged in a circle and numbered from $1$ to $n$ in clockwise order. You want to travel all over Berland, starting in some city, visiting all the other cities and returning to the starting city. Unfortunately, you can only drive along the Berland Ring Highway, which connects all $n$ cities. The road was designed by a very titled and respectable minister, so it is one-directional — it can only be traversed clockwise, only from the city $i$ to the city $(i \bmod n) + 1$ (i.e. from $1$ to $2$, from $2$ in $3$, ..., from $n$ to $1$). The fuel tank of your car holds up to $k$ liters of fuel. To drive from the $i$-th city to the next one, $a_i$ liters of fuel are needed (and are consumed in the process). Every city has a fuel station; a liter of fuel in the $i$-th city costs $b_i$ burles. Refueling between cities is not allowed; if fuel has run out between cities, then your journey is considered incomplete. For each city, calculate the minimum cost of the journey if you start and finish it in that city.
The problem has a rather obvious naive solution in $O(n)$ for each starting city, but it's too slow. So we have to speed up this solution somehow. Binary lifting is one of the options, but here we have a problem that it is difficult to connect two consecutive groups of steps, because after the first group there is a certain amount of fuel left. Therefore, one of the solutions is to switch to such steps that $0$ liters of fuel remains after it. Let's consider one of such "greedy" steps. Suppose we are in the city $i$ with $0$ fuel, then the following situations are possible: $b_i=2$, let's buy exactly $a_i$ liters of fuel to reach the next city, then the step length is $1$ and the cost is $2a_i$; $b_i=1$ and $cnt=0$ (where $cnt$ is the maximum number such that $b_{i+1}=2$, $b_{i+2}=2$, ..., $b_{i+cnt}=2$, i.e. the number of consecutive cities with the cost $2$), let's buy exactly $a_i$ liters of fuel to reach the next city, then the step length is $1$ and the cost is $a_i$; $b_i=1$ and $cnt>0$, let's find a minimum $j$ such that $sum = a_i + a_{i+1} + \dots + a_j \ge k$ and $j \le i + cnt$ (i.e. such $j$ that you can reach it by spending all $k$ of liters): $sum \le k$, let's buy exactly $sum$ liters with the cost $1$ in the city $i$, then the step length is $j-i+1$ and the cost is $sum$; $sum > k$, let's buy $k$ liters with the cost $1$ in the city $i$, and the remainder of $sum - k$ liters with the cost $2$ in the city $j$, then the step length is $j-i+1$ and the cost is $k + 2(sum-k)$. $sum \le k$, let's buy exactly $sum$ liters with the cost $1$ in the city $i$, then the step length is $j-i+1$ and the cost is $sum$; $sum > k$, let's buy $k$ liters with the cost $1$ in the city $i$, and the remainder of $sum - k$ liters with the cost $2$ in the city $j$, then the step length is $j-i+1$ and the cost is $k + 2(sum-k)$. Now using these types of steps, we maintain an important invariant - after each step, the amount of fuel is $0$. So we can easily calculate the total distance and cost for several consecutive steps. Which leads us to a solution using binary lifting: for each city $i$ calculate the length and cost of the path with $2^{pw}$ (for all $pw$ up to $\log{n}$) greedy steps. And then, using this data, we can calculate the answer for each starting city in $O(\log{n})$.
[ "binary search", "data structures", "graphs", "greedy", "implementation" ]
2,500
#include<bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) void solve(){ int n, k; scanf("%d%d", &n, &k); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); vector<int> b(n); forn(i, n) scanf("%d", &b[i]); vector<long long> pr(2 * n + 1); forn(i, 2 * n) pr[i + 1] = pr[i] + a[i % n]; vector<long long> dist(n); vector<long long> cost(n); int cnt = 0; for (int i = 2 * n - 1; i >= 0; --i){ if (i < n){ if (b[i] == 2){ dist[i] = 1; cost[i] = a[i] * 2; } else if (cnt == 0){ dist[i] = 1; cost[i] = a[i]; } else{ int j = lower_bound(pr.begin() + i, pr.begin() + i + cnt + 1, pr[i] + k) - pr.begin(); assert(j > i); dist[i] = j - i; if (pr[j] - pr[i] <= k) cost[i] = pr[j] - pr[i]; else cost[i] = 2 * (pr[j] - pr[i]) - k; } } if (b[i % n] == 2) ++cnt; else cnt = 0; } int pw = 0; while ((1 << pw) <= n) ++pw; vector<vector<long long>> distk(pw, dist); vector<vector<long long>> costk(pw, cost); for (int j = 1; j < pw; ++j) forn(i, n){ distk[j][i] = distk[j - 1][i] + distk[j - 1][(i + distk[j - 1][i]) % n]; costk[j][i] = costk[j - 1][i] + costk[j - 1][(i + distk[j - 1][i]) % n]; } forn(i, n){ int pos = i; long long tot = 0; long long ans = 0; for (int j = pw - 1; j >= 0; --j) if (tot + distk[j][pos] <= n){ tot += distk[j][pos]; ans += costk[j][pos]; pos = (pos + distk[j][pos]) % n; } if (tot < n) ans += pr[i + n] - pr[i + tot]; printf("%lld ", ans); } puts(""); } int main(){ int tc; scanf("%d", &tc); while (tc--) solve(); }
1809
G
Prediction
Consider a tournament with $n$ participants. The rating of the $i$-th participant is $a_i$. The tournament will be organized as follows. First of all, organizers will assign each participant an index from $1$ to $n$. All indices will be unique. Let $p_i$ be the participant who gets the index $i$. Then, $n-1$ games will be held. In the first game, participants $p_1$ and $p_2$ will play. In the second game, the winner of the first game will play against $p_3$. In the third game, the winner of the second game will play against $p_4$, and so on — in the last game, the winner of the $(n-2)$-th game will play against $p_n$. Monocarp wants to predict the results of all $n-1$ games (of course, he will do the prediction only after the indices of the participants are assigned). He knows for sure that, when two participants with ratings $x$ and $y$ play, and $|x - y| > k$, the participant with the higher rating wins. But if $|x - y| \le k$, any of the two participants may win. Among all $n!$ ways to assign the indices to participants, calculate the number of ways to do this so that Monocarp can predict the results of \textbf{all} $n-1$ games. Since the answer can be large, print it modulo $998244353$.
We need some sort of better criterion other than "all matches can be predicted" first. Suppose the ratings of the participants are $r_1, r_2, \dots, r_n$ in the order of their indices. Then, if all games are predictable, the $i$-th game should be won by the participant with the rating equal to $\max \limits_{j=1}^{i+1} r_j$; and in the $(i+1)$-th game, they will play against the participant with rating $r_{i+2}$. So, in order for each game to be predictable, the maximum on each prefix should be different from the next element by at least $k+1$. This is the criterion we will use. So, we will try to count the number of orderings meeting this condition. One very important observation we need to make is that, if we remove several participants with the lowest ratings from the ordering, that ordering still satisfies the condition (for each element, either the prefix before it is removed completely, or the maximum on it is unchanged). So, this allows us to construct the correct ordering by placing the sportsmen from the maximum rating to the minimum rating, and making sure that on every step, the order stays correct. Okay. Let's reverse the ratings array, and try to write the following dynamic programming: $dp_i$ is the number of correct orderings of the first $i$ sportsmen (the $i$ highest-rated sportsmen, since we reversed the ratings array). Let's try to place the next sportsman. We run into the following issue: for some orderings of the first $i$ sportsmen, it is possible to place the next one anywhere (these orderings are where the first sportsman in the ordering doesn't conflict with the sportsman we are trying to place); but for other orderings, some positions might be forbidden. And to keep track of which positions are forbidden, and for which sportsmen, we probably need some additional states for the dynamic programming, which we don't really want to since $O(n)$ states is probably the most we can allow. Okay, so let's avoid this issue entirely. We don't like the orderings where the next sportsman can't be placed anywhere, so let's find a way to "ignore" them: discard the previous definition of $dp_i$. Now, let $dp_i$ is the number of correct orderings of the $i$ highest-rated sportsmen where the first element in the ordering doesn't conflict with any of the elements we haven't placed yet; when we place the next sportsman, in case it becomes the first element and conflicts with some of the elements we haven't placed yet, we place those conflicting elements as well. So, this leads to the following transitions in the dynamic programming: if we place the $(i+1)$-th sportsman on any position other than the first one, there are $i$ ways to do it, and we transition from $dp_{i}$ to $dp_{i+1}$; otherwise, if we place the $(i+1)$-th sportsman on the first position, let $f(i+1)$ be the last sportsman "conflicting" with the sportsman $i+1$. Let's try placing all sportsmen from $i+2$ to $f(i+1)$ before placing the sportsman $i+1$. They cannot be placed on the first position (otherwise they will conflict either with each other or with the sportsman $i+1$), so the first one can be placed in $i$ ways, the second one - in $(i+1)$ ways, and so on; this product can be easily calculated in $O(1)$ by preparing factorials and inverse factorials. So, then we transition from $dp_i$ to $dp_{f(i+1)}$. There is a special case in our dynamic programming. It should start with $dp_1 = 1$, but what if the $1$-st sportsman conflicts with someone? Then the ordering of the first $i=1$ sportsmen is incorrect. In this case, the answer is $0$ since the $1$-st and the $2$-nd sportsmen are conflicting. Overall complexity of this solution is $O(n \log MOD)$ or $O(n + \log MOD)$ depending on your implementation.
[ "combinatorics", "dp", "math" ]
2,800
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { return ((x + y) % MOD + MOD) % MOD; } int mul(int x, int y) { return x * 1ll * y % MOD; } int binpow(int x, int y) { int z = 1; while(y) { if(y % 2 == 1) z = mul(z, x); x = mul(x, x); y /= 2; } return z; } int inv(int x) { return binpow(x, MOD - 2); } int divide(int x, int y) { return mul(x, inv(y)); } int main() { int n, k; scanf("%d %d", &n, &k); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); reverse(a.begin(), a.end()); vector<int> fact(n + 1); fact[0] = 1; for(int i = 1; i <= n; i++) fact[i] = mul(fact[i - 1], i); // for each player, we find the first player which doesn't conflict with them vector<int> first_no_conflict(n); for(int i = 0; i < n; i++) { if(i) first_no_conflict[i] = first_no_conflict[i - 1]; while(first_no_conflict[i] < n && a[first_no_conflict[i]] >= a[i] - k) first_no_conflict[i]++; } vector<int> dp(n + 1); if(a[0] - a[1] > k) dp[1] = 1; for(int i = 1; i < n; i++) { // first choice: put a[i] on the first position // then we put all which conflict with a[i] on any position other than 1 int no_of_conflicting = first_no_conflict[i] - i - 1; // put all conflicting with a[i] on any position other than 1 // the first one chooses from i positions, the second - from i+1 positions, and so on // so the number of ways is fact[i + no_of_conflicting - 1] / fact[i - 1] dp[i + no_of_conflicting + 1] = add(dp[i + no_of_conflicting + 1], mul(dp[i], divide(fact[i + no_of_conflicting - 1], fact[i - 1]))); // second choice: put a[i] on any other position dp[i + 1] = add(dp[i + 1], mul(dp[i], i)); } printf("%d\n", dp[n]); }
1810
A
Beautiful Sequence
A sequence of $m$ integers $a_{1}, a_{2}, \ldots, a_{m}$ is good, if and only if there exists at least one $i$ ($1 \le i \le m$) such that $a_{i} = i$. For example, $[3,2,3]$ is a good sequence, since $a_{2} = 2$, $a_{3} = 3$, while $[3,1,1]$ is not a good sequence, since there is no $i$ such that $a_{i} = i$. A sequence $a$ is beautiful, if and only if there exists at least one subsequence of $a$ satisfying that this subsequence is good. For example, $[4,3,2]$ is a beautiful sequence, since its subsequence $[4,2]$ is good, while $[5,3,4]$ is not a beautiful sequence. A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements. Now you are given a sequence, check whether it is beautiful or not.
What is the necessary and sufficient condition? The necessary and sufficient condition for a beautiful sequence is that there exist one $i$, such that $a_{i} \le i$. Just check the sequence for the condition.
[ "brute force", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; int a[100005]; void solve() { int n; scanf("%d",&n); for(int i =1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1;i <= n;i++) { if(a[i] <= i) { puts("YES"); return; } } puts("NO"); } int main() { int t;scanf("%d",&t); while(t--) solve(); }
1810
B
Candies
This problem is about candy. Initially, you only have $1$ candy, and you want to have exactly $n$ candies. You can use the two following spells in any order at most $40$ times in total. - Assume you have $x$ candies now. If you use the first spell, then $x$ candies become $2x-1$ candies. - Assume you have $x$ candies now. If you use the second spell, then $x$ candies become $2x+1$ candies. Construct a sequence of spells, such that after using them in order, you will have \textbf{exactly} $n$ candies, or determine it's impossible.
How the binary representation changes after an operation? First, we notice that after each operation, the number of candies is always a odd number. So even numbers can not be achieved. Then consider how the binary representation changes for a odd number $x$, after turn it into $2x+1$ or $2x-1$. For the $2x + 1$ operation: $\overline{\dots 1}$ turns into $\overline{\dots 11}$. For the $2x + 1$ operation: $\overline{\dots 1}$ turns into $\overline{\dots 11}$. For the $2x - 1$ operation: $\overline{\dots 1}$ turns into $\overline{\dots 01}$. For the $2x - 1$ operation: $\overline{\dots 1}$ turns into $\overline{\dots 01}$. So, the operation is just insert a $0/1$ before the last digit. And the answer for an odd $n$ is just the binary representation of $n$, after removing the last digit.
[ "constructive algorithms", "math", "number theory" ]
800
#include<bits/stdc++.h> using namespace std; void solve() { int n;scanf("%d",&n); if(n % 2 == 0) { puts("-1");return; } vector<int> v; int f = 0; for(int i = 29;i >= 1;i--) { if((n >> i) & 1) { f = 1; v.push_back(2); } else if(f) { v.push_back(1); } } printf("%d\n",v.size()); for(auto x : v) { printf("%d ",x); } printf("\n"); } int main() { int t;scanf("%d",&t); while(t--) solve(); return 0; }
1810
C
Make It Permutation
You have an integer array $a$ of length $n$. There are two kinds of operations you can make. - Remove an integer from $a$. This operation costs $c$. - Insert an arbitrary positive integer $x$ to any position of $a$ (to the front, to the back, or between any two consecutive elements). This operation costs $d$. You want to make the final array a permutation of \textbf{any} positive length. Please output the minimum cost of doing that. Note that you can make the array empty during the operations, but the final array must contain at least one integer. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
Try the enumerate the length $n$ of permutation. There're too many lengths to be checked. How to decrease the amount of $n$? Firstly, we need to remove numbers such that each number appears at most once, this part of cost is unavoidable. Then, let's sort the array $a_{1},a_{2} \dots a_{m}$ ($1\le a_{i} < a_{2} < \dots < a_{m}$). Secondly, assume we enumerate the length of the permutation $n$. We need to remove all the $a_{i}$ greater than $n$, and insert some numbers $x$ ($x \le n$) but does not appear in the array $a$. We can find some $i$ such that $a_{i} \le n < a_{i+1}$, the cost here is simply $(m-i)\cdot a + (n - i)\cdot b$. Here, $m$ is the length of array $a$, after removing the repeated numbers. However, $n$ can up to $10^9$ and can not be enumerated. But for all the $n \in [a_{i} , a_{i+1})$, the smaller $n$ has a smaller cost. (see that $(m-i)\cdot a$ do not change, and $(n-i)\cdot b$ decreases). Thus, the possible $n$ can only be some $a_{i}$, and we can caculate the cost in $O(n)$ in total. Don't forget the special case: remove all the numbers and add a $1$.
[ "brute force", "greedy", "sortings" ]
1,300
#include<bits/stdc++.h> using namespace std; int p[100005]; typedef long long ll; void solve() { int n,a,b;scanf("%d%d%d",&n,&a,&b); set<int> st; ll sol = 0 , ans = 2e18; for(int i = 1;i <= n;i++) { int x;scanf("%d",&x); if(st.find(x) == st.end()) st.insert(x); else sol += a; } int c = 0; for(auto x : st) p[++c] = x; for(int i = 1;i <= c;i++) { ans = min(ans , 1LL*(p[i] - i)*b + 1LL*(c-i)*a); } ans = min(ans , 1LL*c*a + b) ; printf("%lld\n",ans+sol); } int main() { int t;scanf("%d",&t); while(t--) solve(); }
1810
D
Climbing the Tree
The snails are climbing a tree. The tree height is $h$ meters, and snails start at position $0$. Each snail has two attributes $a$ and $b$ ($a > b$). Starting from the $1$-st day, one snail climbs the tree like this: during the daylight hours of the day, he climbs up $a$ meters; during the night, the snail rests, and he slides down $b$ meters. If on the $n$-th day, the snail reaches position $h$ for the first time (that is, the top of the tree), he will finish climbing, and we say that the snail spends $n$ days climbing the tree. Note that on the last day of climbing, the snail doesn't necessarily climb up $a$ meters, in case his distance to the top is smaller than $a$. Unfortunately, you don't know the exact tree height $h$ at first, but you know that $h$ is a positive integer. There are $q$ events of two kinds. - Event of type $1$: a snail with attributes $a$, $b$ comes and claims that he spent $n$ days climbing the tree. If this message contradicts previously adopted information (i. e. there is no tree for which all previously adopted statements and this one are true), ignore it. Otherwise, adopt it. - Event of type $2$: a snail with attributes $a$, $b$ comes and asks you how many days he will spend if he climbs the tree. You can only give the answer based on the information you have adopted so far. If you cannot determine the answer precisely, report that. You need to deal with all the events in order.
The possible $L$ is always an interval. How to maintain it? The main idea is to that for each $a,b,n$, the possible $L$ is a interval $[l,r]$. We will show how to calculate that. In the first $n-1$ days, the snail will climb $(n-1)\cdot (a-b)$ meters. And in the daytime of the $n$-th day, the snail will climb $a$ meters. So after $n$ days, the snail climbs at most $(n-1)\cdot (a-b) + a$ meters, which means $L \le (n-1)\cdot (a-b) + a$. Also, the snail can not reach $L$ before $n$ days, which means $L > (n-2)\cdot (a-b) + a$. So $L \in [(n-2)\cdot (a-b) + a + 1 , (n-1)\cdot (a-b) + a]$. $n=1$ is a special case, where $L \in [1,a]$ . Now after each operation $1$, we can maintain a possible interval $[L_{min} , L_{max}]$. When a snail comes, we let the new $[L_{min}',L_{max}']$ be $[L_{min},L_{max}] \cap [l,r]$, where $[l,r]$ is the possible interval for the new snail. If the new interval is empty, we ignore this information, otherwise adopt it. Now let's focus on another problem: for a fixed $L,a,b$, how to calculate the number of days the snail needs to climb? We can solve the equation $(n-2)(a-b) + a < L \le (n-1)(a-b) + a$, and get $n - 2 < \frac{L - a}{a - b} \le n - 1$, which means $n$ equals to $\lceil \frac{L-a}{a-b} \rceil + 1$. Still, special judge for $L \le a$, where $n=1$ in this case. Then, for each query of type $2$, we just calculate the number of days we need for $L_{min}$ and $L_{max}$. If they are the same, output that number. Otherwise output $-1$.
[ "binary search", "math" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; void solve() { int q;scanf("%d",&q); ll L = 1 , R = 1e18; while(q--) { int op;scanf("%d",&op) ; if(op == 1) { int a,b,n;scanf("%d%d%d",&a,&b,&n); ll ql = 1LL*(n - 2)*(a - b) + a + 1, qr = 1LL*(n - 1)*(a - b) + a; if(n == 1) ql = 1 , qr = a; if(ql > R || qr < L) { puts("0"); } else L = max(L , ql) , R = min(R , qr) , puts("1"); } else { int a,b;scanf("%d%d",&a,&b); ll ans1 = max(1LL,(L - b - 1) / (a - b) + 1) , ans2 = max(1LL,(R - b - 1) / (a - b) + 1); if(ans1 == ans2) printf("%lld\n",ans1); else puts("-1"); } } return; } int main() { int t;scanf("%d",&t); while(t--) solve(); }
1810
E
Monsters
There is an undirected graph with $n$ vertices and $m$ edges. Initially, for each vertex $i$, there is a monster with danger $a_{i}$ on that vertex. For a monster with danger $a_{i}$, you can defeat it if and only if you have defeated at least $a_{i}$ other monsters before. Now you want to defeat all the monsters. First, you choose some vertex $s$ and defeat the monster on that vertex (since you haven't defeated any monsters before, $a_{s}$ has to be $0$). Then, you can move through the edges. If you want to move from vertex $u$ to vertex $v$, then the following must hold: either the monster on vertex $v$ has been defeated before, or you can defeat it now. For the second case, you defeat the monster on vertex $v$ and reach vertex $v$. You can pass the vertices and the edges any number of times. Determine whether you can defeat all the monsters or not.
How to check whether it is possible to defeat all the monsters, starting from a fixed vertex $u$? Let $S(u)$ be the vertices set that can be reached, starting from vertex $u$. What's the relationship between $S(u)$ and $S(v)$, where $v\in S(u)$? For some vertex set $T$, let's define $E(T)$ as the ''neighbours'' of vertex set $T$. Formally, $v \in E(T)$ if and only if $v \notin T$, but there exist some vertex $u$, such that there's an edge $(u,v)$ in the graph, and $u \in T$. Now let's consider how to solve the problem for some fixed starting vertex $u$? Let's maintain the set $S(u)$ and $E(S(u))$. Initially, $S(u) = {u }$. We keep doing the procedure: choose a vertex $v \in E(S(u))$ with minimal value $a_{v}$. If $a_{v} \le |S(u)|$, we add $v$ into set $S(u)$, and update set $E(S(u))$ simultaneously. Since $S(u)$ is always connected during the procedure, we are actually doing such a thing: find a vertex $v$ that is ''reachable'' now with minimal value $a_{v}$, and try to defeat the monster on it. Our goal is to find some $u$ such that $|S(u)| = n$. Then let's move to a lemma: if $v \in S(u)$, then $S(v) \subseteq S(u)$. If it is not, consider the procedure above and the first time we add some vertex $x$ such that $x \notin S(u)$ into $S(v)$. At this moment, $|S(v)| \le |S(u)|$ must hold(since it's the first time we add some vertex not in $S(u)$). On the other side, $x \in E(S(u))$ must hold, and hence $a_{x} > |S(u)| \ge |S(v)|$. Thus, we can not add $x$ into $S(v)$. Then we can tell, if $|S(u)| < n$, then for $v \in S(u)$, $|S(v)| < n$. So it's unnecessary to search starting from $v$. And we can construct such an algorithm: Search from $1,2,3,\dots n$ in order, if some $i$ has been included in some $S(j)$ before, do not search from it. Surprisingly, this algorithm is correct. We can prove it's time complexity. For each vertex $v$, if $v \in S(u)$ now, and when searching from vertex $u'$, $v$ is add into $S(u')$ again, then $|S(u')| > 2|S(u)|$. Thus, one vertex can not be visited more than $log(n)$ times, which means the time complexity is $O(nlog^2(n))$. This problem has many other methods to solve. This one I think is the easiest to implement.
[ "brute force", "data structures", "dfs and similar", "dsu", "graphs", "greedy" ]
2,100
#include<bits/stdc++.h> using namespace std; int vis[200005]; int n , m; vector<int> E[200005]; int a[200005]; int T = 1; bool span(int u) { set<pair<int,int> > st; st.insert(pair<int,int>{a[u] , u}); int amt = 0 , df = 0; while(st.size()) { auto pa = (*st.begin()) ; vis[pa.second] = u; if(pa.first > df) {return (amt == n);} st.erase(st.begin()); amt++ ; df++ ; for(auto v : E[pa.second]) { if(vis[v] < u) { st.insert(pair<int,int>{a[v] , v}); } } } return (amt == n); } void solve() { scanf("%d%d",&n,&m); for(int i= 1;i <= n;i++) scanf("%d",&a[i]) , vis[i] = 0, E[i].clear(); for(int i = 1;i <= m;i++) { int u,v;scanf("%d%d",&u,&v);E[u].push_back(v) ; E[v].push_back(u); } for(int i = 1;i <= n;i++) { if(a[i] == 0 && !vis[i]) { if(span(i)){puts("YES");return;} } } puts("NO"); } int main() { int t;scanf("%d",&t); while(t--) solve(); }
1810
F
M-tree
A rooted tree is called good if every vertex of the tree either is a leaf (a vertex with no children) or has exactly $m$ children. For a good tree, each leaf $u$ has a positive integer $c_{u}$ written on it, and we define the value of the leaf as $c_{u} + \mathrm{dep}_{u}$, where $\mathrm{dep}_{u}$ represents the number of edges of the path from vertex $u$ to the root (also known as the depth of $u$). The value of a good tree is the \textbf{maximum} value of all its leaves. Now, you are given an array of $n$ integers $a_{1}, a_{2}, \ldots, a_{n}$, which are the integers that should be written on the leaves. You need to construct a good tree with $n$ leaves and write the integers from the array $a$ to all the leaves. Formally, you should assign each leaf $u$ an index $b_{u}$, where $b$ is a permutation of length $n$, and represent that the integer written on leaf $u$ is $c_u = a_{b_{u}}$. Under these constraints, you need to \textbf{minimize} the value of the good tree. You have $q$ queries. Each query gives you $x$, $y$ and changes $a_{x}$ to $y$, and after that, you should output the minimum value of a good tree based on the current array $a$. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
Can you solve a single query using binary search? How to check the answer? Try to find a closed formula for this problem. Let $num_{i}$ be the number of occurances of integer $i$ in the array $a$. To check whether the answer can be $\le x$ or not, we can do the following greedy: Starting with a single vertex written $x$, which is the root. For each $i$(from large ones to small ones), if the number of current leaves is smaller than $num_{i}$, then we can not make the answer $\le x$. Otherwise, let $num_{i}$ leaves stop, and other leaves ''grow'' $m$ children each(these vertices are no longer leaves, but their children are). We can discover that each round, the ''stopped'' vertices have $dep = x - i$, which represents their value is $x$. We can use the following code to calculate it. Since a negtive number multiplies $m$ is still a negtive number, the code can be as following: Find out something? The final $d$ is just $m^x - \sum_{i=1}^{x}{num_{i} \cdot m^i}$, which represents it's equivalent to checking $m^x \ge \sum_{i=1}^{n}{m^{a_{i}}}$! So now the answer is just $\lceil log_{m}{\sum_{i=1}^{n}{m^{a_{i}}}} \rceil$. This is the highest bit plus one of $\sum{m^{a_{i}}}$ in $m$-base representation(except for that it's just some $m^x$. In this case the answer is $x$ but not $x+1$). We can use a segment tree, supporting interval min/max query and interval covering to solve the question.
[ "data structures", "math", "sortings", "trees" ]
2,800
using namespace std; int n , m , q; const int N = 2e5 + 40; int num[N]; int a[N]; int cov[N*4 + 5] , mx[N*4 + 5] , mn[N*4 + 5]; void rec(int u) { mx[u] = max(mx[u<<1|1] , mx[u<<1]) ; mn[u] = min(mn[u<<1|1] , mn[u<<1]); } void pd(int u) { if(cov[u] != -1) { cov[u<<1] = mn[u<<1] = mx[u<<1] = cov[u]; cov[u<<1|1] = mn[u<<1|1] = mx[u<<1|1] = cov[u]; cov[u] = -1; } return; } void build(int u,int l,int r) { cov[u] = -1; if(l == r) {mn[u] = mx[u] = num[l] ; return;} build(u<<1 , l , (l + r >> 1)) ; build(u<<1|1 , (l + r >> 1) + 1 , r); rec(u) ; return; } void modify(int u,int l,int r,int ql,int qr,int v) { if(ql <= l && qr >= r) { cov[u] = mn[u] = mx[u] = v; return; } pd(u); int md = (l + r>> 1); if(ql <= md) modify(u<<1 , l , md , ql , qr ,v); if(qr > md) modify(u<<1|1 , md +1 , r , ql , qr , v); rec(u); return; } int qumax(int u,int l,int r,int ql) { if(mn[u] == m - 1) return -1; if(l == r) return l; pd(u); int md = (l + r>> 1); if(ql > md) return qumax(u<<1|1 , md + 1 , r , ql); if(ql == l) { if(mn[u<<1] < m - 1) return qumax(u<<1 , l , md , ql); return qumax(u<<1|1 , md + 1 , r , md + 1); } int w = qumax(u<<1 , l , md , ql) ; if(w == -1) return qumax(u<<1|1 , md + 1 , r , md + 1); return w; } int qumin(int u,int l,int r,int ql) { if(mx[u] == 0) return -1; if(l == r) return l; pd(u); int md = (l + r>> 1) ; if(ql > md) return qumin(u<<1|1 , md + 1 , r , ql); if(ql == l) { if(mx[u<<1] > 0) return qumin(u<<1 , l , md , ql); return qumin(u<<1|1 , md + 1 , r , md + 1); } int w = qumin(u<<1 , l , md , ql); if(w == -1) return qumin(u<<1|1 , md + 1 , r , md + 1); return w; } int qmax(int u,int l,int r,int ql,int qr) { if(ql <= l && qr >= r) { return mx[u]; } pd(u); int md = (l + r>> 1) , ans = 0; if(ql <= md) ans = max(ans , qmax(u<<1 , l , md , ql , qr )); if(qr > md) ans = max(ans , qmax(u<<1|1 , md +1 , r , ql , qr)); return ans; } int qmin(int u,int l,int r,int ql,int qr) { if(ql <= l && qr >= r) { return mn[u]; } pd(u); int md = (l + r>> 1) , ans = 1e9; if(ql <= md) ans = min(ans , qmin(u<<1 , l , md , ql , qr )); if(qr > md) ans = min(ans , qmin(u<<1|1 , md +1 , r , ql , qr)); return ans; } int ask(int u,int l,int r) { if(l == r) return l; int md = (l + r >> 1); pd(u); if(mx[u<<1|1] == 0) return ask(u<<1 , l , md); return ask(u<<1|1 , md + 1 , r) ; } int get() { int highbit = ask(1 , 1 , n+35); if(highbit == 1 || qmax(1 , 1 , n+35 , 1 , highbit - 1) == 0) return highbit; return highbit + 1; } void add(int u) { int l = qumax(1 , 1 , n + 35 , u); if(l > u) modify(1 , 1 , n+35 , u , l - 1 , 0) ; modify(1 , 1 , n+35 , l , l , qmax(1 , 1 , n + 35 , l , l ) + 1); return; } void sub(int u) { int l = qumin(1 , 1 , n + 35 , u); if(l > u) modify(1 , 1 , n+35 , u , l - 1 , m - 1) ; modify(1 , 1 , n+35 , l , l , qmax(1 , 1 , n + 35 , l , l ) - 1); return; } void solve() { scanf("%d%d%d",&n,&m,&q); for(int i = 1;i <= n + 35;i++) num[i] = 0; for(int i = 1;i <= n;i++) { scanf("%d",&a[i]);num[a[i]]++; } for(int i = 1;i <= n + 35;i++) { num[i + 1] += num[i] / m;num[i] %= m; } build(1 , 1 , n + 35); while(q--) { int u , v;scanf("%d%d",&u,&v); sub(a[u]) ; a[u] = v; add(a[u]) ; printf("%d%c",get(), " \n"[q == 0]); } return; } int main() { int t;scanf("%d",&t); while(t--) solve(); }
1810
G
The Maximum Prefix
You're going to generate an array $a$ with a length of at most $n$, where each $a_{i}$ equals either $1$ or $-1$. You generate this array in the following way. - First, you choose some integer $k$ ($1\le k \le n$), which decides the length of $a$. - Then, for each $i$ ($1\le i \le k$), you set $a_{i} = 1$ with probability $p_{i}$, otherwise set $a_{i} = -1$ (with probability $1 - p_{i}$). After the array is generated, you calculate $s_{i} = a_{1} + a_{2} + a_{3}+ \ldots + a_{i}$. Specially, $s_{0} = 0$. Then you let $S$ equal to $\displaystyle \max_{i=0}^{k}{s_{i}}$. That is, $S$ is the maximum prefix sum of the array $a$. You are given $n+1$ integers $h_{0} , h_{1}, \ldots ,h_{n}$. The score of an array $a$ with maximum prefix sum $S$ is $h_{S}$. Now, for each $k$, you want to know the expected score for an array of length $k$ modulo $10^9+7$.
How to calculate the maximal prefix sum? One possible way is let $f_{n+1} = 0$ and $f_{i}=max(f_{i+1},0)+a_{i}$. Consider this method to find maximal prefix sum: let $f_{n+1} = 0$ and $f_{i}=max(f_{i+1},0)+a_{i}$. We can discover that the only influence $[a_{i+1},a_{i+2} \dots a_{n}]$ has(to the whole array's maximal prefix sum) is its maximal prefix sum. Then we let $dp_{i,j}$ be : the expect score we can get, if we assume that the maximal prefix sum of $[a_{i+1},a_{i+2} \dots a_{n}]$ is $j$ (Read the definition carefully). The answer for each $k$ is $dp_{k,0}$, since if the maximal prefix sum for $[a_{k+1},a_{k+2} \dots a_{n}]$ is $0$, that is equivalent to removing them from the array. And also $dp_{0,j} = h_{j}$. And we have $dp_{i,j} = p_{i}\cdot dp_{i-1,j+1} + (1 - p_{i})\cdot dp_{i-1,max(j-1,0)}$. The first section represents chosing $a_{i} = 1$ and the second one represents chosing $a_{i} = -1$. We also have other solutions, using inclusion-exclusion or generate function. Actually all the testers' solutions differs from each other.
[ "dp" ]
3,200
#include<bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int N = 5005; int p[N] , q[N]; int n; int f[N][N]; int h[N]; int fpow(int a,int b) { int ans = 1; while(b){ if(b & 1) ans = 1LL*ans*a%mod; a = 1LL*a*a%mod;b >>= 1; } return ans; } void solve() { scanf("%d",&n); for(int i = 1;i <= n;i++) { int a,b;scanf("%d%d",&a,&b); p[i] = 1LL*a*fpow(b , mod - 2) % mod; q[i] = (1 - p[i] + mod) % mod; } for(int i = 0;i <= n;i++) scanf("%d",&h[i]); for(int i = 0;i <= n;i++) f[0][i] = h[i]; for(int i = 1;i <= n;i++) { for(int j = 0;j <= n;j++) { f[i][j] = (1LL*p[i]*f[i - 1][j + 1] + 1LL*q[i]*f[i - 1][max(0 , j - 1)] ) % mod; } printf("%d ",f[i][0]); } printf("\n"); return; } int main() { int t;scanf("%d",&t); while(t--) solve(); return 0; }
1810
H
Last Number
You are given a multiset $S$. Initially, $S = \{1,2,3, \ldots, n\}$. You will perform the following operation $n-1$ times. - Choose the largest number $S_{\text{max}}$ in $S$ and the smallest number $S_{\text{min}}$ in $S$. Remove the two numbers from $S$, and add $S_{\text{max}} - S_{\text{min}}$ into $S$. It's easy to show that there will be exactly one number left after $n-1$ operations. Output that number.
Actually I don't know how to hint. Try to find some rules related to $\frac{\sqrt{5}+1}{2}$, fibnacci or similar Assume that the moment before the $x$-th operation(but after $x-1$-th), the first time we have $S_{max} \le 2S_{min}$. Let's divide the operation into two part: before $x$ and equal or after $x$. Still, at the moment just before the $x$-th operation, let us sort the elements in the multiset in non-decreasing order, $S_{0},S_{1} \dots S_{k}$. We will show that the answer is $S_{0}\cdot (-1)^{k} + \sum_{i=1}^{k}{S_{i}\cdot (-1)^{i+1}}$. This lemma is based on the fact that, after each operation(which is after $x$-th), $S_{1}$ to $S_{k-1}$ will not change, $S_{k}$ is removed, and $S_{0}$ turn to $S_{k}-S_{0}$. Which also means $S_{k} - S_{0} \le S_{1}$ always holds. At the very beginning, $S_{k} - S_{0} \le S_{0} \le S_{1}$ obviously holds. And we can observe that either $S_{k} = S_{k-1}$ or $S_{k-1} = S_{k} - 1$. When $S_{k-1} = S_{k}$, the new $S_{0}$ after two operations is equal to the old $S_{0}$. When $S_{k-1} = S_{k} - 1$, the new $S_{0}$ after two operations is equal to the old $S_{0}$ minus one. So if we write the $S_{0}$ as an array $t_{0} , t_{1} \ldots t_{k}$ by time order, $t_{i+2} \le t_{i}$ always holds. Thus, $t_{i} \le S_{1}$ always holds. Let $d_{i}$ be the $S_{max}$ value in the $i$-th operation. Let's prove that before the $x$-th operation, $d_{i} = n-\lceil \frac{i}{\phi} \rceil + 1$, where $\phi = \frac{\sqrt{5} + 1}{2}$. We prove this by Mathematical induction. One fact should be known that during these operations, $S_{min} = i$ always holds for the $i$-th operation(since $S_{max} - S_{min} > S_{min}$). For $i=1$, it is true because $d_{1} = n$ and $n - \lceil \frac{1}{\phi} \rceil + 1 = n$. Assume for $i\le k$, it is true. Still use the fact that $d_{k+1} = d_{k}$ or $d_{k+1} = d_{k} + 1$. The necessary and sufficient condition for $d_{k+1} > d_{k}$ is all the numbers greater or equal to $d_{k}$ is ''used''. How many numbers are there? We have $n - d_{k} + 1$ numbers from the original multiset, and some numbers that occurs during the operations, which are the number of $j$ satisfying $d_{j} - j \ge d_{k}$. Thus, $d_{k+1} > d_{k}$ is equivalent to: $\space \space \space \space \sum_{j=1}^{k}{[d_{j} - j \ge d_{k}]} + n - d_{k} + 1 = k$ $\Leftrightarrow \sum_{j=1}^{k}{[d_{j} - j \ge d_{k}]} = k - \lceil \frac{k}{\phi} \rceil$ $\Leftrightarrow \sum_{j=1}^{k}{[d_{j} - j \ge d_{k}]} = \lfloor \frac{k(\phi - 1)}{\phi} \rfloor$ $\Leftrightarrow \sum_{j=1}^{k}{[\lceil \frac{j}{\phi} + j \rceil \le \lceil \frac{k}{\phi} \rceil]} = \lfloor \frac{k(\phi - 1)}{\phi} \rfloor$ $\Leftrightarrow \sum_{j=1}^{k}{[\lceil \frac{j(\phi + 1)}{\phi} \rceil \le \lceil \frac{k}{\phi} \rceil]} = \lfloor \frac{k(\phi - 1)}{\phi} \rfloor$ Note that $\frac{j(\phi + 1)}{\phi}$ is always increasing, which means that formula $\lceil \frac{j(\phi + 1)}{\phi} \rceil \le \lceil \frac{k}{\phi} \rceil$ holds for $j = \lfloor \frac{k(\phi - 1)}{\phi} \rfloor$, but does not hold for $j = \lfloor \frac{k(\phi - 1)}{\phi} \rfloor + 1$. The first equation, $\lceil \lfloor \frac{k(\phi - 1)}{\phi} \rfloor \cdot \frac{\phi + 1}{\phi} \rceil \le \lceil \frac{k}{\phi} \rceil$ always holds. Because $\frac{\phi - 1}{\phi}\cdot \frac{\phi + 1}{\phi} = \frac{1}{\phi}$, and ofcourse $\lfloor ka \rfloor b \le kab$. Let's do the research when the second equation does not hold. Let $m_{1} = \lbrace \frac{i(\phi - 1)}{\phi} \rbrace$, and $m_{2} = \lbrace \frac{i}{\phi} \rbrace$ ($\lbrace x \rbrace = x - \lfloor x \rfloor$). Note that $m_{1} + m_{2} = 1$, since $\lbrace \frac{i(\phi - 1)}{\phi} \rbrace = \lbrace i - \frac{i}{\phi} \rbrace$. The topic we are going to research is when $\lceil (\lfloor \frac{k(\phi - 1)}{\phi} \rfloor + 1) \cdot \frac{\phi + 1}{\phi}\rceil > \lceil \frac{k}{\phi} \rceil$ hold(which also means, $d_{k+1} > d_{k}$). $\Leftrightarrow \lceil (\frac{i(\phi - 1)}{\phi} - m_{1}) \cdot \frac{\phi+1}{\phi} + \frac{\phi + 1}{\phi} \rceil > \lceil \frac{i}{\phi} \rceil$ $\Leftrightarrow \lceil \frac{i}{\phi} - m_{1} \cdot \frac{\phi+1}{\phi} + \frac{\phi + 1}{\phi} \rceil > \lceil \frac{i}{\phi} \rceil$ $\Leftrightarrow \lceil \frac{i}{\phi} - (1 - m_{1}) \cdot \frac{\phi+1}{\phi} \rceil > \lceil \frac{i}{\phi} \rceil$ $\Leftrightarrow (1 - m_{1}) \cdot \frac{\phi+1}{\phi} > 1 - m_{2}$ $\Leftrightarrow \frac{\phi+1}{\phi} > \frac{1}{m_{2}} - 1$ $\Leftrightarrow m_{2} > \frac{\phi}{2\phi + 1}$ Then let's focus on, if $d_{k+1} = n - \lceil \frac{k+1}{\phi} \rceil + 1$, when will $d_{k + 1} > d_{k}$ hold? It's easy to find when $m_{2} > 1 - \frac{1}{\phi}$, $d_{k+1} > d_{k}$ holds. And since $\phi = \frac{\sqrt{5} + 1}{2}$, we can tell $\frac{\phi}{2\phi + 1} = 1 - \frac{1}{\phi}$. Thus, we proved the topic, for all $k < x$(before the $x$-th operation), $d_{k} = n - \lceil \frac{k}{\phi} \rceil + 1$. Then, by solve $n - \lceil \frac{x}{\phi} \rceil + 1 \le 2x$, we can get $x = \lceil (n+1)\frac{\phi - 1}{\phi} \rceil$. Now let's prove for $k \ge x$, $d_{k} = n - \lceil \frac{k}{\phi} \rceil + 1$ also holds ! Using the similar idea as lemma 2, find out when $d_{k + 1} > d_{k}$ holds. However, at this time, only $j \le x - 1$ will contribute(since for those $j > x - 1$, according to lemma 1, they become the minimal one and do not contribute to anything). Similarly, that is $\sum_{j=1}^{x - 1}{[d_{j} - j \ge d_{k}]} = \lfloor \frac{k(\phi - 1)}{\phi} \rfloor$. Seems to be different this time, but actually they are the same, because $\lfloor \frac{k(\phi - 1)}{\phi} \rfloor \le x - 1$ holds(the proving is easy, leave it as a exercise). This condition holds means that we can use the same method in lemma 2 to prove it. Till now, the lemmas told us the solving the problem is actually solving something like $\sum{(-1)^{i} \cdot (n- \lceil \frac{i}{\phi} \rceil + 1)}$. We can divide them into positive part and negtive part, and then solving $\sum{\lfloor C\cdot i \rfloor}$, where $i$ range from some $l$ to $r$, and $C$ is a irrational constant. Since $n$ is not very large, we can approximate $C$ by $\frac{a}{b}$, where $a,b$ are integers, and turn it into a traditional task. (Maybe it is called floor sum or something like, I'm not sure about the algorithm's english name). The marvelous jiangly told me $a,b$ in long long range is enough. But the tester used int128. We can dig more about the $\phi$. Let $b_{i} = S_{i+1} - S_{i}$ (sorted, before the $x$-th operation), and what we care is $b_{1} + b_{3} + b_{5}\dots$. We can find that array $b$ is actually a consecutive substring of fibonacci string. More over, let $F_{n}$ be the starting point of array $b$ in the fibonacci string when the initial size is $n$, we have the conclusion for $n \ge 5$: $F[5 \dots inf] = [3,0],[4,1],[8,0],[12,1] \dots [f_{i+3} + (-1)^{i+1} , 1 + (-1)^{i}]$, where $f_{i} = f_{i-1} + f_{i-2} , f_{1} = f_{2} = 1$ . $[r,l]$ represents a list of numbers $[r,r-1,r-2 \dots l+1,l]$. Now the only left problem is to find the prefix sum of fibonacci string(of even positions, or of odd positions). This is quite a simple task by using any $log(n)$ or $log^2(n)$ solution.
[ "combinatorics", "math" ]
2,900
#include<bits/stdc++.h> using namespace std; int l[500]; int fib[500]; int evenfib[500]; int getsum(int i,int n) ///1-index { if(n == 0) return 0; if(i <= 1) return fib[i]; if(n <= l[i - 2]) return getsum(i - 2, n); return fib[i - 2] + getsum(i - 1 , n - l[i - 2]); } int getsum2(int i,int n,int p) ///n = 2*k+p, 0-index { if(i <= 0) return 0; if(i <= 1) return 1^p; if(n <= l[i - 2] - 1) return getsum2(i - 2 , n , p); int L; if(p) L = (l[i - 2] - !(l[i-2]&1)); else L = (l[i- 2] - (l[i - 2] & 1)); int ans ; if(p) ans = fib[i - 2] - evenfib[i - 2]; else ans = evenfib[i - 2]; ans += getsum2(i - 1 , n - l[i - 2] , p ^ ((l[i - 2] & 1))); return ans; } int getfib(int n) ///0-index { if(n <= 0) return 0; n++; int ans = 0; int i; for(i = 0;l[i] <= n;i++) { ans += fib[i] ; n -= l[i]; } return ans + getsum(i , n); } int get_even(int n) ///n = 2*k { n++; int ans = 0; int i , lbefore = 0; for(i = 0;l[i] <= n;i++) { if(lbefore) ans += fib[i] - evenfib[i]; else ans += evenfib[i]; lbefore ^= (l[i]&1); n -= l[i]; } if(n) ans += getsum2(i , n - 1, lbefore); return ans; } const double phi = (3 - sqrt(5)) / 2; const double eps = 1e-6; int getstart(int n) { if(n == 3) return 0; if(n == 4) return 1; n -= 4; int i; for(i = 1;1;i++) { int lft ; if(i & 1) lft = fib[i + 3] + 1; else lft = fib[i + 3] - 1; if(n <= lft) break; n -= lft; } int start ; if(i & 1) start = fib[i + 3] - n + 1; else start = fib[i + 3] - n; return start; } typedef long long ll; const int L = 95; int a[120] = {8,0,6,0,1,8,5,9,7,2,9,7,2,9,2,0,5,5,7,9,0,1,8,1,7,3,5,9,3,7,4,9,2,7,7,3,1,5,5,4,6,8,7,3,1,7,3,2,4,9,1,0,2,8,0,9,6,9,7,2,2,8,8,1,6,3,4,3,6,5,6,1,3,1,4,5,9,7,1,5,1,5,0,1,0,5,2,1,1,0,6,6,9,1,8,3}; ll b[120]; double cal(int n) { memset(b,0,sizeof(b)); for(int i = 0;i <= L;i++) b[i] = 1LL*n*a[i]; for(int i = 0;i <= L + 15;i++) { b[i + 1] += (b[i] / 10) ; b[i] %= 10; } int ans = 0; for(int i = L + 11;i >= L + 1;i--) ans = (ans * 10 + b[i]) ; return ans; } void solve(int n) { if(n <= 2) {puts("1");return;} int v = cal(n); int len = n - v;v++; int start = getstart(n); int ans = 0; if(len & 1) { ans = v; ///[start + 1 , start + 3...start + len - 2] if(start & 1) ans -= (get_even(start + len - 2) - get_even(start - 1)); else ans -= (getfib(start + len - 1) - get_even(start + len - 1) - getfib(start) + get_even(start)); } else { ans = getfib(start + len - 2) - getfib(start - 1); ///[start + 1 , start + len - 3] if(start & 1) ans -= (get_even(start + len - 3) - get_even(start - 1)); else ans -= (getfib(start + len - 2) - get_even(start + len - 2) - getfib(start) + get_even(start)); } printf("%d\n",ans);return; } int main() { l[0] = l[1] = 1; fib[0] = 0 , fib[1] = 1; evenfib[1] = 1; for(int i = 2;l[i-1] <= 1000000000;i++) { l[i] = l[i - 1] + l[i - 2]; fib[i] = fib[i - 1] + fib[i - 2]; if(l[i - 2] & 1) evenfib[i] = evenfib[i - 2] + fib[i - 1] - evenfib[i - 1]; else evenfib[i] = evenfib[i - 2] + evenfib[i - 1]; } int t;scanf("%d",&t); while(t--) { int n;scanf("%d",&n);solve(n); } return 0; }
1811
A
Insert Digit
You have a \textbf{positive} number of length $n$ and one additional digit. You can insert this digit anywhere in the number, including at the beginning or at the end. Your task is to make the result as large as possible. For example, you have the number $76543$, and the additional digit is $4$. Then the maximum number you can get is $765443$, and it can be obtained in two ways — by inserting a digit after the $3$th or after the $4$th digit of the number.
Note that numbers of the same length are compared lexicographically. That is, until some index the numbers will match, and then the digit in our number should be greater. Let's write out the numbers $s_1, s_2, \ldots s_i$ until $s_i \ge d$. As soon as this condition is false or the line ends, insert the digit $d$. We got the lexicographically maximum number, which means just the maximum number.
[ "greedy", "math", "strings" ]
800
#include <iostream> using namespace std; void solve() { int n, d; cin >> n >> d; string s; cin >> s; for (int i = 0; i < n; ++i) { if (s[i] - '0' >= d) { cout << s[i]; } else { cout << d; for (int j = i; j < n; ++j) { cout << s[j]; } cout << '\n'; return; } } cout << d << '\n'; } int main() { int t; cin >> t; for (int _ = 0; _ < t; ++_) { solve(); } return 0; }
1811
B
Conveyor Belts
Conveyor matrix $m_n$ is matrix of size $n \times n$, where $n$ is an \textbf{even} number. The matrix consists of concentric ribbons moving clockwise. In other words, the conveyor matrix for $n = 2$ is simply a matrix $2 \times 2$, whose cells form a cycle of length $4$ clockwise. For any natural $k \ge 2$, the matrix $m_{2k}$ is obtained by adding to the matrix $m_{2k - 2}$ an outer layer forming a clockwise cycle. \begin{center} {\small The conveyor matrix $8 \times 8$}. \end{center} You are standing in a cell with coordinates $x_1, y_1$ and you want to get into a cell with coordinates $x_2, y_2$. A cell has coordinates $x, y$ if it is located at the intersection of the $x$th row and the $y$th column. Standing on some cell, every second you will move to the cell next in the direction of movement of the tape on which you are. You can also move to a neighboring cell by spending one unit of energy. Movements happen instantly and you can make an unlimited number of them at any time. Your task is to find the minimum amount of energy that will have to be spent to get from the cell with coordinates $x_1, y_1$ to the cell with coordinates $x_2, y_2$. For example, $n=8$ initially you are in a cell with coordinates $1,3$ and you want to get into a cell with coordinates $6, 4$. You can immediately make $2$ movements, once you are in a cell with coordinates $3, 3$, and then after $8$ seconds you will be in the right cell.
Note that the conveyor matrix $n \times n$ consists of $n$ cycles, through each of which we can move without wasting energy. Now you need to find the distance between the cycles where the start and end cells are located. In one step from any cycle, you can go either to the cycle that is closer to the edge of the matrix, or to the cycle that is further from the edge of the matrix. It turns out that it is enough to find on which cycles there are cells on the edge and take their difference modulo.
[ "implementation", "math" ]
1,000
def layer(n, x, y): return min([x, y, n + 1 - x, n + 1 - y]) def solve(): n, x1, y1, x2, y2 = map(int, input().split()) print(abs(layer(n, x1, y1) - layer(n, x2, y2))) t = int(input()) for _ in range(t): solve()
1811
C
Restore the Array
Kristina had an array $a$ of length $n$ consisting of non-negative integers. She built a new array $b$ of length $n-1$, such that $b_i = \max(a_i, a_{i+1})$ ($1 \le i \le n-1$). For example, suppose Kristina had an array $a$ = [$3, 0, 4, 0, 5$] of length $5$. Then she did the following: - Calculated $b_1 = \max(a_1, a_2) = \max(3, 0) = 3$; - Calculated $b_2 = \max(a_2, a_3) = \max(0, 4) = 4$; - Calculated $b_3 = \max(a_3, a_4) = \max(4, 0) = 4$; - Calculated $b_4 = \max(a_4, a_5) = \max(0, 5) = 5$. As a result, she got an array $b$ = [$3, 4, 4, 5$] of length $4$.You only know the array $b$. Find any matching array $a$ that Kristina may have originally had.
To solve the problem, you can build an array $a$ as follows $a_1 = b_1$ $a_i = \min(b_{i-1}, b_i)$ at $2 \le i \le n-1$ $a_n = b_{n-1}$ Let's show that from the constructed array $a$ we can get an array $B$ equal to the original array $b$: $B_1 = \max(a_1, a_2) = \max(b_1, \min(b_1, b_2))$ If $b_1 \gt b_2$, then $\max(b_1, b_2) = b_1$ If $b_2 \ge b_1$, then $\max(b_1, b_1) = b_1$ So $B_1 = b_1$ If $b_1 \gt b_2$, then $\max(b_1, b_2) = b_1$ If $b_2 \ge b_1$, then $\max(b_1, b_1) = b_1$ So $B_1 = b_1$ $B_i = \max(a_i, a_{i+1}) = \max(\min(b_{i-1}, b_i), \min(b_i, b_{i+1}))$ at $2 \le i \le n-2$ If $b_{i+1} \ge b_i$ and $b_{i-1} \ge b_i$, then $\max(\min(b_{i-1}, b_i), \min(b_i, b_{i+1}) = \min(b_i, b_i) = b_i$ If $b_{i+1} \ge b_i \ge b_{i-1}$, then $\max(b_{i-1}, b_i) = b_i$ If $b_{i-1} \ge b_i \ge b_{i+1}$, then $\max(b_i, b_{i+1}) = b_i$ By the construction of the array $b$ it is not possible that $b_i \gt b_{i+1}$ and $b_i \gt b_{i-1}$. So $B_i = b_i$ If $b_{i+1} \ge b_i$ and $b_{i-1} \ge b_i$, then $\max(\min(b_{i-1}, b_i), \min(b_i, b_{i+1}) = \min(b_i, b_i) = b_i$ If $b_{i+1} \ge b_i \ge b_{i-1}$, then $\max(b_{i-1}, b_i) = b_i$ If $b_{i-1} \ge b_i \ge b_{i+1}$, then $\max(b_i, b_{i+1}) = b_i$ By the construction of the array $b$ it is not possible that $b_i \gt b_{i+1}$ and $b_i \gt b_{i-1}$. So $B_i = b_i$ $B_{n-1} = \max(a_{n-1}, a_n) = \max(\min(b_{n-2}, b_{n-1}), b_{n-1})$ If $b_{n-2} \gt b_{n-2}$, then $\max(b_{n-1}, b_{n-1}) = b_{n-1}$ If $b_{n-1} \ge b_{n-2}$, then $\max(b_{n-2}, b_{n-1}) = b_{n-1}$ So $B_{n-1} = b_{n-1}$ If $b_{n-2} \gt b_{n-2}$, then $\max(b_{n-1}, b_{n-1}) = b_{n-1}$ If $b_{n-1} \ge b_{n-2}$, then $\max(b_{n-2}, b_{n-1}) = b_{n-1}$ We get that $B_i = b_i$ for $1 \le i \le n-1$, so $B = b$ and array $a$ is built correctly.
[ "constructive algorithms", "greedy" ]
1,100
#include "bits/stdc++.h" using namespace std; void solve(){ int n; cin >> n; vector<int>b(n-1), a; for(int i = 0; i < n - 1; i++) cin >> b[i]; a.emplace_back(b[0]); for(int i = 0; i < n - 2; i++){ a.emplace_back(min(b[i], b[i + 1])); } a.emplace_back(b[n - 2]); for(auto &i : a) cout << i << ' '; cout << "\n"; } int main(){ int t; cin >> t; while(t--){ solve(); } return 0; }
1811
D
Umka and a Long Flight
The girl Umka loves to travel and participate in math olympiads. One day she was flying by plane to the next olympiad and out of boredom explored a huge checkered sheet of paper. Denote the $n$-th Fibonacci number as $F_n = \begin{cases} 1, & n = 0; \\ 1, & n = 1; \\ F_{n-2} + F_{n-1}, & n \ge 2. \end{cases}$ A checkered rectangle with a height of $F_n$ and a width of $F_{n+1}$ is called a Fibonacci rectangle of order $n$. Umka has a Fibonacci rectangle of order $n$. Someone colored a cell in it at the intersection of the row $x$ and the column $y$. It is necessary to cut this rectangle \textbf{exactly} into $n+1$ squares in such way that - the painted cell was in a square with a side of $1$; - there was \textbf{at most one} pair of squares with equal sides; - the side of each square was equal to a Fibonacci number. Will Umka be able to cut this rectangle in that way?
$F_0^2 + F_1^2 +\ldots + F_n^2 = F_n\cdot F_{n+1}$, which can be proved by induction: $F_n\cdot F_{n+1} = F_n\cdot (F_{n-1}+F_n) = F_{n-1} \cdot F_n + F_n^2$. If the partition exists, it has the form $[F_0, F_1, \ldots, F_n]$, since the area of the rectangle with another partition will be greater than $F_n \cdot F_{n+1}$. We will cut the rectangles in the order $F_n, F_{n-1}, \ldots, F_0$. Denote the coordinates of the colored cell at the step $n$ as $\langle x_n, y_n\rangle$. If $F_{n-1} <y_n\le F_n$ and $n> 1$, then there is no partition, since the square $F_n$ at any location overlaps the colored cell. Cut off the square $F_n$ from the right or left edge, depending on the location of the colored cell, that is, $\langle x_{n-1}, y_{n-1} \rangle = \langle y_n, x_n\rangle$ or $\langle x_{n-1}, y_{n-1} \rangle = \langle y_n - F_n, x_n \rangle$. Suppose that it was advantageous to cut it not from the edge, then it is necessary to cut the rectangles $z\times F_n$ and $(F_{n-1}-z)\times F_n$, where $1\le z <F_{n+1}-F_n =F_{n-1}$ using the set $[F_0, F_1 \ldots F_{n-1}]$. Then $F_{n-1}$ will not enter the partition, but $2\cdot F_{n-2}^2 < (2F_{n-2}+F_{n-3})^2 + 1 = ( F_{n-2} + F_{n-1})^2 +1$, so $F_1^2 + F_2^2 + \ldots +2 \cdot F_{n-2}^2 < F_0^2 +F_1^2 +\ldots+F_{n-1}^2 = F_{n-1} \cdot F_n = z \cdot F_n + (F_{n-1} - z) \cdot F_n$. We came to a contradiction.
[ "constructive algorithms", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; const int MAXN = 50; int fib[MAXN]; void build() { fib[0] = fib[1] = 1; for (int i = 2; i < MAXN; ++i) fib[i] = fib[i - 2] + fib[i - 1]; } bool solve(int n, int x, int y) { if (n == 1) return true; if (fib[n - 1] <= y && y < fib[n]) return false; if (fib[n] <= y) y -= fib[n]; return solve(n - 1, y, x); } int main() { int t; cin >> t; build(); while (t--) { int n, x, y; cin >> n >> x >> y; cout << (solve(n, --x, --y) ? "YES" : "NO") << '\n'; } }
1811
E
Living Sequence
In Japan, the number $4$ reads like death, so Bob decided to build a live sequence. Living sequence $a$ contains all natural numbers that do not contain the digit $4$. $a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, \ldots]$. For example, the number $1235$ is part of the sequence $a$, but the numbers $4321$, $443$ are not part of the sequence $a$. Bob realized that he does not know how to quickly search for a particular number by the position $k$ in the sequence, so he asks for your help. For example, if Bob wants to find the number at position $k = 4$ (indexing from $1$), you need to answer $a_k = 5$.
Note that any number in the sequence can be made up of $9$ possible digits (all digits except $4$). Then let's find the first digit of the answer, notice that it is just $x$ or $x+1$, where $x \cdot 9^{l-1} \le k$ (where $l$ - the length of the number we're looking for) and $x$ - the maximum. Note that $x$ simply corresponds to a digit in the base-$9$ numeral system. Why is this so? Because without the first digit we can assemble any numbers with $9$ possible digits, and we can put the digits $0...x$ except $4$ in the first place. Thus, in the answer, the first digit will be $x$ if $x < 4$ and $x+1$ if $x \ge 4$. Note that once the first digit is determined, the rest can be found the same way, since the prefix does not affect anything.
[ "binary search", "dp", "math", "number theory" ]
1,500
#include <iostream> #include <cmath> #include <cctype> #include <vector> #include <algorithm> #include <set> #include <map> #include <deque> #include <stack> #include <unordered_set> #include <sstream> #include <cstring> #include <iomanip> #include <queue> #include <unordered_map> #include <random> #include <cfloat> #include <chrono> #include <bitset> #include <complex> #include <immintrin.h> int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); int32_t num_tests; std::cin >> num_tests; for(int32_t t = 0; t < num_tests; t++) { int64_t k; std::cin >> k; std::vector<int32_t> digits; while(k > 0) { digits.push_back(k % 9); k /= 9; } std::reverse(digits.begin(), digits.end()); for(int32_t i = 0; i < digits.size(); i++) std::cout << (char)(digits[i] < 4 ? (digits[i] + '0') : (digits[i] + '1')); std::cout << "\n"; } return 0; }
1811
F
Is It Flower?
Vlad found a flowerbed with graphs in his yard and decided to take one for himself. Later he found out that in addition to the usual graphs, $k$-flowers also grew on that flowerbed. A graph is called a $k$-flower if it consists of a simple cycle of length $k$, through each vertex of which passes its own simple cycle of length $k$ and these cycles do not intersect at the vertices. For example, $3$-flower looks like this: Note that $1$-flower and $2$-flower do not exist, since at least $3$ vertices are needed to form a cycle. Vlad really liked the structure of the $k$-flowers and now he wants to find out if he was lucky to take one of them from the flowerbed.
Note a few things: There are exactly $k^2$ vertices in the $k$-flower, since from each of the $k$ vertices of the main cycle comes another cycle of size $k$; in the $k$-flower, all vertices have degree $2$, except for the vertices of the main cycle, whose degrees are $4$; it follows that in $k$-flower $k^2 +k$ edges; The listed properties do not take into account only the connectivity of the graph and the sizes of our $k$ cycles. To check connectivity we run a bfs or dfs from any vertex and check that all vertices have been visited. To check the cycle lengths, we cut out the edges of the main one and make sure that the graph has fell apart into components of size $k$.
[ "dfs and similar", "graphs", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; int sz(int v, vector<vector<int>> &g, vector<bool> &used){ used[v] = true; int s = 1; for(int u: g[v]){ if(!used[u]) s += sz(u, g, used); } return s; } void remove(vector<int> &from, int x){ for(int &e: from){ if(e == x){ swap(e, from.back()); from.pop_back(); return; } } } void solve(int tc) { int n, m; cin >> n >> m; vector<vector<int>> sl(n); for(int i = 0; i < m; ++i){ int u, v; cin >> u >> v; sl[--u].emplace_back(--v); sl[v].emplace_back(u); } int k = sqrt(n); if(n != k * k || m != n + k){ cout << "NO"; return; } for(int i = 0; i < n; ++i){ if(sl[i].size() != 2 && sl[i].size() != 4){ cout << "NO"; return; } } vector<bool> used(n); if(sz(0, sl, used) != n){ cout << "NO"; return; } for(int i = 0; i < n; ++i){ if(sl[i].size() == 2) continue; for(int j = 0; j < sl[i].size();){ int u = sl[i][j]; if(sl[u].size() > 2){ remove(sl[i], u); remove(sl[u], i); } else{ j++; } } } used = vector<bool>(n); for(int i = 0; i < n; ++i){ if(!used[i] && sz(i, sl, used) != k){ cout << "NO"; return; } } cout << "YES"; } bool multi = true; signed main() { cout.tie(nullptr); int t = 1; if (multi)cin >> t; for (int i = 1; i <= t; ++i) { solve(i); cout << "\n"; } return 0; }
1811
G1
Vlad and the Nice Paths (easy version)
\textbf{This is an easy version of the problem, it differs from the hard one only by constraints on $n$ and $k$}. Vlad found a row of $n$ tiles and the integer $k$. The tiles are indexed from left to right and the $i$-th tile has the color $c_i$. After a little thought, he decided what to do with it. You can start from any tile and jump to any number of tiles \textbf{right}, forming the path $p$. Let's call the path $p$ of length $m$ nice if: - $p$ can be divided into blocks of length exactly $k$, that is, $m$ is divisible by $k$; - $c_{p_1} = c_{p_2} = \ldots = c_{p_k}$; - $c_{p_{k+1}} = c_{p_{k+2}} = \ldots = c_{p_{2k}}$; - $\ldots$ - $c_{p_{m-k+1}} = c_{p_{m-k+2}} = \ldots = c_{p_{m}}$; Your task is to find the number of nice paths of \textbf{maximum} length. Since this number may be too large, print it modulo $10^9 + 7$.
Let's use the dynamic programming. Let $dp[i][j]$ be the number of paths on the prefix $i$ of $j$ blocks of the same color. To make transitions in such dynamics, for the position $i$, we will iterate over the position $p$ in which the block started. Denote as $s$ the number of the same elements as $c_i$ and $c_p$ between them, then such a transition creates $dp[p-1][j-1] \cdot C_{k-2}^{s}$ combinations. This solution works in $O(n^3)$ complexity.
[ "combinatorics", "dp", "math" ]
2,100
M = 10 ** 9 + 7 def pw(a, n): if n == 0: return 1 b = pw(a, n // 2) return b * b % M * (a if n % 2 == 1 else 1) % M def obr(x): return pw(x, M - 2) def cnk(n, k): return fact[n] * obr(fact[k]) % M * obr(fact[n - k]) % M def solve(): n, k = map(int, input().split()) c = [-1] + [int(x) for x in input().split()] if k == 1: print(1) return dp = [[0] * (n // k + 1) for i in range(n + 1)] # dp[i][j] = number for i prefix with j blocks dp[0][0] = 1 for i in range(1, n + 1): for j in range(0, n // k + 1): if j > 0: sz = 1 for s in range(i - 1, - 1, -1): if c[s] == c[i]: sz += 1 if sz >= k: dp[i][j] += dp[s - 1][j - 1] * cnk(sz - 2, k - 2) % M dp[i][j] %= M dp[i][j] += dp[i - 1][j] dp[i][j] %= M for j in range(n // k, -1, -1): if dp[n][j] > 0: print(dp[n][j]) return t = int(input()) fact = [1] * 101 for i in range(1, 101): fact[i] = fact[i - 1] * i % M for _ in range(t): solve()
1811
G2
Vlad and the Nice Paths (hard version)
\textbf{This is hard version of the problem, it differs from the easy one only by constraints on $n$ and $k$}. Vlad found a row of $n$ tiles and the integer $k$. The tiles are indexed from left to right and the $i$-th tile has the color $c_i$. After a little thought, he decided what to do with it. You can start from any tile and jump to any number of tiles \textbf{right}, forming the path $p$. Let's call the path $p$ of length $m$ nice if: - $p$ can be divided into blocks of length exactly $k$, that is, $m$ is divisible by $k$; - $c_{p_1} = c_{p_2} = \ldots = c_{p_k}$; - $c_{p_{k+1}} = c_{p_{k+2}} = \ldots = c_{p_{2k}}$; - $\ldots$ - $c_{p_{m-k+1}} = c_{p_{m-k+2}} = \ldots = c_{p_{m}}$; Your task is to find the number of nice paths of \textbf{maximum} length. Since this number may be too large, print it modulo $10^9 + 7$.
To solve the hard version, let's modify the simple version solution. Note that the $j$ parameter can be discarded, since we only need paths of maximum length on each prefix. Now, as $dp[i]$, we denote a pair of the number of maximum paths and the number of blocks in them. For the position $i$, we will find the position closest to the left, from which we can start a block, and so we will find out what is the maximum for $i$. We will update $dp[i]$ until the maximum of the position being sorted is suitable for us.
[ "binary search", "combinatorics", "data structures", "dp", "math", "two pointers" ]
2,200
from sys import stdin input = lambda: stdin.readline().strip() M = 10 ** 9 + 7 cnk = [[0] * (5000 + 1) for i in range(5000 + 1)] def solve(): n, k = map(int, input().split()) c = [-1] + [int(x) for x in input().split()] if k == 1: print(1) return dp = [[0, 0] for i in range(n + 1)] # dp[i] = [number, max] for i prefix dp[0][0] = 1 for i in range(1, n + 1): sz = 1 for s in range(i - 1, - 1, -1): if c[s] == c[i]: sz += 1 if sz == k: dp[i][1] = dp[s - 1][1] + 1 if sz >= k: if dp[s - 1][1] < dp[i][1] - 1: break dp[i][0] += dp[s - 1][0] * cnk[sz - 2][k - 2] % M dp[i][0] %= M if dp[i][1] < dp[i - 1][1]: dp[i] = [0, dp[i - 1][1]] if dp[i][1] == dp[i - 1][1]: dp[i][0] += dp[i - 1][0] dp[i][0] %= M print(dp[n][0]) for i in range(5000 + 1): cnk[i][0] = 1 for i in range(1, 5000 + 1): for j in range(1, i + 1): cnk[i][j] = (cnk[i - 1][j] + cnk[i - 1][j - 1]) % M t = int(input()) for _ in range(t): solve()
1814
A
Coins
In Berland, there are two types of coins, having denominations of $2$ and $k$ burles. Your task is to determine whether it is possible to represent $n$ burles in coins, i. e. whether there exist non-negative integers $x$ and $y$ such that $2 \cdot x + k \cdot y = n$.
Note that $2$ coins with denomination $k$ can be replaced with $k$ coins with denomination $2$. So, if the answer exists, then there is also such a set of coins, where there is no more than one coin with denomination $k$. Therefore, it is enough to iterate through the number of coins with denomination $k$ (from $0$ to $1$) and check that the remaining number is non-negative and even (i. e. it can be represented as some number of coins with denomination $2$).
[ "implementation", "math" ]
800
for _ in range(int(input())): n, k = map(int, input().split()) for x in range(2): if n - x * k >= 0 and (n - x * k) % 2 == 0: print("YES") break else: print("NO")
1814
B
Long Legs
A robot is placed in a cell $(0, 0)$ of an infinite grid. This robot has adjustable length legs. Initially, its legs have length $1$. Let the robot currently be in the cell $(x, y)$ and have legs of length $m$. In one move, it can perform one of the following three actions: - jump into the cell $(x + m, y)$; - jump into the cell $(x, y + m)$; - increase the length of the legs by $1$, i. e. set it to $m + 1$. What's the smallest number of moves robot has to make to reach a cell $(a, b)$?
Let's fix the number of leg length increases we do. Let the final length be $k$. Notice that for all $i$ from $1$ to $k$ there is some time when the length is exactly $i$. Thus, we can perform jumps of form $(x, y) \rightarrow (x + i, y)$ or $(x, y) \rightarrow (x, y + i)$. What's the jumping strategy, then? Obviously, we can solve the problem independently for $a$ and $b$. Consider $a$. We would love to just make jumps of length $k$ as that's the maximum possible length. Unfortunately, that only works when $a$ is divisible by $k$. Otherwise, we are left with some remainder which is smaller than $k$. But we have already figured out how to jump to any value from $1$ to $k$. So, that only adds another jump. You can say that the total number of jumps is $\lceil \frac a k \rceil$. Same for $b$. Finally, for a fixed $k$, the answer is $\lceil \frac a k \rceil + \lceil \frac b k \rceil + (k - 1)$. The constraints tell us that we are not allowed to iterate over all $k$ from $1$ to $\max(a, b)$. It feels like huge $k$ will never be optimal, but let's try to base our intuition on something. Try to limit the options by studying the formula. Let's simplify. Assume $a = b$ and also get rid of the ceil. Not like that changes the formula a lot. Now it becomes $2 \frac a k + (k - 1)$. We can see that when we increase $k$, $2 \frac a k$ becomes smaller and $(k - 1)$ becomes larger. However, we care more about how fast they become smaller and larger. You can just guess or write down the derivative explicitly and figure out that the first term shrinks faster than the second term grows until around $\sqrt a \cdot c$ for some constant $c$ (apparently, $c = \sqrt 2$). Thus, their sum decreases until then, then increases. Thus, you can search for the best $k$ around $\sqrt a$ or $\sqrt b$ or $\sqrt{\max(a, b)}$. It doesn't really matter, since, for implementation, you can basically try all $k$ until around $10^5$, which is safely enough.
[ "brute force", "math" ]
1,700
for _ in range(int(input())): a, b = map(int, input().split()) ans = a + b for m in range(1, 100000): ans = min(ans, (a + m - 1) // m + (b + m - 1) // m + (m - 1)) print(ans)
1814
C
Search in Parallel
Suppose you have $n$ boxes. The $i$-th box contains infinitely many balls of color $i$. Sometimes you need to get a ball with some specific color; but you're too lazy to do it yourself. You have bought two robots to retrieve the balls for you. Now you have to program them. In order to program the robots, you have to construct two lists $[a_1, a_2, \dots, a_k]$ and $[b_1, b_2, \dots, b_{n-k}]$, where the list $a$ represents the boxes assigned to the first robot, and the list $b$ represents the boxes assigned to the second robot. \textbf{Every integer from $1$ to $n$ must be present in exactly one of these lists}. When you request a ball with color $x$, the robots work as follows. Each robot looks through the boxes that were assigned to that robot, in the order they appear in the list. The first robot spends $s_1$ seconds analyzing the contents of a box; the second robot spends $s_2$. As soon as one of the robots finds the box with balls of color $x$ (and analyzes its contents), the search ends. The search time is the number of seconds from the beginning of the search until one of the robots finishes analyzing the contents of the $x$-th box. If a robot analyzes the contents of all boxes assigned to it, it stops searching. For example, suppose $s_1 = 2$, $s_2 = 3$, $a = [4, 1, 5, 3, 7]$, $b = [2, 6]$. If you request a ball with color $3$, the following happens: - initially, the first robot starts analyzing the box $4$, and the second robot starts analyzing the box $2$; - at the end of the $2$-nd second, the first robot finishes analyzing the box $4$. It is not the box you need, so the robot continues with the box $1$; - at the end of the $3$-rd second, the second robot finishes analyzing the box $2$. It is not the box you need, so the robot continues with the box $6$; - at the end of the $4$-th second, the first robot finishes analyzing the box $1$. It is not the box you need, so the robot continues with the box $5$; - at the end of the $6$-th second, the first robot finishes analyzing the box $5$. It is not the box you need, so the robot continues with the box $3$. At the same time, the second robot finishes analyzing the box $6$. It is not the box you need, and the second robot has analyzed all the boxes in its list, so that robot stops searching; - at the end of the $8$-th second, the first robot finishes analyzing the box $3$. It is the box you need, so the search ends; - so, the search time is $8$ seconds. You know that you are going to request a ball of color $1$ $r_1$ times, a ball of color $2$ $r_2$ times, and so on. You want to construct the lists $a$ and $b$ for the robots in such a way that the total search time over all requests is the minimum possible.
If the ball of color $x$ is present in the first list on position $i$, then it takes $i \cdot t_1$ seconds to find it. The same for the second list: if color $x$ is on position $j$, it takes $j \cdot t_2$ seconds to find it. So, for each position, we have a coefficient which will be multiplied by the number of times it is requested, and the total search time is the sum of these products for all positions. There is a classical problem of the form "you are given two arrays $a_i$ and $b_i$, both of length $m$, consisting of non-negative integers; permute the elements of $a$ in such a way that $\sum\limits_{i=1}^{m} a_i \cdot b_i$ is the minimum possible". To solve this problem, you have to pair the maximum element of $a$ with the minimum element of $b$, the second maximum of $a$ with the second minimum element of $b$, and so on. We can reduce our problem to this one. For each of $2n$ positions in the lists, there is a coefficient; you have to assign the boxes from $1$ to $n$ to the positions so that the sum of $r_i$ multiplied by the coefficients for the positions is the minimum possible. This looks similar, but there are $2n$ positions and only $n$ boxes. To resolve this issue, we can try a lot of different approaches. I believe the easiest one is the following: initially, both lists are empty, and when want to add an element to one of these two lists, we choose the list such that the coefficient for the new position (which is $s_i \cdot (1 + cnt_i)$, where $cnt_i$ is the number of elements we already added to the $i$-th list) is smaller. If for both lists, adding a new element has the same coefficient - it doesn't matter which one we choose. This greedy approach works because every time we add an element to the list, next time we'll add another one into the same list, the coefficient for that element will be greater. So, the problem can be solved in $O(n \log n)$: first, we sort the boxes by the number of times they are requested (in non-ascending order), and then we put them into the two lists greedily, every time choosing the list such that the coefficient for the next element is smaller.
[ "constructive algorithms", "greedy", "sortings" ]
1,500
#include<bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { int n; scanf("%d", &n); vector<int> s(2); for(int j = 0; j < 2; j++) scanf("%d", &s[j]); vector<pair<int, int>> a(n); for(int j = 0; j < n; j++) { scanf("%d", &a[j].first); a[j].second = j + 1; } sort(a.begin(), a.end()); reverse(a.begin(), a.end()); vector<vector<int>> lists(2); for(int j = 0; j < n; j++) { int cost1 = s[0] * (lists[0].size() + 1); int cost2 = s[1] * (lists[1].size() + 1); if(cost1 < cost2) lists[0].push_back(a[j].second); else lists[1].push_back(a[j].second); } for(int j = 0; j < 2; j++) { cout << lists[j].size(); for(auto x : lists[j]) cout << " " << x; cout << endl; } } }
1814
D
Balancing Weapons
You've got a job in a game studio that developed an online shooter, and your first big task is to help to balance weapons. The game has $n$ weapons: the $i$-th gun has an integer fire rate $f_i$ and an integer damage per bullet $d_i$. The $i$-th gun's total firepower is equal to $p_i = f_i \cdot d_i$. You have to modify the values $d_i$ of some guns in such a way that the new values $d_i$ will still be integers, and the firepower of all guns will become balanced. Given an integer $k$, the guns are said to be balanced if $\max\limits_{1 \le i \le n}{p_i} - \min\limits_{1 \le i \le n}{p_i} \le k$. Since gamers that play your game don't like big changes, you need to change the values $d_i$ for the minimum possible number of guns. What is the minimum number of guns for which you have to change these values to make the guns balanced? Note that the new values $d_i$ must be integers greater than $0$.
Note that the answer $n$ is always possible: for example, we can set $d_i = \frac{\prod{f_j}}{f_i}$, then $p_1 = \dots = p_n = \prod{f_j}$ and $\max{p_i} - \min{p_i} = 0$. If the answer is less than $n$ then there is at least one gun $id$ we won't change. It means that all other guns' firepower should be "around" $p_{id}$, i. e. $|p_i - p_{id}| \le k$. So we can look at segment $[p_{id} - k, p_{id} + k]$ and, for each gun $i$, find what values $d'_i$ we should set to get into this segment. After that we can rephrase our task into the next one: we should choose segment $[l, l + k] \subset [p_{id} - k, p_{id} + k]$ such that each gun occurs in $[l, l + k]$ at least once and the number of corresponding $d'_i$ that are equal to $d_i$ is maximum possible. It can be solved with two pointers technique. Note that there are at most three interesting values $d'_i$ we should consider: $v_1 = \left\lfloor \frac{p_{id}}{f_i} \right\rfloor$, $v_2 = v_1 + 1$ and $v_3 = d_i$. For each unique value $v_j$ such that $v_j \cdot f_i \in [p_{id} - k, p_{id} + k]$ we can add an event $(i, c_j)$ in position $v_j f_i$, where $c_j$ is $1$ if $v_j = d_i$ or $0$ otherwise. Now, with two pointers technique, we can iterate over all subsegments of length $k + 1$ of segment $[p_{id} - k, p_{id} + k]$. To get the desired answer we should maintain the number of unique $i$ from events that are present in the subsegment and the sum $s$ of $c_j$ from that events. Since there is only one $c_j = 1$ for each gun $i$ then the sum $s$ of $c_j$ we have is equal exactly to the number of guns we shouldn't change. Then we take the maximum $mx$ over sums $s$ of all subsegments where all guns occur, and the answer for a fixed $p_{id}$ is $n - mx$. Let's iterate over all "fixed" $id$ and take the minimum from all $n - mx$: that will be the answer for the initial task. Checking answer for a fixed $id$ involves creating $3 n$ events and two pointers over segment $[p_{id} - k, p_{id} + k]$, so it takes $O(n + k)$ time and $O(n + k)$ space. So, the total complexity is $O(n^2 + n k)$ time and $O(n + k)$ space.
[ "binary search", "brute force", "data structures", "math", "two pointers" ]
2,500
fun main() { repeat(readln().toInt()) { val (n, k) = readln().split(' ').map { it.toInt() } val f = readln().split(' ').map { it.toLong() } val d = readln().split(' ').map { it.toLong() } fun checkAround(pos : Long) : Int { val qs = Array(2 * k + 1) { MutableList(0) { 0 } } fun inside(x : Long, pos: Long) = (pos - k <= x) && (x <= pos + k) for (i in f.indices) { var newD = maxOf(1L, pos / f[i]) if (newD != d[i] && newD + 1 != d[i] && inside(d[i] * f[i], pos)) { val id = (i + 1) qs[(d[i] * f[i] - pos + k).toInt()].add(id) } repeat(2) { if (inside(newD * f[i], pos)) { val id = if (newD == d[i]) (i + 1) else -(i + 1) qs[(newD * f[i] - pos + k).toInt()].add(id) } newD++ } } val cntPerId = IntArray(n) { 0 } var cntDistinct = 0 var cntGood = 0 fun addToSeg(cid : Int) { val id = -1 + if (cid > 0) cid else -cid val c = if (cid > 0) 1 else 0 if (cntPerId[id] == 0) cntDistinct++ cntPerId[id]++ cntGood += c } fun eraseFromSeg(cid : Int) { val id = -1 + if (cid > 0) cid else -cid val c = if (cid > 0) 1 else 0 cntPerId[id]-- if (cntPerId[id] == 0) cntDistinct-- cntGood -= c } var ans = 0 for (p in 0 until k) qs[p].forEach { addToSeg(it) } for (p in 0..k) { qs[p + k].forEach { addToSeg(it) } if (cntDistinct == n) ans = maxOf(ans, cntGood) qs[p].forEach { eraseFromSeg(it) } } return n - ans } var ans = n for (i in f.indices) { ans = minOf(ans, checkAround(d[i] * f[i])) } println(ans) } }
1814
E
Chain Chips
You are given an undirected graph consisting of $n$ vertices and $n-1$ edges. The $i$-th edge has weight $a_i$; it connects the vertices $i$ and $i+1$. Initially, each vertex contains a chip. Each chip has an integer written on it; the integer written on the chip in the $i$-th vertex is $i$. In one operation, you can choose a chip (if there are multiple chips in a single vertex, you may choose any one of them) and move it along one of the edges of the graph. The cost of this operation is equal to the weight of the edge. The cost of the graph is the minimum cost of a sequence of such operations that meets the following condition: - after all operations are performed, each vertex contains exactly one chip, and the integer on each chip is \textbf{not equal} to the index of the vertex where that chip is located. You are given $q$ queries of the form: - $k$ $x$ — change the weight of the $k$-th edge (the one which connects the vertices $k$ and $k+1$) to $x$. After each query, print the cost of the graph. Note that you don't actually move any chips; when you compute the cost, the chips are on their initial positions.
Let's try to analyze how many times we traverse each edge, in the style of "Contribution to the Sum" technique. For each edge, the number of times it is traversed must be even, since for every chip that goes from the part of the graph $[1..i]$ to the part $[i+1..n]$, there should be a chip that goes in the opposite direction (the number of chips on vertices $[1..n]$ should be unchanged). For each vertex, at least one incident edge should be traversed at least twice - otherwise, the chip from this vertex cannot be moved to any other vertex. We would also like to traverse the edges as rarely as possible. Is it possible to find an answer where, if we traverse any edge, we traverse it only twice? It turns out it is possible. Let's "split" the graph into several parts by removing the edges we don't traverse. If we don't break the constraint that each vertex has at least one incident edge which is traversed by some chip, then each part of the graph will contain at least two vertices. And in each part, we can make sure that each edge is traversed only twice as follows: let the part represent the segment $[l, r]$ of vertices; if we move the chip $r$ to the vertex $l$, the chip $l$ to the vertex $l+1$, the chip $l+1$ to the vertex $l+2$, ..., the chip $r-1$ to the vertex $r$, then every edge in that part will be traversed exactly twice. So, we have shown that if we pick a subset of edges which we traverse that meets the constraint on each vertex having an incident traversed edge, then it is enough to traverse each chosen edge only twice. Now the problem becomes the following: choose a subset of edges in such a way that every vertex has at least one incident chosen edge, minimize the total weight of this subset, and print the integer which is double that total weight. Since the structure of the graph is specific, we can run dynamic programming of the form $dp_{i,f}$ - the minimum total weight of the subset, if we considered the first $i$ edges, and $f$ is $0$ if we haven't taken the last edge, or $1$ if we have. Obviously, this dynamic programming works in $O(n)$, which is too slow because we have to process queries. We will employ a classical technique of storing the dynamic programming in segment tree: build a segment tree on $n-1$ leaves; in every vertex of the segment tree, we store a $2 \times 2$ matrix $d$; if the segment represented by the node of the segment tree is $[l..r]$, then the value of $d[f_1][f_2]$ is the minimum total weight of the subset of edges between $l$ and $r$ such that among every pair of adjacent edges, at least one is chosen; $f_1$ and $f_2$ represent the status of the first/last edge on the segment, respectively. And when some element changes, we need to recalculate only $O(\log n)$ nodes of the segment tree, so this solution works in $O(n \log n + q \log n)$, albeit with a very big constant factor. Implementation note: don't use dynamic-size arrays (like std::vector in C++) to store the values in the matrices, it might slow your solution very seriously. Instead, use static-size arrays.
[ "data structures", "dp", "matrices" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long li; const li INF = (li)(1e18); const int N = 200043; struct data { array<array<long long, 2>, 2> d; data() { for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) d[i][j] = INF; }; data(li x) { for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) d[i][j] = INF; d[0][0] = 0; d[1][1] = x; }; data(data l, data r) { for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) d[i][j] = INF; for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) for(int k = 0; k < 2; k++) for(int x = 0; x < 2; x++) { if(j == 0 && k == 0) continue; d[i][x] = min(d[i][x], l.d[i][j] + r.d[k][x]); } }; }; data T[4 * N]; li a[N]; void recalc(int v) { T[v] = data(T[v * 2 + 1], T[v * 2 + 2]); } void build(int v, int l, int r) { if(l == r - 1) T[v] = data(a[l]); else { int m = (l + r) / 2; build(v * 2 + 1, l, m); build(v * 2 + 2, m, r); recalc(v); } } void upd(int v, int l, int r, int pos, li val) { if(l == r - 1) { a[l] = val; T[v] = data(a[l]); } else { int m = (l + r) / 2; if(pos < m) upd(v * 2 + 1, l, m, pos, val); else upd(v * 2 + 2, m, r, pos, val); recalc(v); } } int main() { int n; scanf("%d", &n); for(int i = 0; i < n - 1; i++) { scanf("%lld", &a[i]); } build(0, 0, n - 1); int q; scanf("%d", &q); for(int i = 0; i < q; i++) { int x; li k; scanf("%d %lld", &x, &k); upd(0, 0, n - 1, x - 1, k); printf("%lld\n", T[0].d[1][1] * 2); } }
1814
F
Communication Towers
There are $n$ communication towers, numbered from $1$ to $n$, and $m$ bidirectional wires between them. Each tower has a certain set of frequencies that it accepts, the $i$-th of them accepts frequencies from $l_i$ to $r_i$. Let's say that a tower $b$ is accessible from a tower $a$, if there exists a frequency $x$ and a sequence of towers $a=v_1, v_2, \dots, v_k=b$, where consecutive towers in the sequence are directly connected by a wire, and each of them accepts frequency $x$. Note that accessibility is not transitive, i. e if $b$ is accessible from $a$ and $c$ is accessible from $b$, then $c$ may not be accessible from $a$. Your task is to determine the towers that are accessible from the $1$-st tower.
Let's consider the sweep line approach by the value of the variable $x$; the vertex $i$ is active from the moment $l_i$ to the moment $r_i$. And we have to find vertices that are reachable in the graph of active vertices from the vertex $1$. So, we rephrased the problem as follows: there are vertices that are active at some moments, and we want to get some information about connectivity during each moment of time. This is a standard offline dynamic connectivity problem which can be solved with a divide-and-conquer approach described here. Now we are able to find the connectivity component of the $1$-th vertex for each value of $x$. It remains to understand how to combine answers for all values of $x$ fast enough. Let's try to visualize the components as vertices of a directed graph. We assign a vertex to each component, and when two components merge, we add two directed edges from the new vertex to the vertices corresponding to the components; and now we can use the reachability information in this graph. Each vertex of the original graph corresponds to one of the sinks in this graph; and sinks that correspond to the vertices of some component are reachable from the vertex corresponding to that component. To restore all the vertex indices later, we will mark all components containing the vertex $1$ while we run our dynamic connectivity approach. Then the vertex $v$ (of the original graph) is included in the answer if the vertex representing the component containing only the vertex $v$ is reachable from any of the marked vertices. Now, all you need to do is run DFS or BFS from all the marked vertices in the component graph.
[ "brute force", "divide and conquer", "dsu" ]
2,700
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) const int N = 200002; const int V = 50 * N; using pt = pair<int, int>; int n, m; pt a[N]; vector<pt> t[4 * N]; int p[N], rk[N], vs[N]; int cntV; pt g[V]; bool ans[V]; void upd(int v, int l, int r, int L, int R, pt e) { if (L >= R) return; if (l == L && r == R) { t[v].push_back(e); return; } int m = (l + r) / 2; upd(v * 2 + 1, l, m, L, min(m, R), e); upd(v * 2 + 2, m, r, max(m, L), R, e); } int k; int* ptr[V]; int val[V]; void upd(int &a, int b) { ptr[k] = &a; val[k] = a; k += 1; a = b; } int getp(int v) { return p[v] == v ? v : getp(p[v]); } void unite(int v, int u) { v = getp(v), u = getp(u); if (v == u) return; if (rk[v] > rk[u]) swap(v, u); upd(p[v], u); g[cntV] = {vs[v], vs[u]}; upd(vs[u], cntV++); if (rk[v] == rk[u]) upd(rk[u], rk[u] + 1); } void solve(int v, int l, int r) { int cur = k; for (auto& [v, u] : t[v]) unite(v, u); if (l + 1 == r) { ans[vs[getp(0)]] = 1; } else { int m = (l + r) / 2; solve(v * 2 + 1, l, m); solve(v * 2 + 2, m, r); } while (k > cur) { k -= 1; (*ptr[k]) = val[k]; } } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for (int i = 0; i < n; ++i) cin >> a[i].first >> a[i].second; for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y; --x; --y; int L = max(a[x].first, a[y].first); int R = min(a[x].second, a[y].second); upd(0, 0, N, L, R + 1, {x, y}); } for (int i = 0; i < n; ++i) { p[i] = i; rk[i] = 1; vs[i] = i; g[i] = {-1, -1}; } cntV = n; solve(0, 0, N); queue<int> q; for (int i = 0; i < cntV; ++i) if (ans[i]) q.push(i); while (!q.empty()) { int v = q.front(); q.pop(); for (int u : {g[v].first, g[v].second}) { if (u != -1 && !ans[u]) { ans[u] = true; q.push(u); } } } for (int i = 0; i < n; ++i) if (ans[i]) cout << i + 1 << ' '; }
1815
A
Ian and Array Sorting
To thank Ian, Mary gifted an array $a$ of length $n$ to Ian. To make himself look smart, he wants to make the array in non-decreasing order by doing the following finitely many times: he chooses two adjacent elements $a_i$ and $a_{i+1}$ ($1\le i\le n-1$), and increases both of them by $1$ or decreases both of them by $1$. Note that, the elements of the array \textbf{can} become negative. As a smart person, you notice that, there are some arrays such that Ian cannot make it become non-decreasing order! Therefore, you decide to write a program to determine if it is possible to make the array in non-decreasing order.
Consider difference array $[a_2-a_1,a_3-a_2,...,a_n-a_{n-1}]$. If the original array is non-decreasing, what properties does the difference array have? Operations to the original array correspond to what operations in the difference array? We consider the difference array $b_i=a_{i+1}-a_i$ ($1\le i\le n-1$). Then the original array is non-decreasing if and only if all elements of the difference array is non-negative. We can see that either $b_i$ is increased by $1$ and $b_{i+2}$ is decreased by $1$ or vice versa for $1\le i\le n-3$, $b_2$ is increased or decreased by $1$ or $b_{n-2}$ is increased or decreased by $1$. If $n$ is odd, then $n-2$ is odd. What we can do is to increase $b_2$ and $b_{n-2}$ enough number of times, and then do $b_i$ increase by $1$ and $b_{i+2}$ decrease by $1$ or vice versa enough times to distribute the values to other elements of $b$. Doing this, we can make all of the elements of $b$ non-negative, which is what we want. So we output 'YES' no matter what for odd $n$. For even $n$, $n-2$ is even. So by increasing $b_2$ and $b_{n-2}$ enough number of times, then distributing, we can only ensure that the elements of $b$ with even indices are non-negative. Since the only operation that affects odd indices is increasing $b_i$ by $1$ and decreasing $b_{i+2}$ by $1$ or vice versa, we can see that the sum of the elements of $b$ with odd indices will not change. If the sum of the elements of $b$ with odd indices is at least $0$, we can distribute the values such that in the end, all of them are non-negative, so we should output 'YES'. But if the sum of elements of $b$ with odd indices is negative, there must exist a negative $b_i$ in the end, and we should output 'NO'.
[ "greedy", "math" ]
1,300
#include<bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; int arr[n]; long long int altsum=0; for(int i=0;i<n;i++){ cin >> arr[i]; if(i%2==0){ altsum-=arr[i]; } else{ altsum+=arr[i]; } } if(n%2==1||altsum>=0){ cout << "YES\n"; } else{ cout << "NO\n"; } return; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while(t--){ solve(); } }
1815
B
Sum Graph
This is an interactive problem. There is a hidden permutation $p_1, p_2, \dots, p_n$. Consider an undirected graph with $n$ nodes only with no edges. You can make two types of queries: - Specify an integer $x$ satisfying $2 \le x \le 2n$. For all integers $i$ ($1 \le i \le n$) such that $1 \le x-i \le n$, an edge between node $i$ and node $x-i$ will be added. - Query the number of \textbf{edges} in the shortest path between node $p_i$ and node $p_j$. As the answer to this question you will get the number of edges in the shortest path if such a path exists, or $-1$ if there is no such path. Note that you can make both types of queries in \textbf{any} order. Within $2n$ queries (including type $1$ and type $2$), guess two possible permutations, at least one of which is $p_1, p_2, \dots, p_n$. You get accepted if at least one of the permutations is correct. You are allowed to guess the same permutation twice. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
Consider using a type 1 operation on $x=n+1$ and $x=n+2$. What do you notice? The resulting graph, after performing type 1 operations according to hint 1, will be a chain (e.g. when $n=6$, it should look like $1 - 6 - 2 - 5 - 3 - 4$). Now, try to figure out a position $k$ such that node $p_k$ is one of the endpoints of the chain. Once you figure that out, how can you make use of this to solve the full problem? There are many ways to solve this problem. My original solution is rather difficult to implement correctly, and a bit complicated. During round testing, tester rsj found an alternative solution, which is, in my opinion, one that's a lot easier to understand and implement. Firstly, use a type 1 operation on $x=n+1$ and $x=n+2$ (or you can do $x=n$ and $x=n+1$). Then, the graph should look like a chain (e.g. when $n=6$, it should look like $1 - 6 - 2 - 5 - 3 - 4$). Note that there are actually two edges between each pair of directly connected nodes, but it is irrelevant to the task. Next, use a type 2 query on all pairs of $(1,i)$ where $2 \le i \le n$. Take the maximum of the query results. Let $k$ be one of the values such that the query result of $(1,k)$ is maximum among all $(1,i)$. It is easy to see that, node $p_k$ is one of the endpoints of the chain. Afterwards, use a type 2 query on all pairs of $(k,i)$ where $1 \le i \le n$ and $i \ne k$. Since node $p_k$ is an endpoint of the chain, all the query results are distinct and you can recover the exact node that each query result corresponds to. A problem arises that it is unclear about which endpoint node $p_k$ actually is. But this issue can be solved easily: since the problem allows outputting two permutations that can be $p$, just try both endpoints and output the corresponding permutations. In total, $2$ type 1 operations and $2n-2$ type 2 operations are used, which sums up to $2n$ operations. As stated in the sample description, you don't even need any operations when $n=2$. It is also easy to see that the actual number of operations required is $2n-1$ since there is a pair of duplicate type 2 operations, but we allow duplicating the operation anyway. Try to solve the problem using at most $n + \left \lfloor \frac{n}{2} \right \rfloor + 2$ queries. Refer to this comment. Thanks to -1e11 and FatihSolak for the solution. (To pass this problem using this solution, optimizations for $n=2$ are needed, as mentioned in the editorial section.) Another way of solving the harder version provided by sysia: refer to this comment.
[ "brute force", "constructive algorithms", "graphs", "implementation", "interactive", "shortest paths", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; void solve(int tc) { int n; cin >> n; cout << "+ " << n+1 << endl; cout << "+ " << n+2 << endl; int l = 1, r = n; int ord[n+1]; for(int i=1; i<=n; i++) { if(i & 1) ord[i] = l++; else ord[i] = r--; } int dist1[n+1]; dist1[1] = 0; int ma = 0, id; for(int i=2; i<=n; i++) { cout << "? 1 " << i << endl; cin >> dist1[i]; if(dist1[i] > ma) { ma = dist1[i]; id= i; } } int p[n+1], q[n+1]; p[id] = ord[1]; q[id] = ord[n]; for(int i=1; i<=n; i++) { if(i != id) { cout << "? " << id << " " << i << endl; int x; cin >> x; p[i] = ord[x+1]; q[i] = ord[n-x]; } } cout << "!"; for(int i=1; i<=n; i++) cout << " " << p[i]; for(int i=1; i<=n; i++) cout << " " << q[i]; cout << endl; } int32_t main() { int t = 1; cin >> t; for(int i=1; i<=t; i++) solve(i); }
1815
C
Between
You are given an integer $n$, as well as $m$ pairs of integers $(a_i,b_i)$, where $1\leq a_i , b_i \leq n$, $a_i \ne b_i$. You want to construct a sequence satisfying the following requirements: - All elements in the sequence are integers between $1$ and $n$. - There is exactly one element with value $1$ in the sequence. - For each $i$ ($1 \le i \le m$), between any two elements (on different positions) in the sequence with value $a_i$, there is at least one element with value $b_i$. - The sequence constructed has the \textbf{maximum} length among all possible sequences satisfying the above properties. Sometimes, it is possible that such a sequence can be arbitrarily long, in which case you should output "INFINITE". Otherwise, you should output "FINITE" and the sequence itself. If there are multiple possible constructions that yield the maximum length, output any.
Construct a graph with $n$ vertices and add a directed edge $a \rightarrow b$ if between every two $a$ there must be a $b$. Let $v_a$ be the number of occurrences of $a$. The key observation is that if $a \rightarrow b$, then $v_{a} \leq v_{b} + 1$. Suppose $a_k \rightarrow a_{k-1} \rightarrow \cdots a_1$ is a directed path, where $a_1 = 1$. Then since $v_1 = 1$, we must have $v_{a_i} \leq i$. In other words, $v_s \leq d_s$. where $d_s$ is one plus the length of the shortest directed path from $s$ to $1$. Therefore, the total array length does not exceed $\sum_{i=1}^{n} d_i$. We claim that we can achieve this. It is easy to calculate the $d_s$ by a BFS. Let $T_i$ consists of vertices $x$ such that $v_x = s$. Let $M$ the largest value of $d_i$ among all $i \in {1,2\cdots n}$. Consider $[T_M] , [T_{M-1}][T_M] , [T_{M-2}][T_{M-1}][T_{M}],\cdots [T_1][T_2][T_3]\cdots [T_m]$ where for each $i$, vertices in various occurrences of $T_i$ must be arranged in the same order. It is easy to check that this construction satisfies all the constraints and achieve the upper bound $\sum_{i=1}^{n} d_i$. Thus, this output is correct. The sequence can be arbitrarily long if and only if there is some $v$ that does not have a path directed to $1$. To see this, let $S$ be the set of vertices that do not have path directed to $1$, then the following construction gives an arbitrarily long output that satisfy all constraints: $1 [S][S][S]\cdots$
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
2,200
#include<bits/stdc++.h> using namespace std; void solve(){ int n,m; cin >> n >> m; vector <int> adj[n+1]; int occ[n+1]; occ[1]=1; for(int i=0;i<m;i++){ int x,y; cin >> x >> y; adj[y].push_back(x); } for(int i=2;i<=n;i++){ occ[i]=0; } queue <int> bfs; bfs.push(1); while(bfs.size()>0){ int f=bfs.front(); bfs.pop(); for(int i=0;i<adj[f].size();i++){ if(occ[adj[f][i]]==0){ occ[adj[f][i]]=occ[f]+1; bfs.push(adj[f][i]); } } } vector <int> v[n+1]; int ans=0; for(int i=1;i<=n;i++){ if(occ[i]==0){ cout << "INFINITE\n"; return; } v[occ[i]].push_back(i); ans+=occ[i]; } cout << "FINITE\n" << ans << endl; for(int i=n;i>=1;i--){ for(int j=n;j>=i;j--){ if(i%2!=j%2){ continue; } for(int k=0;k<v[j].size();k++){ cout << v[j][k] << ' '; } } } for(int i=2;i<=n;i++){ for(int j=n;j>=i;j--){ if(i%2!=j%2){ continue; } for(int k=0;k<v[j].size();k++){ cout << v[j][k] << ' '; } } } cout << endl; return; } int main(){ int t; cin >> t; while(t--){ solve(); } }
1815
D
XOR Counting
Given two positive integers $n$ and $m$. Find the sum of all possible values of $a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_m$, where $a_1,a_2,\ldots,a_m$ are non-negative integers such that $a_1+a_2+\ldots+a_m=n$. Note that all possible values $a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_m$ should be counted in the sum \textbf{exactly once}. As the answer may be too large, output your answer modulo $998244353$. Here, $\bigoplus$ denotes the bitwise XOR operation.
The cases when $m=1$ and $m\ge3$ are relatively much easier than when $m=2$. When $m=2$, perform an $O(\log n)$ DP on answer. Notice we have to DP another thing as well. What is it? If $m=1$, it is clear that we only can have $a_1=n$ so the answer is $n$. If $m\ge3$, $\left[x,\frac{n-x}2,\frac{n-x}2,0,0,...\right]$ gives a xor of $x$, so all $x$ with the same parity as $n$ and at most $n$ can be achieved. Notice xor and sum are identical in terms of parity, and $a\oplus b\le a+b$. So these restrict that only values of $x$ that has same parity with $n$ and is at most $n$ is possible as a result of the xor. Therefore, we can use $O(1)$ to calculate the sum of all non-negative integers at most $n$ and have same parity as $n$. It remains to handle the case when $m=2$. We create the functions $f(n)$ and $g(n)$, where $f(n)$ is the sum of all possible values of the xor and $g(n)$ counts the number of all possible values of the xor. We then consider the following: If $n$ is odd, then one of $a_1,a_2$ is even and the other is odd. WLOG assume $a_1$ is even and $a_2$ is odd. Then we let $a_1'=\frac{a_1}2$ and $a_2'=\frac{a_2-1}2$. We can see that $a_1'+a_2'=\frac{n-1}2$ and $a_1\oplus a_2=2(a_1'\oplus a_2')+1$. Hence we know that $g(n)=g\left(\frac{n-1}2\right)$, and $f(n)=2f\left(\frac{n-1}2\right)+g\left(\frac{n-1}2\right)$. If $n$ is even, there are two cases. If $a_1$ and $a_2$ are both even, we let $a_1'=\frac{a_1}2$ and $a_2'=\frac{a_2}2$. We can see that $a_1'+a_2'=\frac{n}2$ and $a_1\oplus a_2=2(a_1'\oplus a_2')$. If $a_1$ and $a_2$ are both odd, we let $a_1'=\frac{a_1-1}2$ and $a_2'=\frac{a_2-1}2$. We can see that $a_1'+a_2'=\frac{n}2-1$ and $a_1\oplus a_2=2(a_1'\oplus a_2')$. Hence we know that $f(n)=2f\left(\frac{n}2\right)+2f\left(\frac{n}2-1\right)$, and $g(n)=g\left(\frac{n}2\right)+g\left(\frac{n}2-1\right)$. So we can simply DP. It can be seen that the time complexity is $O(\log n)$ per test case, so we are done.
[ "bitmasks", "combinatorics", "dp", "math" ]
2,600
#include<bits/stdc++.h> using namespace std; unordered_map <long long int,long long int> npos,spos; const int MOD=998244353; long long int solve(long long int n){ if(npos[n]!=0){ return spos[n]; } if(n%2==1){ solve(n/2); npos[n]=npos[n/2]; spos[n]=spos[n/2]*2+npos[n/2]; spos[n]%=MOD; } else{ solve(n/2); solve(n/2-1); npos[n]=npos[n/2]+npos[n/2-1]; spos[n]=(spos[n/2]+spos[n/2-1])*2; spos[n]%=MOD; } return spos[n]; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); npos[0]=1; spos[0]=0; int t; cin >> t; while(t--){ long long int n,m; cin >> n >> m; if(m==2){ cout << solve(n) << endl; } else if(m==1){ cout << n%MOD << endl; } else if(n%2==0){ cout << (((n/2)%MOD)*((n/2+1)%MOD))%MOD << endl; } else{ cout << (((n/2+1)%MOD)*((n/2+1)%MOD))%MOD << endl; } } }
1815
E
Bosco and Particle
Bosco is studying the behaviour of particles. He decided to investigate on the peculiar behaviour of the so-called "four-one-two" particle. He does the following: There is a line of length $n+1$, where the topmost point is position $0$ and bottommost is position $n+1$. The particle is initially (at time $t=0$) at position $0$ and heading downwards. The particle moves at the speed of $1$ unit per second. There are $n$ oscillators at positions $1,2,\ldots,n$. Each oscillator can be described by a binary string. The initial state of each oscillator is the first character of its binary string. When the particle hits with an oscillator, the particle reverses its direction if its current state is $1$ and continues to move at the same direction if its current state is $0$, and that oscillator moves on to the next state (the next state of the last state is defined as the first state). Additionally, the particle always reverses its direction when it is at position $0$ or $n+1$ at time $t > 0$. Bosco would like to know the cycle length of the movement of particle. The cycle length is defined as the minimum value of $c$ such that for any time $t \ge 0$, the position of the particle at time $t$ is same as the position of the particle at time $t+c$. It can be proved that such value $c$ always exists. As he realises the answer might be too large, he asks you to output your answer modulo $998244353$.
If the oscillator string is periodic, what should we do? Use the case when $n=1$ to help you calculate the answer. Observe that whole process is periodic. Note that the process is reversible. If you are in some state $s$, consisting of position of the particle and the current state position of each oscillator, you can decide the next state and the previous state. This implies the state transition graph is a permutation, so it decomposes into cycles. Firstly, we can easily see that removing cycles for the oscillator strings does not affect the answer. To help us calculating the answer easier, we have to remove cycle. You can remove cycle using any fast enough string algorithm such as KMP. It is not difficult to see that if all strings are non-periodic, then being periodic with respect to the particle position $x$ is the same as being periodic with respect to both $x$ and all oscillator states. Let $a_i$ be the number of times the particle hits oscillator $i$ when moving downwards and $b_i$ be the number of times the particle hits oscillator i when moving upwards in each cycle. For each oscillator $i$, consider the case when $n=1$ and oscillator $i$ is the only oscillator. Let $a'_i$ be the number of times the particle hits oscillator $i$ when moving downwards and $b'_i$ be the number of times the particle hits the oscillator $i$ when moving upwards in each cycle. Then we must have $a_i=ka'_i$ and $b_i=kb'_i$ for some positive integer k. Also, we must have $a_i=b_{i-1}$ as the number of times the particle goes from oscillator $i-1$ to oscillator $i$ is same as the number of times the particle goes from oscillator $i$ to oscillator $i-1$. It can be shown that the smallest integers $a_i$ and $b_i$ satisfying the above constraints must be the period. We can calculate the the smallest such integers, by factoring each $k$ and maintain the primes. In other words, we can separately consider the $p$-adic valuation of the $a'_i$'s and $b'_i$'s to get the $p$-adic valuation of $a_i$'s and $b_i$'s for each prime. Below is a visualisation: Notice the answer is $2(a_1+a_2+...+a_n+b_n)$, which can be easily calculated. So we are done.
[ "dp", "math", "number theory", "strings" ]
3,100
#include<bits/stdc++.h> using namespace std; vector <int> prime; bool p[1000001]; const long long int mod=998244353; void init(){ p[1]=0; for(int i=2;i<=1000000;i++){ p[i]=1; } for(int i=2;i<=1000000;i++){ if(p[i]){ prime.push_back(i); } for(int j=i;j<=1000000;j+=i){ p[j]=0; } } return; } long long int bigmod(long long int n,long long int k){ long long int pown=n,ans=1; while(k>0){ if(k%2){ ans*=pown; ans%=mod; } pown*=pown; pown%=mod; k/=2; } return ans; } int vp(long long int n,int p){ int ans=0; if(n==0){ return 10000000; } while(n%p==0){ n/=p; ans++; } return ans; } string rpc(string str){ int i=0; int len=str.length(); int j=-1; int nextval[len]; nextval[i]=-1; while (i<len){ if (j==-1||str[i]==str[j]){ i++; j++; nextval[i]=j; } else j=nextval[j]; } if ((len)%(len-nextval[len])==0) return str.substr(0,len-nextval[len]); else return str; } int main(){ init(); int n; cin >> n; int lim=n; pair<int,int> arr[n]; for(int i=0;i<n;i++){ string s; cin >> s; s=rpc(s); int x=0,y=0,ptr=0; bool b=true; do{ if(b){ x++; } else{ y++; } if(s[ptr]=='0'){ b=1-b; } ptr++; ptr%=s.length(); }while(!b||(ptr!=0)); arr[i]={x,y}; if(y==0&&lim==n){ lim=i; } } long long int times[n+1]; for(int i=0;i<=n;i++){ times[i]=1; } for(int i=0;i<prime.size();i++){ int p=prime[i],curl=0,curr=0,difp[lim+1]={0}; for(int j=1;j<=lim;j++){ int l=vp(arr[j-1].first,p); int r=vp(arr[j-1].second,p); if(curr<l){ curl+=(l-curr); curr=r; } else{ curr+=(r-l); } difp[j]=r-l; } int cur=curl; for(int j=0;j<=lim;j++){ cur+=difp[j]; times[j]*=bigmod(p,cur); times[j]%=mod; } } long long int ans=0; for(int i=0;i<=lim;i++){ ans+=times[i]; ans%=mod; } cout << (2*ans)%mod << endl; }
1815
F
OH NO1 (-2-3-4)
You are given an undirected graph with $n$ vertices and $3m$ edges. The graph may contain multi-edges, but does not contain self-loops. The graph satisfies the following property: the given edges can be divided into $m$ groups of $3$, such that each group is a triangle. A triangle is defined as three edges $(a,b)$, $(b,c)$ and $(c,a)$ for some three distinct vertices $a,b,c$ ($1 \leq a,b,c \leq n$). Initially, each vertex $v$ has a non-negative integer weight $a_v$. For every edge $(u,v)$ in the graph, you \textbf{should} perform the following operation \textbf{exactly once}: - Choose an integer $x$ between $1$ and $4$. Then increase both $a_u$ and $a_v$ by $x$. After performing all operations, the following requirement should be satisfied: if $u$ and $v$ are connected by an edge, then $a_u \ne a_v$. It can be proven this is always possible under the constraints of the task. Output a way to do so, by outputting the choice of $x$ for each edge. It is easy to see that the order of operations does not matter. If there are multiple valid answers, output any.
Go through from vertex $1$ through $n$ and decided their final weights in this order. When deciding the weights for $v$ , make sure it is different from $w$ if $w < v$ and $v$ is adjacent to $w$. Ignore vertices $x$ where $x$ is adjacent to $v$ but have $x > v$. If there are at least $d+1$ options to take from, and $d$ of them are not available, then there is still some option to take. Let's try to decide the final weights of $1$ through $n$ in this order. For a triangle $a<b<c$, we call $a$ the first vertex, $b$ the second vertex, $c$ the third vertex. Consider each triangle individually, if we can achieve the following task then we are done: By only adjusting edges of this triangle: There is at least one option for the first vertex After fixing a particular option for the first vertex, there are at least two options for the the second vertex After fixing particular options for the first two vertices, there are at least three options for the third vertex To see this is enough: Suppose a vertex $v$ is in $A$ triangles as the first vertex, $B$ triangles as the second vertex, and $C$ triangles as the third vertex. It is not difficult to see $v$ have exactly $B + 2 \times C$ neighbours that are of smaller index, and there are at least $B+ 2\times C+ 1$ options. Finally, by using the following specific edge weights, the goal can be achieved: $1,4,4$ gives weights $5,5,8$ $2,3,3$ gives weights $5,5,6$ $3,2,2$ gives weights $5,5,4$ $1,4,3$ gives weights $5,4,7$ $2,3,2$ gives weights $5,4,5$ $3,2,1$ gives weights $5,4,3$ These numbers aren't exactly just completely random. You can see that they are composed of two components: A $(+1,-1,-1)$ part and a $(0,0,-1)$ part. Upto two copies of the first option and upto one copy of the second option have been used. There is also a simple solution in this specific case where $G$ consists of triangles and use only weights 1,2,3. This is a special case of 1-2-3 conjecture, which states that the above statement holds for arbitrary graph and using only the weights 1,2,3 (and no 4). Recently (March 2023) it has a claimed proof. The claimed algorithm is far from a linear time algorithm however.
[ "constructive algorithms", "graphs", "math" ]
3,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second const ll mod=998244353; const int N=2e6+1; ll n,m; vector<pair<int,int> >adj[N]; array<int,3>e[N]; array<int,3>f[N]; ll a[N],b[N]; pair<int,int>vis[10000005]; void solve(){ cin >> n >> m; for(int i=1; i<=n ;i++){ adj[i].clear(); } for(int i=1; i<=n ;i++){ cin >> a[i]; } for(int i=1; i<=m ;i++){ for(int j=0; j<3 ;j++){ cin >> e[i][j]; adj[e[i][j]].push_back({i,j}); } f[i][0]=3; f[i][1]=1; f[i][2]=1; a[e[i][0]]+=f[i][0]+f[i][2]; a[e[i][1]]+=f[i][1]+f[i][0]; a[e[i][2]]+=f[i][2]+f[i][1]; } for(int i=1; i<=n ;i++){ for(auto c:adj[i]){ for(int d=0; d<c.se ;d++){ vis[a[e[c.fi][d]]]={c.fi,d}; } } while(vis[a[i]].fi!=0){ int ed=vis[a[i]].fi; if(i==e[ed][1]){ a[i]++; a[e[ed][2]]++; f[ed][1]++; } else{ a[i]+=2; f[ed][0]--; f[ed][1]++; f[ed][2]++; } } for(auto c:adj[i]){ for(int d=0; d<c.se ;d++){ vis[a[e[c.fi][d]]]={0,0}; } } } for(int i=1; i<=m ;i++){ cout << f[i][0] << ' ' << f[i][1] << ' ' << f[i][2] << '\n'; } } int main(){ ios::sync_with_stdio(false);cin.tie(0); int t;cin >> t;while(t--) solve(); }
1816
A
Ian Visits Mary
Ian and Mary are frogs living on lattice points of the Cartesian coordinate plane, with Ian living on $(0,0)$ and Mary living on $(a,b)$. Ian would like to visit Mary by jumping around the Cartesian coordinate plane. Every second, he jumps from his current position $(x_p, y_p)$ to another lattice point $(x_q, y_q)$, such that no lattice point other than $(x_p, y_p)$ and $(x_q, y_q)$ lies on the segment between point $(x_p, y_p)$ and point $(x_q, y_q)$. As Ian wants to meet Mary as soon as possible, he wants to jump towards point $(a,b)$ using \textbf{at most $2$ jumps}. Unfortunately, Ian is not good at maths. Can you help him? A lattice point is defined as a point with both the $x$-coordinate and $y$-coordinate being integers.
Let us show that Ian can get to Mary within two moves. Indeed, consider $(x_1,y_1)$ and $(x_2,y_2)$ where $x_2-x_1=1$, since the value of the $x$-coordinates of a point lying on the segment joining $(x_1,y_1)$ and $(x_2,y_2)$, and is not at the endpoints, is strictly between $x_1$ and $x_2$, but there are no integers strictly between $x_1$ and $x_2$, the point must not be a lattice point. Similarly, no lattice points lie on the segment joining $(x_1,y_1)$ and $(x_2,y_2)$ with $y_2-y_1=1$ except for the endpoints. Therefore, Ian can jump from $(0,0)$ to $(x-1,1)$ to $(x,y)$. Originally, the problem asks you for the minimal amount of steps, which requires gcd. Since it would be too hard, we had a quite last-minute change to the current statement.
[ "constructive algorithms", "geometry", "number theory" ]
800
#include<bits/stdc++.h> using namespace std; void solve(){ int a,b; cin >> a >> b; cout << 2 << "\n" << a-1 << ' ' << 1 << "\n" << a << ' ' << b << "\n"; } int main(){ int t; cin >> t; while(t--){ solve(); } }
1816
B
Grid Reconstruction
Consider a $2 \times n$ grid, where $n$ is an \textbf{even} integer. You may place the integers $1, 2, \ldots, 2n$ on the grid, using each integer \textbf{exactly once}. A path is a sequence of cells achieved by starting at $(1, 1)$, then repeatedly walking either downwards or to the right, and stopping when $(2, n)$ is reached. The path should not extend beyond the grid. The cost of a path is the alternating sum of the numbers written on the cells in a path. That is, let the numbers written on the cells be $a_1, a_2, \ldots, a_k$ (in the order that it is visited), the cost of the path is $a_1 - a_2 + a_3 - a_4 + \ldots = \sum_{i=1}^k a_i \cdot (-1)^{i+1}$. Construct a way to place the integers $1, 2, \ldots, 2n$ on the grid, such that the minimum cost over all paths from $(1, 1)$ to $(2, n)$ is maximized. If there are multiple such grids that result in the maximum value, output any of them.
Consider the parity (odd/even) of $i+j$. What do you observe? Observe that $a_{i,j}$ will be added if $(i+j)$ is even, and will be subtracted otherwise. This forms a checkered pattern. Obviously, it is optimal for all values that will be added to be strictly larger than all values that will be subtracted. Also, the difference between the value of adjacent grids should be almost equal (by some definition of almost). We construct array $a$ as follows: $a_{1,1} = 2n-1$ and $a_{2,n} = 2n$ For $2 \leq i \leq n$ and $i$ is even, $a_{1,i} = i$ and $a_{2,i-1} = i - 1$ For $2 \leq i \leq n$ and $i$ is odd, $a_{1,i} = n + i - 1$ and $a_{2,i-1} = n + (i - 1) - 1$ For example, when $n=10$, the output will be (This is a very informal proof. See "Proof" below for a formal proof.) First of all, due to the checkered pattern, $a_{1,1}, a_{2,2}, a_{1,3}, \cdots, a_{2,n}$ should be filled with $n+1, n+2, n+3, \cdots, 2n$, and $a_{2,1}, a_{1,2}, a_{2,3}, \cdots, a_{1,n}$ should be filled with $1, 2, 3, \cdots, n$. In particular, $a_{1,1}$ and $a_{2,n}$ should be $2n-1$ and $2n$. Next, as we are trying to maximise the minimum, the difference between paths shouldn't be large (since the minimum path will be smaller if the difference is larger). Notice that a path consists of a prefix of $a_1$ and a suffix of $a_2$, and the difference between $2$ adjacent paths is $\pm (a_{1,k} - a_{2,k-1})$ (depending on the parity of $k$). It is optimal for the difference to be as small as possible (which is $1$). Finally, it is optimal that $a_{1,k} - a_{2,k-1}$ stays constant in the whole array. If they are different, the difference between $2$ paths (not adjacent) will be larger than $1$, which is suboptimal. Consider the cost of the top right path and bottom left path. The cost of the top right path is $a_{1,1} - a_{1,2} + a_{1,3} - \cdots - a_{1,n} + a_{2,n}$. The cost of the bottom right path is $a_{1,1} - a_{2,1} + a_{2,2} - a_{2,3} + ... + a_{2,n}$. Summing both values, we get $a_{1,1} + a_{2,n} + ((a_{1,1} - a_{1,2} + a_{1,3} - a_{1,4} + ... - a_{1,n}) + (-a_{2,1} + a_{2,2} - a_{2,3} + ... + a_{2,n}))$ which is equal to $a_{1,1} + a_{2,n} + ((a_{1,1} + a_{2,2} + a_{1,3} + a_{2,4} + \cdots + a_{2,n}) - (a_{2,1} + a_{1,2} + a_{2,3} + a_{1,4} + \cdots + a_{1,n}))$ This value attains maximum when $a_{1,1} = 2n$, $a_{2,n} = 2n-1$, $(a_{1,1} + a_{2,2} + a_{1,3} + a_{2,4} + \cdots + a_{2,n}) = ((n+1) + (n+2) + (n+3) + \cdots + 2n)$ and $(a_{2,1} + a_{1,2} + a_{2,3} + a_{1,4} + \cdots + a_{1,n}) = (1 + 2 + 3 + \cdots + n)$, which is $(2n + (2n - 1) + (\frac{(n)((n+1)+2n)}{2}) - (\frac{(n)(1+n)}{2})) = (n^2 + 4n - 1)$. Therefore, the upper bound for the maximum cost is $\lfloor \frac{n^2 + 4n - 1}{2} \rfloor = \frac{1}{2}n^2 + 2n - 1$. We will now show that the construction above meets the upper bound. Let $P_k$ be the cost of the path $a_{1,1}, a_{1,2}, a_{1,3}, \cdots, a_{1,k}, a_{2,k}, a_{2,k+1}, \cdots, a_{2,n}$. Observe that $P_k - P_{k-1} = (-1)^k(a_{1,k} - a_{2,k-1}) = (-1)^k$, as the paths differ by exactly $2$ grids and $a_{1,k} - a_{2,k-1} = 1$ (from the above construction). Calculating $P$, $P_1 = (2n - 1) - 2 + (n + 2) - 4 + (n + 4) - \cdots - (n - 2) + 2n = (2n - 1) + (n)(\frac{n}{2} - 1) - n + 2n = \frac{1}{2}n^2 + 2n - 1$ $P_2 = P_1 + (-1)^2 = \frac{1}{2}n^2 + 2n$ $P_3 = P_2 + (-1)^3 = \frac{1}{2}n^2 + 2n - 1$ $\cdots$ Therefore, $min(P) = \frac{1}{2}n^2 + 2n - 1$, which achieves the upper bound. Can you find a construction for a $n \times n$ grid (and give a formal proof)? (We don't have a solution)
[ "constructive algorithms", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans[3][n + 1]; ans[1][1] = 2 * n - 1; ans[2][n] = 2 * n; for (int i = 2; i <= n; i++) { if (i % 2 == 0) { ans[1][i] = i; ans[2][i - 1] = i - 1; } else { ans[1][i] = n + (i - 1); ans[2][i - 1] = n + (i - 1) - 1; } } for (int i = 1; i <= 2; i++) { for (int j = 1; j <= n; j++) { cout << ans[i][j] << (j == n ? '\n' : ' '); } } } }
1817
A
Almost Increasing Subsequence
A sequence is almost-increasing if it does not contain three \textbf{consecutive} elements $x, y, z$ such that $x\ge y\ge z$. You are given an array $a_1, a_2, \dots, a_n$ and $q$ queries. Each query consists of two integers $1\le l\le r\le n$. For each query, find the length of the longest almost-increasing subsequence of the subarray $a_l, a_{l+1}, \dots, a_r$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.
It is not obvious how the condition in the statement for an almost-increasing subsequence can be turned into a fast data structure that can support queries. So instead of tackling the problem head on, let's try to make an upperbound for how many elements can be in the maximum length almost-increasing subsequence. Assume you're given a query about the subarray of the original array $[a_l, a_{l+1}, \dots, a_r]$. Let's partition this array into decreasing subarrays. This means everytime when $a_i < a_{i+1}$ we place a cut between $a_i$ and $a_{i+1}$. For example, consider the array $[4,6,7,2,2,3]$, it will be cut into $[4], [6], [7, 2, 2], [3]$. All these small subarrays are non-increasing, which means that any subsequence of such a subarray is non-increasing. Because an almost-increasing subsequence cannot have three consecutive elements $x \geq y \geq z$, in each of the subarrays of our partition at most $2$ elements can be chosen to insert into our almost-increasing subsequence. Actually we can put exactly $\min( \text{|subarray|}, 2)$ elements of each subarray into the increasing subsequence, by taking the first and the last element of each subarray. This is valid, because the cuts for the partition were made at places where $a_i < a_{i+1}$, so every $b_i \geq b_{i+1}$ in our candidate subsequence is preceded and followed by a $b_j < b_{j+1}$. By our upperbound, this construction is optimal. The sum, $\sum_\limits \text{partition} \min( \text{|subarray|}, 2)$ can be calculated for one query in linear time, giving a $O(n q)$ solution. To optimize this, the sum $\sum_\limits \text{partition} \min( \text{|subarray|}, 2)$ can be rewritten to $\sum_\limits \text{partition}|\text{subarray}| - |\text{inner elements}|$, where inner elements of a subarray are all the elements that are not the first or last element. For such elements $a_i$, we know that $a_{i-1} \geq a_i \geq a_{i+1}$. The sum of lengths over the partition sums to $r-l+1$. So we're left with counting the number of special indices $l < i < r$ such that $a_{i-1} \geq a_i \geq a_{i+1}$. This can be done with $O(n)$ preprocessing and $O(1)$ queries using prefix sums. For a query we can output $r-l+1 - |\textit{special} \ \text{indices}|$. There are some literal edgecases, where some care in the implementation is needed. The total time complexity is $O(n+q)$.
[ "binary search", "data structures", "greedy" ]
1,500
#include "bits/stdc++.h" using namespace std; typedef vector<int> vi; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n,q; cin >> n >> q; vi a(n); for(int& i : a) cin >> i; vi p(n-1); for(int i=1;i<n-1;++i) { int downhill = a[i-1]>=a[i] and a[i]>=a[i+1]; p[i] = p[i-1] + downhill; } while(q--) { int l,r; cin >> l >> r; --l,--r; if(l==r) { cout << "1\n"; } else { int ans = (r-l+1) - p[r-1] + p[l]; cout << ans << '\n'; } } }
1817
B
Fish Graph
You are given a simple undirected graph with $n$ nodes and $m$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $1$ to $n$. We define a graph to be a Fish Graph if it contains a simple cycle with a special node $u$ belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly $2$ extra edges. Both edges should connect to node $u$, but they should not be connected to any other node of the cycle. Determine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph. In this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph. \begin{center} {\small Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph.} \end{center}
Problem idea: jeroenodb Preparation: jeroenodb Can you find a necessary condition for whether a Fish Subgraph exists? For the Fish Subgraph to exist, the graph must have a cycle with one node in the cycle having degree at least 4. When the necessary condition is satisfied, actually, you can always find a Fish Subgraph. Try to prove this, and see if your proof can be turned into an algorithm.
[ "brute force", "constructive algorithms", "dfs and similar", "graphs" ]
1,900
null
1817
B
Fish Graph
You are given a simple undirected graph with $n$ nodes and $m$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $1$ to $n$. We define a graph to be a Fish Graph if it contains a simple cycle with a special node $u$ belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly $2$ extra edges. Both edges should connect to node $u$, but they should not be connected to any other node of the cycle. Determine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph. In this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph. \begin{center} {\small Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph.} \end{center}
Try to prove this, and see if your proof can be turned into an algorithm. Firstly, let's try to find some necessary conditions for a Fish Subgraph to exist. Because the Fish Graph has a cycle with two extra edges attached, the original must contain a cycle with a node in the cycle having degree at least 4. It turns out this condition is actually sufficient, let's prove this: So, assume a graph contains a cycle, and one of the nodes in the cycle has $deg(u) \geq 4$. We will only look at this cycle, and two extra edges connected to the special node that are not cycle edges, and remove all the other edges from consideration. These two extra edges could have both endpoints inside the cycle, creating diagonal(s) and not the fins of the Fish Graph we want. If both edges don't form diagonals of the cycle, we've found a Fish Graph. Otherwise, let's label the nodes in the cycle $v_1 v_2 \dots v_k$, and label the two extra edges $e_1$ and $e_2$. Look at the diagonal that connects nodes $v_1$ and $v_d$, with $d>2$ as small as possible. Using it, we find a smaller cycle $v_1 v_2 ... v_d$. To finish the proof, we notice that one of the edges from $\{e_1,e_2\}$ and the edge $v_1 v_k$ now have become free to use as fins of the Fish Graph, as they are no longer diagonals of the smaller cycle. $\square$ This proof can be turned into an algorithm solving the problem. First off, we need to find any cycle with a node with degree $\geq 4$. Let's brute force the node $u$, which must have degree $\geq 4$. Then brute force the first edge of the cycle $uv$ (by looping over the adjacency list of node $u$). Now to find any cycle, it suffices to find a path from $v$ to $u$, temporarily deleting the edge $uv$. This can be done with DFS or BFS. When a cycle is found, all edges except $2$ extra edges can be removed from consideration, and the proof for sufficiency can be implemented to fix possible diagonals. For BFS it is even easier, because it already finds the shortest path from $u$ to $v$, making diagonals impossible. The time complexity will be $\mathcal{O}(m \cdot (n+m))$, because the algorithm loops over all edges, and does a graph traversal for each of them. Bonus: How do you make this algorithm $\mathcal{O}(n+m)$?
[ "brute force", "constructive algorithms", "dfs and similar", "graphs" ]
1,900
#include "bits/stdc++.h" using namespace std; #define all(x) begin(x),end(x) typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pi; void solve() { int n,m; cin >> n >> m; vvi adj(n); while(m--) { int u,v; cin >> u >> v; --u,--v; adj[u].push_back(v); adj[v].push_back(u); } // find cycle and node with big degree. for(int u=0;u<n;++u) if(adj[u].size()>=4) for(int v : adj[u]) { // find path from u to v, without edge (u,v) vi cur; vi p; vector<bool> vis(n); auto dfs = [&](auto&& self, int at) -> void { vis[at]=1; cur.push_back(at); if(at==v) { p=cur; return; } for(int to : adj[at]) if(!vis[to]) { if(at==u and to==v) continue; self(self,to); if(!p.empty()) return; } cur.pop_back(); }; dfs(dfs,u); if(p.empty()) continue; // found cycle, with a node with degree >=4 vi extra = adj[u]; extra.resize(4); int mn = p.size(); for(auto i : extra) { auto it = find(all(p),i); if(it!=p.begin()+1) { mn = min(mn,int(it-p.begin())+1); } } p.resize(mn); partition(all(extra),[&](int i) {return count(all(p),i)==0;}); extra.resize(2); cout << "YES\n"; cout << p.size()+2 << '\n'; auto out = [&](int a, int b) {cout << a+1 << ' ' << b+1 << '\n';}; int prv=p.back(); for(auto i : p) { out(i,prv); prv=i; } out(u,extra[0]); out(u,extra[1]); return; } cout << "NO\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--) solve(); }
1817
C
Similar Polynomials
A polynomial $A(x)$ of degree $d$ is an expression of the form $A(x) = a_0 + a_1 x + a_2 x^2 + \dots + a_d x^d$, where $a_i$ are integers, and $a_d \neq 0$. Two polynomials $A(x)$ and $B(x)$ are called similar if there is an integer $s$ such that for any integer $x$ it holds that $$ B(x) \equiv A(x+s) \pmod{10^9+7}. $$ For two similar polynomials $A(x)$ and $B(x)$ of degree $d$, you're given their values in the points $x=0,1,\dots, d$ modulo $10^9+7$. Find a value $s$ such that $B(x) \equiv A(x+s) \pmod{10^9+7}$ for all integers $x$.
Not that if polynomials are equivalent, they must have the same leading coefficient $k$. Let $A(x) = \dots + a x^{d-1} + k x^d$ and $B(x) = \dots + b x^{d-1} + k x^d$. Then $B(x-s) = \dots + (b-k s d)x^{d-1} + x^d.$ So, if $A(x)$ and $B(x)$ are equivalent, then $A(x) \equiv B(x-s)$, where $a = b-k s d$, or $s = \frac{b-a}{kd}$. General remark. On a more intuitive level, you can perceive $s$ as the value by which you should shift the argument of $A(x)$, so that the sums of roots of $A(x)$ and $B(x)$ coincide, as the coefficient near $x^{d-1}$ is just the negated sum of roots of the polynomials. Lagrange interpolation approach. Generally, if $f(x_0)=y_0, \dots, f(x_d) = y_d$, it is possible to represent $f(x)$ as $f(x) = \sum\limits_{i=0}^d y_i \prod\limits_{j \neq i} \frac{x - x_j}{x_i - x_j}.$ From this, it is possible to find the coefficients near $x^d$ and $x^{d-1}$, that is a sum of corresponding coefficients in each individual summand. Altogether it sums up as $[x^{d}]f(x) = \sum\limits_{i=0}^d y_i \prod\limits_{j \neq i} \frac{1}{x_i - x_j} = \sum\limits_{i=0}^d y_i \prod\limits_{j \neq i} \frac{1}{i-j} = \sum\limits_{i=0}^d y_i \frac{(-1)^{d-i}}{i! (d-i)!}$ Let's denote $c_i = \frac{(-1)^{d-i}}{i! (d-i)!}$, then it simplifies a bit as $[x^d] f(x) = \sum\limits_{i=0}^d y_i c_i,$ and for the coefficient near $d-1$ we should note that $[x^{d-1}] (x-x_1) \dots (x-x_d) = -(x_1 + \dots + x_d)$, thus $[x^{d-1}]f(x) = -\sum\limits_{i=0}^d y_i c_i \sum\limits_{j \neq i} j = -\sum\limits_{i=0}^d y_i c_i \left(\frac{d(d+1)}{2} - i\right).$ Knowing the coefficients near $x^d$ and $x^{d-1}$ for both $A(x)$ and $B(x)$, it is easy to find $a=[x^{d-1}]A(x)$, $b=[x^{d-1}]B(x)$ and $k = [x^d] A(x) = [x^d] B(x)$, which in turn allow us to compute $s$ with the formula above. Finite differences approach. You can consider adjacent differences in values $\Delta A(i) = A(i) - A(i+1)$. The result $\Delta A(i)$ is a polynomial in $i$ that has a degree $d-1$. Taking the differences $d-1$ times, we get the values of $\Delta^{d-1} A(x)$ and $\Delta^{d-1} B(x)$ in $x=\{0, 1\}$. On the other hand, $\Delta^{d-1} B(x) = \Delta^{d-1} A(x+s)$, so you still need to find $s$, but $\Delta^{d-1} A(x)$ and $\Delta^{d-1} B(x)$ are the polynomials of degree $1$, which makes the whole problem trivial. Note: To compute $\Delta^{d-1} A(0)$ and $\Delta^{d-1} A(1)$ in $O(d)$, one can use the binomial formula: $\Delta^k A(x) = \sum\limits_{i=0}^k (-1)^i \binom{k}{i} A(x+i).$ Indeed, if we denote by $S$ an operator such that $S A(x) = A(x+1)$, then $\Delta^k A(x)= (I-S)^k A(x)= \sum\limits_{i=0}^k (-1)^i \binom{k}{i} S^i A(x) = \sum\limits_{i=0}^k (-1)^i \binom{k}{i} A(x+i).$
[ "combinatorics", "math" ]
2,400
const int mod = 1e9 + 7; namespace algebra { const int maxn = 3e6 + 42; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); template<typename T> T bpow(T x, size_t n) { if(n == 0) { return T(1); } else { auto t = bpow(x, n / 2); t = t * t; return n % 2 ? x * t : t; } } const int m = mod; struct modular { int r; constexpr modular(): r(0) {} constexpr modular(int64_t rr): r(rr % m) {if(r < 0) r += m;} modular inv() const {return bpow(*this, m - 2);} modular operator - () const {return r ? m - r : 0;} modular operator * (const modular &t) const {return (int64_t)r * t.r % m;} modular operator / (const modular &t) const {return *this * t.inv();} modular operator += (const modular &t) {r += t.r; if(r >= m) r -= m; return *this;} modular operator -= (const modular &t) {r -= t.r; if(r < 0) r += m; return *this;} modular operator + (const modular &t) const {return modular(*this) += t;} modular operator - (const modular &t) const {return modular(*this) -= t;} modular operator *= (const modular &t) {return *this = *this * t;} modular operator /= (const modular &t) {return *this = *this / t;} bool operator == (const modular &t) const {return r == t.r;} bool operator != (const modular &t) const {return r != t.r;} bool operator < (const modular &t) const {return r < t.r;} explicit operator int() const {return r;} int64_t rem() const {return 2 * r > m ? r - m : r;} }; istream& operator >> (istream &in, modular &x) { return in >> x.r; } ostream& operator << (ostream &out, modular const& x) { return out << x.r; } vector<modular> F(maxn), RF(maxn); template<typename T> T fact(int n) { static bool init = false; if(!init) { F[0] = T(1); for(int i = 1; i < maxn; i++) { F[i] = F[i - 1] * T(i); } init = true; } return F[n]; } template<typename T> T rfact(int n) { static bool init = false; if(!init) { RF[maxn - 1] = T(1) / fact<T>(maxn - 1); for(int i = maxn - 2; i >= 0; i--) { RF[i] = RF[i + 1] * T(i + 1); } init = true; } return RF[n]; } } using namespace algebra; using base = modular; void solve() { int d; cin >> d; vector<base> A(d + 1), B(d + 1); copy_n(istream_iterator<base>(cin), d + 1, begin(A)); copy_n(istream_iterator<base>(cin), d + 1, begin(B)); base s = 0, k2 = 0; auto coef = [&](int i) { return base((d - i) % 2 ? -1 : 1) * rfact<base>(i) * rfact<base>(d - i); }; for(int i = 0; i <= d; i++) { s += (A[i] - B[i]) * coef(i) * (d * (d + 1) / 2 - i); k2 += (A[i] + B[i]) * coef(i); } s *= base(2) / (k2 * d); cout << s << "\n"; }
1817
D
Toy Machine
There is a toy machine with toys arranged in two rows of $n$ cells each ($n$ is odd). \begin{center} Initial state for $n=9$. \end{center} Initially, $n-2$ toys are placed in the non-corner cells of the top row. The bottom row is initially empty, and its leftmost, rightmost, and central cells are blocked. There are $4$ buttons to control the toy machine: left, right, up, and down marked by the letters L, R, U, and D correspondingly. When pressing L, R, U, or D, all the toys will be moved simultaneously in the corresponding direction and will only stop if they push into another toy, the wall or a blocked cell. Your goal is to move the $k$-th toy into the leftmost cell of the top row. The toys are numbered from $1$ to $n-2$ from left to right. Given $n$ and $k$, find a solution that uses at most $1\,000\,000$ button presses. To test out the toy machine, a \textbf{web page} is available that lets you play the game in real time.
Problem idea: adamant Preparation: jeroenodb Instead of caring about the positions of all the toys, we only need to care about the position of the special toy with index $k$. The other toys can be treated as undistinguishable. The intended way of solving this problem is playing the game in the webpage, trying to come up with some simple combinations of operations that make the special toy move to another position in a predictable way. Using these building blocks in a smart way, finding a way to move the special toy to the topleft. As the size of the grid can be up to $100\,000$ and we can make $1\,000\,000$ moves, we will be aiming for a solution which does a linear number of moves. There are lots of potential solutions which use a linear number of moves, here is a relatively painless one: Do casework on $k$: Case $1$: If $1 \leq k < \frac{n-1}{2}$, we initally make one $\texttt{R}$ button press to align the toys with the right boundary. After this, there is an easy pattern to expose all the toys in the left halve, one by one: $\texttt{DRURDRUR...}$ repeated. When the special toy is exposed, the repeating pattern is stopped, and $\texttt{DL}$ are pressed. Toy $k$ will be moved to the topleft corner. Left halve solution for $n=15$. Case $2$: If $k = \frac{n-1}{2}$, the puzzle can be solved in two moves: $\texttt{DL}$. Solution for middle toy and $n=15$. Case $3$: If $\frac{n-1}{2} < k \leq n-2$, we try to reduce back to case $1$, by moving the special toy to the left halve, and ensuring that all other toys are in the top row. Using symmetry, we can apply case $1$ to $k^\prime = n-1 - k$, but mirror all horizontal moves, to move the toy to the topright corner. The other toys are no longer all in the top row. To fix this, the last pattern we need is again $\texttt{DRURDRUR...}$ repeated. After a while of repeating this, all toys will be in the right halve of the board, occupying the top and bottom row. To finish moving the special toy (which stayed in the topright corner), we do the buttons presses $\texttt{LDRU}$. All toys end up in the top row, and the special toy will be at position $k_\text{new} = \frac{n-1}{2} - 1$, so this successfully reduces to case $1$. Full solution for right halve for $n=15$. How many moves does this take? In case $1$ the pattern $\texttt{DRUR}$ needs to be repeated at most $\approx \frac{n}{2}$ times. In case $3$, we need to use the first pattern $\frac{n}{2}$ times, and we use the second pattern $\frac{n}{2}$ times. We reduce down to case $1$, but luckily the special toy is already close to the correct position, so only a constant number of extra moves are done. So in total, this solution uses $O(1) + \max \left( 4\frac{n}{2}, 4 \cdot 2 \frac{n}{2} \right) = 4n + O(1)$ moves. So this solution fits well within the constraints, although it is pretty wasteful. Bonus: Can you prove that the optimal number of moves needed in the worstcase (over all $k$) for a width of $n$ is $\Omega(n)$? We only did some testing of small cases, with a bruteforce BFS solution, and found that the worstcase is around $n/2$ button presses.
[ "constructive algorithms", "games", "implementation" ]
2,700
#include "bits/stdc++.h" using namespace std; int main() { int n,k; cin >> n >> k; --k; int half = (n-3)/2; string res = ""; if(k==half) { res = "DL"; } else { while(true) { if(k<half) { res+="R"; int need = half-1-k; while(need--) { res+="DRUR"; } res+="DL"; break; } else { int need = k-half-1; while(need--) { res+="LDLU"; } res+="LDR"; for(int i=0;i<half+1;++i) { res+="DRUR"; } res+="LDRU"; k = half-1; } } } cout << res << '\n'; }
1817
E
Half-sum
You're given a multiset of non-negative integers $\{a_1, a_2, \dots, a_n\}$. In one step you take two elements $x$ and $y$ of the multiset, remove them and insert their mean value $\frac{x + y}{2}$ back into the multiset. You repeat the step described above until you are left with only two numbers $A$ and $B$. What is the maximum possible value of their absolute difference $|A-B|$? Since the answer is not an integer number, output it modulo $10^9+7$.
Similar to the Huffman encoding, the process described in the statement can be represented as constructing a tree, in which on every step we take two trees with weights $a$ and $b$, and connect them with a shared root into a single tree with weight $\frac{a+b}{2}$. In the end of the process, we have two trees with weights $A$ and $B$, and we want to maximize $|A-B|$. In these trees, let $h_i$ be the height of the leaf corresponding to $a_i$. Then $a_i$ contributes to the final answer with the coefficient either $2^{-h_i}$, or $-2^{-h_i}$, depending on which tree it is in. If we fix any set $\{h_1, \dots, h_n\}$ and would need to distribute $a_1, \dots, a_n$ between the heights, assuming $A < B$, it would always be better to send smaller numbers to the $A$-tree and bigger numbers to the $B$-tree, so that the positive impact belongs to bigger numbers and the negative impact belongs to the smaller numbers. That being said, if $a_1 \leq a_2 \leq \dots \leq a_n$, it is always optimal to choose a number $1 \leq k < n$ and send $a_1, a_2, \dots, a_k$ to the $A$-tree, while sending $a_{k+1}, a_{k+2}, \dots, a_n$ to the $B$-tree. Now we need to understand, how to pick an optimal $k$ and how to construct optimal trees with a fixed $k$. Assume that $a_1, a_2, \dots, a_k$ will all go to the $A$-tree, for which we want to minimize the weight. What is the optimal distribution of $h_1, h_2, \dots, h_k$? Turns out, there always exists an optimal configuration, in which the constructed tree is very skewed, in a way that each vertex has at most $1$ child that is not a leaf. Indeed, consider a vertex $v$ which has two children $L$ and $R$, both of which have children of its own. Let $x$ be a leaf with the smallest weight in the whole sub-tree of $v$ (without loss of generality, assume that it's a descendant of $L$). If we swap $x$ with $R$, we will effectively swap coefficients with which $x$ and $R$ contribute to the weight of $A$ overall. In other words, if the initial contribution was $2^{-h_x} \cdot x + 2^{-h_R} \cdot R$, it will become $2^{-h_x} \cdot R + 2^{-h_R} \cdot x$. Note that $x \leq R$ and $h_x > h_R$. As a consequence, the later sum is not worse than the former and it's always optimal to swap $x$ and $R$ due to the rearrangement inequality. Similar argument works for the tree $B$, except for we want to maximize sum in it, rather than minimize it. With this in mind, if the split is $a_1, a_2, \dots, a_k$ and $a_{k+1}, a_{k+2}, \dots, a_n$, then the heights are $1, 2, 3, \dots, k-2, k-1, k-1$ for the first block, and similar (but reversed) for the second block. This allows us to find a specific value of $|A-B|$ for each specific $k$ in $O(n)$. How to improve from that? We suggest two possible approaches here. Divide and conquer approach. Assume that the optimal $k$ belongs to the interval $[l, r]$. In this case, all numbers outside the interval will have the same coefficients regardless of specific $k$, as long as $k$ itself is from the interval. This means that we can solve the problem with divide and conquer approach: Let $m = \lfloor \frac{r-l}{2}\rfloor$; Find best $k$ recursively on $[l, m]$ and $[m, r]$; Compare them on the whole $[l; r]$, and return the best of them. Which makes overall $O(n \log n)$ complexity. Alternative approach. Let's compare the distribution of coefficients for $|A|=k$ and $|A|=k-1$: $\mathbf{|A| = k}$$-a_1 \color{green}{2^{-1}}$$-a_2 \color{green}{2^{-2}}$$\dots$$-a_{k-2} \color{green}{2^{-(k-2)}}$$-a_{k-1} \color{red}{2^{-(k-1)}}$$-a_k \color{red}{2^{-(k-1)}}$$a_{k+1} \color{red}{2^{-(n-k-1)}}$$a_{k+2} \color{green}{2^{-(n-k-1)}}$$\dots$$a_{n-1} \color{green}{2^{-2}}$$a_{n} \color{green}{2^{-1}}$$\mathbf{|A| = k-1}$$-a_1 \color{green}{2^{-1}}$$-a_2 \color{green}{2^{-2}}$$\dots$$-a_{k-2} \color{green}{2^{-(k-2)}}$$-a_{k-1} \color{blue}{2^{-(k-2)}}$$a_k \color{blue}{2^{-(n-k)}}$$a_{k+1} \color{blue}{2^{-(n-k)}}$$a_{k+2} \color{green}{2^{-(n-k-1)}}$$\dots$$a_{n-1} \color{green}{2^{-2}}$$a_{n} \color{green}{2^{-1}}$ As you see, almost all coefficients stay the same, except for coefficients near $a_{k-1}$, $a_k$ and $a_{k+1}$: $\mathbf{|A|=k}$$\mathbf{|A|=k-1}$$a_{k-1} \cdot \square$$-2^{-(k-1)}$$-2^{-(k-2)}$$a_{k} \cdot \square$$-2^{-(k-1)}$$2^{-(n-k)}$$a_{k+1} \cdot \square$$2^{-(n-k-1)}$$2^{-(n-k)}$ Therefore, let $f(k)$ be the optimal answer for $|A|=k$, and let $\alpha=k-1$, $\beta=n-k$ we may say that $f(k) - f(k-1) = (a_{k+1}-a_k)2^{-\beta} - (a_k - a_{k-1}) 2^{-\alpha}.$ Or, multiplying it with $2^n$ we get $2^n[f(k) - f(k-1)] = (a_{k+1}-a_k)2^{k} - (a_k - a_{k-1}) 2^{n-k+1}.$ We can sum it up to get the difference between $f(k)$ and $f(j)$ for arbitrary $j < k$: $2^n [f(k) - f(j)] = (d_k 2^k + \dots + d_{j+1} 2^{j+1}) - (d_{k-1}2^{n-(k-1)} + \dots + d_j 2^{n-j}),$ where $d_i = a_{i+1} - a_i$. Then, assuming $d_k > 0$, we can bound it as $2^n [f(k) - f(j)] \geq 2^k - 2^{n-j}\max d_i = 2^k - 2^{n-j+\log \max d_i}.$ The later means that $f(k) > f(j)$ when $k + j > n + \log \max d_i$, which is the case when $k > \frac{n}{2} + \log \max d_i$ and $j \geq \frac{n}{2}$. By the same argument, we may show that $f(k) > f(j)$ when $k < \frac{n}{2} - \log \max d_i$ and $k < j < \frac{n}{2}$. In other words, it means that one of the following holds for the value $k$, on which the maximum value of $f(k)$ is achieved: $k$ is the first position in the array, at which $d_k = a_{k+1} - a_k > 0$, $k$ is the last position in the array, at which $d_k = a_{k+1} - a_k > 0$, $k$ belongs to the segment $[\frac{n}{2} - \log \max d_i, \frac{n}{2} + \log \max d_i] \subset [\frac{n}{2}-30, \frac{n}{2}+30]$. Therefore, there are at most $64$ positions of interest in the array which can be checked manually. Moreover, optimal value in the segment $[\frac{n}{2}-30, \frac{n}{2}+30]$ can be found by checking every possible position while ignoring all the elements outside of the segment (due to the result from the divide and conquer approach). This allows, assuming $a_1 \leq a_2 \leq \dots \leq a_n$, to resolve the problem in $O(n)$.
[ "brute force", "divide and conquer", "greedy" ]
3,400
// split into 1, ..., k and k+1, ..., n pair<int, istring> check_k(istring const& a, int k) { int n = size(a); istring A(n, 0), B(n, 0); for(int i = 0; i < n; i++) { if(i <= k) { A[min(k, i + 1)] += a[i]; } else { B[min(n - k - 2, n - i)] += a[i]; } } // multiply by 2^(n - i - 1) instead of dividing by 2^i reverse(all(A)); reverse(all(B)); int carry = 0; // subtract A from B and normalize base 2 for(int i = 0; i < n; i++) { B[i] -= A[i] - carry; carry = B[i] >> 1; // floor(B[i] / 2) B[i] &= 1; } if(carry < 0) { return {-1, {}}; // it's always possible to make it positive } while(carry) { B.push_back(carry & 1); carry >>= 1; } while(!B.empty() && B.back() == 0) { B.pop_back(); } reverse(all(B)); return {(int)size(B) - n, B}; } const int mod = 1e9 + 7; int bpow(int x, int n) { if(!n) { return 1; } else if(n % 2) { return int64_t(x) * bpow(x, n - 1) % mod; } else { return bpow(int64_t(x) * x % mod, n / 2); } } int inv(int x) { return bpow(x, mod - 2); } void solve() { int n; cin >> n; istring a(n, 0); for(int i = 0; i < n; i++) { cin >> a[i]; } sort(all(a)); auto cand = check_k(a, 0); int cnt = 0; for(int i = 1; i < n; i++) { if(a[i] != a[i - 1]) { cand = max(cand, check_k(a, i - 1)); cnt++; if(cnt == 30) { break; } } } cnt = 0; istring b = a; reverse(all(b)); for(int i = 1; i < n; i++) { if(b[i] != b[i - 1]) { cand = max(cand, check_k(a, n - i - 1)); cnt++; if(cnt == 30) { break; } } } auto [sz, ansf] = cand; int ans = 0; for(size_t i = 0; i < size(ansf); i++) { ans = (ans + bpow(2, (mod - 1) + (sz - i)) * ansf[i]) % mod; } cout << ans << "\n"; }
1817
F
Entangled Substrings
\begin{quote} Quantum entanglement is when two particles link together in a certain way no matter how far apart they are in space. \end{quote} You are given a string $s$. A pair of its non-empty substrings $(a, b)$ is called entangled if there is a (possibly empty) link string $c$ such that: - Every occurrence of $a$ in $s$ is immediately followed by $cb$; - Every occurrence of $b$ in $s$ is immediately preceded by $ac$. In other words, $a$ and $b$ occur in $s$ only as substrings of $acb$. Compute the total number of entangled pairs of substrings of $s$. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.
Suffix automaton approach. For every substring $a$ of $s$ we can define the longest string $\hat{a}$ such that $a$ only occurs in $s$ as a specific substring of $\hat{a}$. To find $\hat{a}$, we find the longest strings $x$ and $y$ such that the occurrences of $a$ are always preceded by $x$ and always succeeded by $y$. Then, we can say that $\hat{a} = x a y$. If you're familiar with suffix structures you would recognize that in this terms, $xa$ is the longest string that belongs to the same state of the suffix automaton of $s$ as $a$. Knowing that, how would we find $\hat{a} = x a y$? When we add a new character at the end of a substring, we make a transition in the suffix automaton via this character. Generally, if the state of the string $xa$ has transitions via two different characters, it would mean that the string $y$ is empty, as it means that different strings may succeed the occurrences of $xa$. Also, if the state is terminal, it would mean that the last occurrence of $xa$ is at the suffix of $s$ and it can not be succeeded by any non-empty string. If the state is not terminal, and its only transition is by a character $c$, it means that the string $xa$ is always succeeded by $c$. The facts above mean that to find $xay$, we may start with the state of the suffix automaton that corresponds to the string $a$, and then, while the state is non-terminal, and it only has a single out-going transition, we move to a next state via this transition. In the end, $xay$ would be the longest string of the state we ended up in. Now back to the problem. Note that if a string $a$ only occurs in $s$ as a substring of another string $t$, it means that $\hat{a} = \hat{t}$. In terms of the strings $a$, $b$ and $c$ from the statement it means that $\hat{a} = \hat{b} = \widehat{acb}$. Assume that we grouped together the states of the suffix automaton that end up in the same state if you follow unique out-going transitions from them until you get into a state with two possible transitions, or a terminal state. Each group corresponds to a unique largest string such that any string that belongs to any state from the group only occurs in $s$ as a specific substring of the largest string. Note that for strings that belong to the same state of the suffix automaton, they also have the same string $y$. The length $|y|$ determines the unique position in which all the strings from the state occur in the largest string as set of nested suffixes. So, for the largest string $t$, their right position of occurrences will be $|t|-|y|$, and their lengths form the contiguous segment $[len(link(q)) + 1, len(q)]$. Thus, the whole problem reduces for each group of states to the following: We have a bunch of triplets $(l_1, l_2, r)$. Each triple denotes a set of segments $[l_1, r], [l_1 + 1, r], \dots, [l_2, r]$. You need to count the number of non-overlapping pairs of segments. This can be done in $O(n \log n)$ with the help of segment tree. Suffix array approach. There is an alternative solution using suffix arrays (suggested by Dario). Let $a_0, \dots, a_{n-1}$ be the suffix array and $b_0, \dots, b_{n-2}$ be the longest common prefix of adjacent elements of the suffix array. We say that $[l, r]$ is good for length $len$ if the positions $a[l, r]$ are exactly the occurrences of a sub-string of length $len$. This is equivalent to $b_{l-1}, b_r < len$ and $b_i \geq len$ for all $l \leq i < r$. There are at most $O(n)$ good intervals (an interval is good if it is good for any length). Indeed they are a subset of the sub-trees of the Cartesian tree of the array $b$. Now we iterate over the good intervals. Let $[l, r]$ be a good intervals for the lengths $[u, v]$. Consider a translation $t$ and check if by adding $t$ to all elements $a_l, a_{l+1}, .., a_r$ one gets a good interval. This can be checked in $O(1)$. This check can be done from $t=u$ to $t=v$ and one can stop as soon as a bad $t$ is found. If t is a good translation; then we can count in $O(1)$ the corresponding good pairs of sub-strings $A, B$. And this concludes the problem. It remains to perform quickly step 3. Given two good intervals $I, J$ we say that $J$ follows $I$ if $a[J]$ coincides with the array one obtains adding $1$ to all elements of $a[I]$. The "following" relationship creates a family of chains on the good intervals. One performs step 3 independently on the various chains.
[ "string suffix structures", "strings" ]
3,500
map<char, int> to[maxn]; int len[maxn], link[maxn]; int last, sz = 1; void add_letter(char c) { int p = last; last = sz++; len[last] = len[p] + 1; for(; to[p][c] == 0; p = link[p]) { to[p][c] = last; } int q = to[p][c]; if(q != last) { if(len[q] == len[p] + 1) { link[last] = q; } else { int cl = sz++; len[cl] = len[p] + 1; link[cl] = link[q]; to[cl] = to[q]; link[last] = link[q] = cl; for(; to[p][c] == q; p = link[p]) { to[p][c] = cl; } } } } int term[maxn]; int used[maxn], comp[maxn], dist[maxn]; vector<int> in_comp[maxn]; void dfs(int v = 0) { comp[v] = v; dist[v] = 0; used[v] = 1; for(auto [c, u]: to[v]) { if(!used[u]) { dfs(u); } if(to[v].size() == 1 && !term[v]) { comp[v] = comp[u]; dist[v] = dist[u] + 1; } } in_comp[comp[v]].push_back(v); } void solve() { string s; cin >> s; for(auto c: s) { add_letter(c); } for(int p = last; p; p = link[p]) { term[p] = 1; } term[0] = 1; dfs(); int64_t ans = 0; for(int v = 0; v < sz; v++) { if(in_comp[v].size()) { int m = in_comp[v].size(); sort(all(in_comp[v]), [&](int a, int b) { return dist[a] > dist[b]; }); vector<int64_t> A(m), B(m); for(int i = 0; i < m; i++) { int u = in_comp[v][i]; int L = dist[u]; int R = L + len[link[u]]; // L' must be larger than R int cnt = len[u] - len[link[u]]; A[i] = (int64_t)cnt * L; B[i] = cnt; if(i > 0) { A[i] += A[i - 1]; B[i] += B[i - 1]; } auto it = upper_bound(all(in_comp[v]), R, [&](int R, int b) { return R > dist[b]; }) - begin(in_comp[v]); if(it) { it--; ans += A[it] - B[it] * R; } } } } cout << ans << "\n"; }
1818
A
Politics
In a debate club with $n$ members, including yourself (member $1$), there are $k$ opinions to be discussed in sequence. During each discussion, members express their agreement or disagreement with the opinion. Let's define $Y$ as the number of members who agree and $N$ as the number of members who disagree. After each discussion, members leave the club based on the following criteria: - If more members agree than disagree ($Y > N$), all members who disagreed leave the club. - If more members disagree than agree ($Y < N$), all members who agreed leave the club. - If there is a tie ($Y = N$), all members leave the club. As the club president, your goal is to stay in the club and maximize the number of members remaining after the meeting. You have access to each member's stance on all $k$ opinions before the meeting starts, and you can expel any number of members (excluding yourself) before the meeting begins. Determine the maximum number of members, including yourself, who can remain in the club after the meeting. You don't need to provide the specific expulsion strategy but only the maximum number of members that can stay. Ensure that you remain in the club after the meeting as well.
The members that stay in the end must have the same take about each of the discussed opinions (if takes about some opinion differ for two members, at least one of them should have left during the discussion of that opinion). It means that the people that are left must all have the same takes as the president. On the other hand, all such people can stay if you expel everybody else in advance, so the problem just asks you to count the number of people with the same takes on all opinions as the president.
[ "greedy", "implementation" ]
800
void solve() { int n, k; cin >> n >> k; string t[n]; int ans = n; for(int i = 0; i < n; i++) { cin >> t[i]; if(t[i] != t[0]) { ans--; } } cout << ans << "\n"; }
1818
B
Indivisible
You're given a positive integer $n$. Find a permutation $a_1, a_2, \dots, a_n$ such that for any $1 \leq l < r \leq n$, the sum $a_l + a_{l+1} + \dots + a_r$ is not divisible by $r-l+1$. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
If $n > 1$ is odd, there is no solution, as the sum of the whole array $\frac{n(n+1)}{2}$ is always divisible by $n$. Otherwise, the solution is as follows: Start with the identity permutation $1, 2, \dots, n$. Swap the adjacent pairs to get $2, 1, 4, 3, 6, 5, ..., n, n-1$. Indeed, consider the sum of a sub-array $a_l, \dots, a_r$. There are $2$ cases: $l$ and $r$ have different parity: the sum is $\frac{(r-l+1)(l+r)}{2}$ and its greatest common divisor with $r-l+1$ is $\frac{r-l+1}{2}$, as $l+r$ is not divisible by $2$; $l$ and $r$ have the same parity: the sum is $\frac{(r-l+1)(l+r)}{2}+1$ or $\frac{(r-l+1)(l+r)}{2}-1$, depending on the parity. The first summand is divisible by $r-l+1$, as $l+r$ is even. So, the whole sum has the remainder $1$ or $-1$ modulo $r-l+1$, thus it can't be divisible by it.
[ "constructive algorithms" ]
900
void solve() { int n; cin >> n; if(n == 1) { cout << 1 << "\n"; } else if(n % 2) { cout << -1 << "\n"; } else { int a[n]; iota(a, a + n, 1); for(int i = 0; i < n; i += 2) { swap(a[i], a[i + 1]); } for(auto it: a) { cout << it << ' '; } cout << "\n"; } }
1819
A
Constructive Problem
As you know, any problem that does not require the use of complex data structures is considered constructive. You are offered to solve one of such problems. You are given an array $a$ of $n$ non-negative integers. You are allowed to perform the following operation \textbf{exactly once}: choose some non-empty subsegment $a_l, a_{l+1}, \ldots, a_r$ of the array $a$ and a non-negative integer $k$, and assign value $k$ to all elements of the array on the chosen subsegment. The task is to find out whether $\operatorname{MEX}(a)$ can be increased by exactly one by performing such an operation. In other words, if before the operation $\operatorname{MEX}(a) = m$ held, then after the operation it must hold that $\operatorname{MEX}(a) = m + 1$. Recall that $\operatorname{MEX}$ of a set of integers $c_1, c_2, \ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the set $c$.
Let the current value of mex equal to $m$ and the value of mex after performing operation equals to $m'$. It's easy to see that in the resulting array there should exist element equals to $m + 1$ (if it doesn't exist, the value of mex won't be equal to $m + 1$). Also notice that $k$ should be equal to $m$ because this value didn't appear in the array before the operation and must appear there after performing the operation. Consider the following cases. If there exists such $i$ that $a_i = m + 1$, let's find the minimum value $l$ and the maximum value $r$ such that $a_l = a_r = m + 1$. It's easy to see that the performed operation should cover these elements. We already know which value of $k$ to select. Now notice that there are no profits from using longer segments because $m'$ is already not greater than $m + 1$ (there are no elements equal to $m + 1$) and longer segments may make $m'$ less. If there is no such $i$ that $a_i = m$ but there exists $i$ such that $a_i > m + 1$, $m'$ is already not greater than $m + 1$. Similarly with the previous case, we can find any $i$ such that $a_i > m + 1$ and replace $a_i$ with $m$. In all other cases if there exist two indices $i \ne j$ such that $a_i = a_j$, we can replace one of these elements with $m$. In this case we will make $m'$ equals to $m + 1$. If there are no such indices, $m$ equals to the length of the array and we cannot increment $m$. The only thing we have to do after considering cases is to check if the performed operation leads to correct value of $m'$. Time complexity: $\mathcal{O}(n \log n)$.
[ "brute force", "greedy" ]
1,300
// Nikita Golikov, 2023 #include <bits/stdc++.h> using namespace std; using uint = unsigned int; using ll = long long; using ull = unsigned long long; #ifdef GOLIKOV #define debug(x) cerr << (#x) << ":\t" << (x) << endl #else #define debug(x) 238; #endif template <class A, class B> bool smin(A& x, B&& y) { if (y < x) { x = y; return true; } return false; } template <class A, class B> bool smax(A& x, B&& y) { if (x < y) { x = y; return true; } return false; } template <class T> int calcMex(vector<T> v) { sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int n = int(v.size()); for (int i = 0; i < n; ++i) if (v[i] != i) return i; return n; } bool solveTest() { int n; cin >> n; vector<int> a(n); map<int, int> leftOcc, rightOcc; for (int i = 0; i < n; ++i) { cin >> a[i]; rightOcc[a[i]] = i; if (!leftOcc.count(a[i])) leftOcc[a[i]] = i; } int mex = calcMex(a); if (leftOcc.count(mex + 1)) { int L = leftOcc[mex + 1], R = rightOcc[mex + 1]; for (int i = L; i <= R; ++i) { a[i] = mex; } int mx = calcMex(a); assert(mx <= mex + 1); return mx == mex + 1; } for (int i = 0; i < n; ++i) { assert(a[i] != mex); if (a[i] > mex || (leftOcc[a[i]] != rightOcc[a[i]])) { return true; } } return false; } int main() { #ifdef GOLIKOV assert(freopen("in", "rt", stdin)); auto _clock_start = chrono::high_resolution_clock::now(); #endif ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { cout << (solveTest() ? "Yes" : "No") << '\n'; } #ifdef GOLIKOV cerr << "Executed in " << chrono::duration_cast<chrono::milliseconds>( chrono::high_resolution_clock::now() - _clock_start).count() << "ms." << endl; #endif return 0; }
1819
B
The Butcher
Anton plays his favorite game "Defense of The Ancients 2" for his favorite hero — The Butcher. Now he wants to make his own dinner. To do this he will take a rectangle of height $h$ and width $w$, then make a vertical or horizontal cut so that both resulting parts have integer sides. After that, he will put one of the parts in the box and cut the other again, and so on. More formally, a rectangle of size $h \times w$ can be cut into two parts of sizes $x \times w$ and $(h - x) \times w$, where $x$ is an integer from $1$ to $(h - 1)$, or into two parts of sizes $h \times y$ and $h \times (w - y)$, where $y$ is an integer from $1$ to $(w - 1)$. He will repeat this operation $n - 1$ times, and then put the remaining rectangle into the box too. Thus, the box will contain $n$ rectangles, of which $n - 1$ rectangles were put in the box as a result of the cuts, and the $n$-th rectangle is the one that the Butcher has left after all $n - 1$ cuts. Unfortunately, Butcher forgot the numbers $h$ and $w$, but he still has $n$ rectangles mixed in random order. Note that Butcher \textbf{didn't rotate the rectangles}, but only shuffled them. Now he wants to know all possible pairs $(h, w)$ from which this set of rectangles can be obtained. And you have to help him do it! It is guaranteed that there exists at least one pair $(h, w)$ from which this set of rectangles can be obtained.
Note that we know the area of the original rectangle. This value can be calculated as the sum of the areas of the given rectangles. Now let's consider two similar cases: the first cut was horizontal or the first cut was vertical. We will present the solution for the first case, the second one is considered similarly. If the first cut was horizontal, then there exists a rectangle which width is equal to the width of the entire original rectangle. Moreover, it's easy to notice that this is a rectangle with the maximum width. Knowing the width and area, we also know the height of the rectangle we need. The only thing left is to come up with an algorithm that, for given $h$ and $w$, tells us whether it is possible to construct a rectangle with such dimensions. We will perform the following procedure: let us have a rectangle $\{h', w'\}$ for which $h' = h$ or $w' = w$ holds, and cut off our current rectangle with the rectangle $\{h', w'\}$. Formally, if $w' = w$, we will make $h -= h'$, if $h = h'$, we will make $w -= w'$. Note that this greedy algorithm is correct, since at each iteration we performed either a horizontal cut or a vertical cut. Thus, at each iteration of our algorithm, we should have only one option: to remove some rectangle corresponding to a vertical cut or to remove a rectangle corresponding to a horizontal cut. We can choose any of these rectangles. Having performed this algorithm in the case where the first cut was vertical and in the case where the first cut was horizontal, we will check both potential answers. Time complexity: $\mathcal{O}(n \log n)$.
[ "geometry", "greedy", "implementation", "sortings", "two pointers" ]
1,900
//#pragma GCC target("trapv") #include <iostream> #include <vector> #include <algorithm> #include <set> #include <string> #include <cmath> #include <map> #include <iostream> #include <list> #include <stack> #include <cassert> using namespace std; typedef long long ll; typedef long double ld; #define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); const ll INF = 1e9 * 1e9 + 100, SZ = 1100; ll n; vector<pair<ll, ll>> vec; map<ll, pair<ll, ll>> blocks; pair<ll, ll> solve() { set<pair<ll, ll>> widest, longest; for (size_t i = 0; i < vec.size(); i++) { widest.insert({ vec[i].first, i }); longest.insert({ vec[i].second, i }); blocks[i] = vec[i]; } pair<ll, ll> ans = { -1, -1 }; bool mode = 0; ll prevw = INF, prevh = INF, prv = -1; bool cringe = 0; while (widest.size() != 0) { if (mode == 0) { ll cur = (*widest.rbegin()).first, sum = 0; if (ans.second == -1) ans.second = cur; prv = blocks[(*widest.rbegin()).second].second; while (widest.size() > 0 && (*widest.rbegin()).first == cur) { auto it = (--widest.end()); longest.erase({blocks[it->second].second, it->second }); sum += blocks[it->second].second; widest.erase(it); } if (!cringe) ans.first = sum; prv = sum; if (prevw == INF) { prevh = cur; } else { prevw -= sum; if (prevh != cur) return { -1, -1 }; } } else { ll cur = (*longest.rbegin()).first, sum = 0; if (!cringe) { ans.first = cur + prv; cringe = 1; } while (longest.size() > 0 && (*longest.rbegin()).first == cur) { auto it = (--longest.end()); widest.erase({ blocks[it->second].first, it->second }); sum += blocks[it->second].first; longest.erase(it); } if (prevw == INF) { prevw = cur; prevh -= sum; if (prevw != cur) return { -1, -1 }; } else { prevh -= sum; if (prevw != cur) return { -1, -1 }; } } mode ^= 1; } if (prevh == 0 || prevw == 0 || prevh == INF || prevw == INF) { return ans; } else { return { -1, -1 }; } } signed main() { fastInp; ll t; cin >> t; while (t--) { vec.clear(); blocks.clear(); cin >> n; vec.resize(n); for (auto& c : vec) cin >> c.first >> c.second; vector<pair<ll, ll>> ans; ans.push_back(solve()); swap(ans.back().first, ans.back().second); if (ans.back().first == -1) ans.pop_back(); for (auto& c : vec) swap(c.first, c.second); ans.push_back(solve()); if (ans.back().first == -1) ans.pop_back(); if (ans.size() == 2 && ans[0] == ans[1]) { ans.pop_back(); } cout << ans.size() << "\n"; for (auto c : ans) cout << c.first << " " << c.second << "\n"; } return 0; }
1819
C
The Fox and the Complete Tree Traversal
The fox Yae climbed the tree of the Sacred Sakura. A tree is a connected undirected graph that does not contain cycles. The fox uses her magical powers to move around the tree. Yae can jump from vertex $v$ to another vertex $u$ if and only if the distance between these vertices does not exceed $2$. In other words, in one jump Yae can jump from vertex $v$ to vertex $u$ if vertices $v$ and $u$ are connected by an edge, or if there exists such vertex $w$ that vertices $v$ and $w$ are connected by an edge, and also vertices $u$ and $w$ are connected by an edge. After Yae was able to get the sakura petal, she wondered if there was a \textbf{cyclic} route in the tree $v_1, v_2, \ldots, v_n$ such that: - the fox can jump from vertex $v_i$ to vertex $v_{i + 1}$, - the fox can jump from vertex $v_n$ to vertex $v_1$, - all $v_i$ are pairwise distinct. Help the fox determine if the required traversal exists.
Note that if the tree contains the subgraph shown below, then there is no answer. To prove this it is enough to consider all possible cases for how a cyclic route can pass through the upper vertex and understand that it is impossible to construct such route. Let's assume that the tree does not contain the subgraph shown. It is easy to see that in this case, the tree can be represented as a path and vertices directly attached to it. To check that the tree can be represented in this way, we will find the diameter of the tree and check that all other vertices are directly connected to it. Now we need to learn how to build a cyclic route. Number the vertices of the diameter from $1$ to $k$ in the order of traversal of the diameter from one end to the other. Now let's build the route as follows. Firstly, visit vertex $1$, then visit all vertices not on the diameter attached to vertex $2$, then move to vertex $3$, then to all vertices not on the diameter attached to vertex $4$, and so on. When we reach the end of the diameter, we will visit all vertices of the diameter with even numbers, as well as all vertices of the tree not on the diameter attached to the vertices of the diameter with odd numbers. Now let's make the same route in the opposite direction along the diameter, but through vertices of a different parity, which reaches vertex $2$. Time complexity: $\mathcal{O}(n)$.
[ "constructive algorithms", "dp", "implementation", "math", "trees" ]
2,400
// #pragma comment(linker, "/stack:200000000") // #pragma GCC optimize("Ofast,no-stack-protector") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") // #pragma GCC optimize("unroll-loops") #include <stdio.h> #include <bits/stdc++.h> #ifdef PERVEEVM_LOCAL #define debug(x) std::cerr << (#x) << ":\t" << (x) << std::endl #else #define debug(x) 238 #endif #define fastIO std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0) #define NAME "File" using ll = long long; using ld = long double; #ifdef PERVEEVM_LOCAL std::mt19937 rnd(238); #else std::mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count()); #endif template<typename T> bool smin(T& a, const T& b) { if (b < a) { a = b; return true; } return false; } template<typename T> bool smax(T& a, const T& b) { if (a < b) { a = b; return true; } return false; } const double PI = atan2(0.0, -1.0); const int INF = 0x3f3f3f3f; const ll LINF = (ll)2e18; const int N = 200100; std::vector<int> g[N]; int d[N], par[N]; bool onDiameter[N]; void dfs(int v, int p, int depth) { d[v] = depth; par[v] = p; for (auto to : g[v]) { if (to != p) { dfs(to, v, depth + 1); } } } void run() { int n; scanf("%d", &n); for (int i = 0; i < n - 1; ++i) { int from, to; scanf("%d%d", &from, &to); g[from - 1].push_back(to - 1); g[to - 1].push_back(from - 1); } dfs(0, 0, 0); int v1 = 0; for (int i = 0; i < n; ++i) { if (d[i] > d[v1]) { v1 = i; } } dfs(v1, v1, 0); int v2 = v1; for (int i = 0; i < n; ++i) { if (d[i] > d[v2]) { v2 = i; } } std::vector<int> diameter; for (int v = v2; v != v1; v = par[v]) { onDiameter[v] = true; diameter.push_back(v); } onDiameter[v1] = true; diameter.push_back(v1); std::reverse(diameter.begin(), diameter.end()); for (int i = 0; i < n; ++i) { if (onDiameter[i]) { continue; } if (!onDiameter[par[i]]) { printf("No\n"); return; } } printf("Yes\n"); std::vector<int> ans; for (int i = 0; i < (int)diameter.size(); i += 2) { ans.push_back(diameter[i]); if (i + 1 != (int)diameter.size()) { for (auto to : g[diameter[i + 1]]) { if (!onDiameter[to]) { ans.push_back(to); } } } } if (diameter.size() % 2 == 0) { for (int i = (int)diameter.size() - 1; i > 0; i -= 2) { ans.push_back(diameter[i]); if (i - 1 >= 0) { for (auto to : g[diameter[i - 1]]) { if (!onDiameter[to]) { ans.push_back(to); } } } } } else { for (int i = (int)diameter.size() - 1; i > 0; i -= 2) { ans.push_back(diameter[i - 1]); if (i - 2 >= 0) { for (auto to : g[diameter[i - 2]]) { if (!onDiameter[to]) { ans.push_back(to); } } } } } assert((int)ans.size() == n); for (auto i : ans) { printf("%d ", i + 1); } printf("\n"); } int main(void) { // freopen(NAME".in", "r", stdin); // freopen(NAME".out", "w", stdout); #ifdef PERVEEVM_LOCAL auto start = std::chrono::high_resolution_clock::now(); #endif run(); #ifdef PERVEEVM_LOCAL auto end = std::chrono::high_resolution_clock::now(); std::cerr << "Execution time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; #endif return 0; }
1819
D
Misha and Apples
Schoolboy Misha got tired of doing sports programming, so he decided to quit everything and go to the magical forest to sell magic apples. His friend Danya came to the magical forest to visit Misha. What was his surprise when he found out that Misha found a lot of friends there, the same former sports programmers. And all of them, like Misha, have their own shop where they sell magic apples. To support his friends, who have changed their lives so drastically, he decided to buy up their entire assortment. The buying process works as follows: in total there are $n$ stalls, numbered with integers from $1$ to $n$, and $m$ kinds of magic apples, numbered with integers from $1$ to $m$. Each shop sells some number of kinds of apples. Danya visits all the shops in order of increasing number, starting with the first one. Upon entering the shop he buys one magic apple of each kind sold in that shop and puts them in his backpack. However, magical apples wouldn't be magical if they were all right. The point is that when two apples of the same type end up together in the backpack, all of the apples in it magically disappear. Importantly, the disappearance happens after Danya has put the apples in the backpack and left the shop. Upon returning home, Danya realized that somewhere in the forest he had managed to lose his backpack. Unfortunately, for some shops Danya had forgotten what assortment of apples there was. Remembering only for some shops, what kinds of magical apples were sold in them, he wants to know what is the maximum number of apples he could have in his backpack after all his purchases at best.
In this problem, we need to choose which types of apples will be sold in stores with $k_i = 0$. Let's fix some arrangement of apples and consider the last moment in it when the apples disappeared from the backpack. All the apples that we took after this moment will go into the final answer, and if there was also a store with $k_i = 0$ among these stores, then the answer is equal to $m$. Depending on the arrangement of apples, the moments of the last zeroing may change, so let's find all such moments of time after which disappearance may occur, and for all such moments, let's check if we can reach the end without zeroing, and if we can, then what is the maximum number of apples we can collect after that. Formally, let's calculate $\mathrm{canZero}_i$ for all $0 \leq i \leq n$, equal to 1 if there is such an arrangement of apples that after purchases in stores on the segment $[1, i]$, the backpack will be empty, and 0 otherwise, with $\mathrm{canZero}_0 = 1$. Also, let's calculate $\mathrm{maxRemain}_i$ for all $0 \leq i \leq n$, equal to 0 if after passing on the segment $[i + 1, n]$ with an initially empty backpack, we are guaranteed to empty the backpack at least once, otherwise equal to $m$ if there is a store with $k_i = 0$ on this segment, otherwise equal to the total number of apples on this segment, with $\mathrm{maxRemain}_n = 0$. The second array is easily calculated by definition. Let's consider one of the ways to build the first array. We will build it from left to right. If $k_i = 0$, then we can guarantee that the backpack will be empty after this store, so the value of $\mathrm{canZero}_i$ for such $i$ is 1. Otherwise, consider all the apples in this store. After the $i$-th store, the apples will disappear if one of these apples was already in the backpack before. Let's find the maximum such $j < i$ that the store $j$ contains one of the apples in the store $i$, or $k_j = 0$. Now let's find the maximum such $s < j$ that $\mathrm{canZero}_s = 1$. Then we check that there will be no disappearances on the segment $[s + 1, i - 1]$. In this case, $\mathrm{canZero}_i = 1$, otherwise it is equal to 0. Then the answer will be $\max\limits_{\mathrm{canZero}_i = 1} \mathrm{maxRemain}_i$. Time complexity: $\mathcal{O}(n)$.
[ "brute force", "data structures", "dp", "two pointers" ]
2,800
#include <bits/stdc++.h> #include <exception> using namespace std; using ll = long long; void solve() { int n, m; cin >> n >> m; vector<vector<int>> apples(n); for (int i = 0; i < n; ++i) { int k; cin >> k; for (int j = 0; j < k; ++j) { int x; cin >> x; apples[i].push_back(x); } } // vector<int> last(m + 1, -1); unordered_map<int, int> last; auto get_last = [&](int i) { if (!last.count(i)) { return -1; } else { return last[i]; } }; vector<char> can_zero(n + 1, false); vector<int> prev(n + 1, 0); can_zero[0] = true; int oops = -1; for (int i = 0; i < n; ++i) { if (apples[i].empty()) { can_zero[i + 1] = true; last[0] = i; } else { int nearest_pair = get_last(0); int new_oops = oops; for (int x : apples[i]) { nearest_pair = max(nearest_pair, get_last(x)); new_oops = max(new_oops, get_last(x)); last[x] = i; } if (nearest_pair != -1) { int nearest_zero = prev[nearest_pair]; if (oops < nearest_zero) { can_zero[i + 1] = true; } } oops = new_oops; } if (can_zero[i + 1]) { prev[i + 1] = i + 1; } else { prev[i + 1] = prev[i]; } } // vector<char> used(m + 1, false); unordered_set<int> used; vector<int> max_cnt(n + 1, 0); int current_cnt = 0; for (int i = n - 1; i >= 0; --i) { bool fail = false; if (apples[i].empty()) { used.insert(0); } for (int x : apples[i]) { if (used.count(x)) { fail = true; break; } used.insert(x); ++current_cnt; } if (fail) { break; } if (used.count(0)) { max_cnt[i] = m; } else { max_cnt[i] = current_cnt; } } int ans = 0; for (int i = 0; i <= n; ++i) { if (can_zero[i]) { ans = max(ans, max_cnt[i]); } } cout << ans << '\n'; } int main() { cin.tie(nullptr)->sync_with_stdio(false); int t = 1; cin >> t; while (t--) solve(); }
1819
E
Roads in E City
This is an interactive problem. As is well known, the city "E" has never had its roads repaired in its a thousand and a half years old history. And only recently the city administration repaired some of them. It is known that in total in the city "E" there are $n$ intersections and $m$ roads, which can be used in both directions, numbered with integers from $1$ to $m$. The $i$-th road connects intersections with numbers $a_i$ and $b_i$. Among all $m$ roads, some subset of the roads has been repaired, but you do not know which one. The only information you could get from the city's road services is that you can get from any intersection to any other intersection by driving only on the roads that have been repaired. You are a young entrepreneur, and decided to organize a delivery service of fresh raw meat in the city "E" (in this city such meat is called "steaks", it is very popular among the locals). You have already recruited a staff of couriers, but the couriers are willing to travel only on repaired roads. Now you have to find out which roads have already been repaired. The city administration has given you the city for a period of time, so you can make different queries of one of three types: - Block the road with the number $x$. In this case, movement on the road for couriers will be forbidden. \textbf{Initially all roads are unblocked}. - Unblock the road with the number $x$. In this case, couriers will be able to move on the road $x$ if it is repaired. - Try to deliver the order to the intersection with the number $y$. In this case, one of your couriers will start moving from intersection with number $s$ you don't know and deliver the order to intersection with number $y$ if there is a path on unblocked repaired roads from intersection $s$ to intersection $y$. It is guaranteed that intersection $s$ \textbf{will be chosen beforehand}. Unfortunately, the city is placed at your complete disposal for a short period of time, so you can make no more than $100 \cdot m$ requests.
Let's consider city as a graph. We will call an edge good if the road is repaired, and bad if the road is not repaired. Since we know that we can reach any vertex from any other vertex using good edges, we will find the minimum spanning tree of the graph built on good edges. To do this, we will iterate through the edges one by one and check if the graph remains connected by good edges after removing that edge. If the graph remains connected, we will remove the edge. After this actions, only the good edges that form the minimum spanning tree of the graph will remain. Let's find out how to check if the graph remains connected after removing an edge. Suppose we are trying to remove an edge between vertices $A$ and $B$. If the graph remains connected after removing this edge, then the answer to any query will be $1$. Otherwise, the graph will be divided into 2 connected components. Let the starting vertex for the next query be $S$. This vertex will be in one of the two connected components. If we choose a random vertex from $A$ and $B$ as the finishing vertex, there will be no path between the starting and finishing vertices using good edges with probability $1/2$. Therefore, if we make $45$ such queries, then with probability $1/2^{45}$, start and finish will be in same components for all queries. In the remaining cases, there will be no path at least in one query, which will indicate that the graph will no longer be connected by good edges after removing the edge. This way, we can obtain the minimum spanning tree in $m \cdot 47$ queries. After obtaining the minimum spanning tree, we will check if all other edges are good. Let's check the edge between vertices $C$ and $D$. We can find a path between vertices $C$ and $D$ in the minimum spanning tree, remove any edge from it, and then vertices $C$ and $D$ will be in different connected components. After that, we will add the edge $CD$, and using an algorithm similar to the previous one, we will check if the graph is connected by good edges. To do this, we will ask about a random vertex $C$ or $D$ 45 times. This way, we can find all other good edges in $m \cdot 49$ queries.
[ "interactive", "math", "probabilities", "trees" ]
3,200
#include <bits/stdc++.h> #define x first #define y second using namespace std; mt19937 rnd; struct solve { vector<pair<int, int>> r; vector<vector<pair<int, int>>> s; vector<int> ans; int n, m; static constexpr int rep = 45; int dfs(int a, int p, int b) { for (auto i : s[a]) { if (i.x == b) { return i.y; } if (i.x == p) { continue; } int x = dfs(i.x, a, b); if (x != -1) { return x; } } return -1; } solve() { cin >> n >> m; r.resize(m); for (int i = 0; i < m; i++) { cin >> r[i].x >> r[i].y; r[i].x--; r[i].y--; } s.resize(n); ans.resize(m, -1); int cnt = 0; for (int i = 0; i < m; i++) { rem(i); for (int j = 0; j < rep; j++) { if (!ask_end(i)) { ans[i] = 1; break; } } if (ans[i] == 1) { add(i); cnt++; s[r[i].x].emplace_back(r[i].y, i); s[r[i].y].emplace_back(r[i].x, i); } } assert(cnt == n - 1); for (int i = 0; i < m; i++) { if (ans[i] != -1) continue; ans[i] = 1; int c = dfs(r[i].x, -1, r[i].y); rem(c); add(i); for (int j = 0; j < rep; j++) { if (!ask_end(i)) { ans[i] = 0; break; } } rem(i); add(c); } cout << "!"; for (int i = 0; i < m; i++) { cout << ' ' << ans[i]; } cout << endl; int x; cin >> x; if (x != 1) { exit(1); } } void rem(int x) { cout << "- " << x + 1 << endl; } void add(int x) { cout << "+ " << x + 1 << endl; } bool ask(int a) { cout << "? " << a + 1 << endl; // cerr << "? " << a + 1 << endl; int x; cin >> x; return x == 1; } bool ask_end(int i) { // cerr << "ask_end " << i << endl; int a = r[i].x; if (rnd() % 2) { a = r[i].y; } return ask(a); } }; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { solve(); } }
1819
F
Willy-nilly, Crack, Into Release!
You have long dreamed of working in a large IT company and finally got a job there. You have studied all existing modern technologies for a long time and are ready to apply all your knowledge in practice. But then you sit down at your desk and see a sheet of paper with the company's motto printed in large letters: abcdabcdabcdabcd.... The company's motto contains four main principles— a (Willi), b (Nilli), c (Crack), d (Release). Therefore, you consider strings of length $n$ consisting of these four Latin letters. \textbf{Unordered} pairs of letters "ab", "bc", "cd", and "da" in this motto are adjacent, so we will call such pairs of symbols good. So, if you are given a string $s$ of length $n$, and it is known that the unordered pair of symbols $\{ x, y \}$ is good, then you can perform one of the following operations on the string: - if $s_n = x$, then you are allowed to replace this symbol with $y$, - if there exists $1 \le i < n$ such that $s_i = x$ and $s_{i+1} = \ldots = s_n = y$, then you are allowed to replace the $i$-th symbol of the string with $y$, and all subsequent symbols with $x$. For example, the string bacdd can be replaced with one of the strings bacda, bacdc, or badcc, and the string aac can be replaced with aab or aad. A non-empty sequence of operations for the string $s$ will be called correct if the following two conditions are met: - after performing all operations, the string becomes $s$ again, - no string, except for $s$, will occur more than once during the operations. At the same time, the string $s$ can occur exactly twice - before the start of the operations and after performing all operations. Now we are ready to move on to the problem statement! You have a set of strings that is initially empty. Then, each of $q$ queries adds another string $t_i$ to the set, or removes the string $t_i$ from the set. After each query, you need to output the minimum and maximum size of a correct sequence of operations in which each word occurs at least once. The choice of the initial string $s$ is up to you.
There are two ways to approach this problem. Let's start with a solution that does not involve associations with known images. Consider a cyclic sequence of strings that satisfies the condition of the problem. Consider the longest common prefix of all the strings in this sequence. It is not very interesting to us, since by definition it does not change with the operations. There are two cases. Either the sequence of operations has a length of $2$, when we perform some action and then immediately "cancel" it with a second action. This case is only possible if there are no more than two important strings in the set. In this case, the required condition can be easily checked in $\mathcal{O}(n)$ time. Otherwise, our sequence consists of more than two operations and this is much more like a cycle. Let's say, for example, that the first non-constant character in the sequence of strings initially equals "a". Then after the first change it will be equal to either "b" or "d". Note that after this the first character will no longer be able to immediately turn into "a", since the only way to do this is to "cancel" the operation $\ldots acccc\ldots c \to \ldots caaaa\ldots a$, but this is only possible in the first case. Thus, the first character will be required to go "around the cycle" $abcda$. This cycle can be divided into four segments based on the value of the first character of the string. In each of these segments, we are interested in the sequence of operations that transforms the string with the suffix $zx\ldots x$ into a string that matches the original in the prefix, but its suffix is $zy \ldots y$, where $x \neq y \neq z \neq x$ and the pair of characters $\{ x,y \}$ is "good". With the help of a not very complicated analysis of cases, we can see that for each prefix we are interested in $6$ groups of paths that connect strings whose characters, except for the suffix being considered, match, and these paths visit all important strings with the prefix being considered. Within each group of paths, we are interested in the minimum and maximum path, respectively. Note that these values can be easily calculated using dynamic programming. We can calculate all these states in $\mathcal{O}(4^n)$ time. Then we need to iterate over the length of the common prefix of all the strings and answer the query in $\mathcal{O}(n)$ time. So far, we can only calculate the states of interest to us in some galactic time. But this is not entirely scary! Let's say, for example, that when we add or remove one string from the set of important strings, only $\mathcal{O}(n)$ states change, since only the states responsible for the prefixes of the added/deleted string $s$ will change. To some extent, this is reminiscent of a segment tree, or rather, a quadtree. We just need to figure out how to get rid of the $\mathcal{O}(4^n)$ term in the asymptotic complexity. But this is also simple. Let's notice that if there are no strings with the given prefix in the set of important strings, then the states responsible for this prefix will depend only on the length of the remaining suffix, and all these values can be precomputed in $O(n)$ time. Thus, we store a trie with strings from the queries, in each node of which we store the state of the dynamic programming, and in case we need the values of the dynamic programming from non-existent trie nodes during recalculation, we can replace them with precomputed values. Time complexity: $\mathcal{O}(nq)$. The author's code is not very complicated, but if you suddenly want to understand it, I warn you that it uses several "hacks" of questionable justification. For example, instead of $6$ dynamic programming states, only $3$ really useful ones are stored there. The combinatorial structure MinMaxValue is used to simplify the support of simultaneous maximum and minimum values, and much more. I think that it will be especially useful for beginners to familiarize themselves with how to simplify their lives in implementing combinatorial problems. Now let's turn to the geometric interpretation of the problem. Imagine a square with a size of $(2^n-1) \times (2^n-1)$. In its corners, we can draw squares with sizes of $(2^{n-1}-1 \times 2^{n-1}-1)$ each. Let's say that strings starting with the character $a$ go to the upper-left square, strings starting with the character $b$ go to the upper-right, the character $c$ corresponds to the lower-right corner, and the character $d$ corresponds to the lower-left. Then we can divide the four resulting squares into four parts each in the same way and divide the strings by corners already by the second character, and so on. In the end, each string is associated with an integer point with coordinates from the interval $[0, 2^n-1]$. We also have lines from the drawn squares, which are naturally divided into vertical and horizontal segments of length $1$ each. This picture is useful because it depicts a graph whose vertices correspond to the strings being considered, and its edges connect pairs of strings that are obtained from each other by means of one move. Thus, looking at the picture, much of the structure of simple cycles in the problem being considered becomes clear and obvious, and with the help of such a picture it is much easier to describe the transitions in the dynamic programming and not get confused.
[ "data structures", "dp" ]
3,500
#include <bits/stdc++.h> using namespace std; using pi = pair<int, int>; using ll = long long; const int Q = 1e5; const int N = 20; const int V = N*Q; const ll LINF = 1e18; struct MinMaxValue { ll min_value; ll max_value; MinMaxValue operator * (const MinMaxValue& x) const { if (x.max_value < 0 || max_value < 0) { return MinMaxValue { 0, -1 }; } return MinMaxValue { .min_value = x.min_value + min_value, .max_value = x.max_value + max_value }; } MinMaxValue operator + (const MinMaxValue& x) const { if (x.max_value == -1) return *this; if (max_value == -1) return x; return MinMaxValue { .min_value = min(x.min_value, min_value), .max_value = max(x.max_value, max_value) }; } MinMaxValue& operator += (const MinMaxValue& x) { return *this = *this + x; } void Reset() { min_value = 0; max_value = -1; } }; struct { MinMaxValue dig, ver, hor; int cnt; int go[4]; } nd[V]; int vc = 0; MinMaxValue dig[N+1], ver[N+1], hor[N+1]; std::set<ll> words; int NewVertex(int h) { int* go = nd[vc].go; go[0] = go[1] = go[2] = go[3] = -1; nd[vc].dig = dig[h]; nd[vc].hor = hor[h]; nd[vc].ver = ver[h]; nd[vc].cnt = 0; return vc++; } tuple<const MinMaxValue&, const MinMaxValue&, const MinMaxValue&, int> GetState(int v, int h) { return v == -1 ? make_tuple(cref(dig[h]), cref(ver[h]), cref(hor[h]), 0) : make_tuple(cref(nd[v].dig), cref(nd[v].ver), cref(nd[v].hor), nd[v].cnt); } void Calculate(int v, int h, int corner) { auto [dig0, ver0, hor0, cnt0] = GetState(nd[v].go[corner^0], h-1); auto [dig1, ver1, hor1, cnt1] = GetState(nd[v].go[corner^1], h-1); auto [dig2, ver2, hor2, cnt2] = GetState(nd[v].go[corner^2], h-1); auto [dig3, ver3, hor3, cnt3] = GetState(nd[v].go[corner^3], h-1); nd[v].cnt = cnt0 + cnt1 + cnt2 + cnt3; nd[v].dig.Reset(); if (cnt0 == 0) nd[v].dig += hor2 * dig3 * ver1; if (cnt3 == 0) nd[v].dig += ver2 * dig0 * hor1; nd[v].hor = ver0 * dig2 * dig3 * ver1; if (cnt2 + cnt3 == 0) nd[v].hor += hor0 * hor1; nd[v].ver = hor0 * dig1 * dig3 * hor2; if (cnt1 + cnt3 == 0) nd[v].ver += ver0 * ver2; } void UpdateCount(int v, int h, int corner, ll msk, ll msk_save) { if (h == 0) { if (nd[v].cnt == 0) { words.insert(msk_save); } else { words.erase(msk_save); } nd[v].cnt ^= 1; } else { UpdateCount(nd[v].go[msk & 3], h-1, msk & 3, msk >> 2, msk_save); Calculate(v, h, corner); } } bool near_symbols[256][256]; MinMaxValue GetAnswer(int h) { int v = 0; if (nd[v].cnt == 0) { return MinMaxValue { .min_value = 2, .max_value = 4 * dig[h-1].max_value }; } MinMaxValue res; res.Reset(); bool cycle_len2 = false; if (nd[v].cnt <= 1) cycle_len2 = true; if (nd[v].cnt == 2) { string s, t; for (ll msk = *words.begin(); s.size() < h; msk >>= 2) s.push_back("abdc"[msk & 3]); for (ll msk = *next(words.begin()); t.size() < h; msk >>= 2) t.push_back("abdc"[msk & 3]); auto flag = near_symbols[s.back()][t.back()]; if (s.substr(0, h-1) == t.substr(0, h-1) && flag) { cycle_len2 = true; } int s_suf = 0, t_suf = 0; while (s_suf < h && s[h - s_suf - 1] == s.back()) ++s_suf; while (t_suf < h && t[h - t_suf - 1] == t.back()) ++t_suf; if (s_suf == t_suf && s_suf < h && flag && s.substr(0, h-s_suf-1) == t.substr(0, h-t_suf-1) && s.back() == t[h - s_suf - 1] && t.back() == s[h - t_suf - 1]) cycle_len2 = true; } if (cycle_len2) { res.min_value = 2; res.max_value = 2; } while (h != 0) { const int v0 = nd[v].go[0], v1 = nd[v].go[1], v2 = nd[v].go[2], v3 = nd[v].go[3]; const auto& dig0 = get<0>(GetState(v0, h-1)); const auto& dig1 = get<0>(GetState(v1, h-1)); const auto& dig2 = get<0>(GetState(v2, h-1)); const auto& dig3 = get<0>(GetState(v3, h-1)); if(dig0.max_value > 0 && dig1.max_value > 0 && dig2.max_value > 0 && dig3.max_value > 0) { res += dig0 * dig1 * dig2 * dig3; } --h; if (v0 != -1 && nd[v0].cnt == nd[v].cnt) { v = v0; continue; } if (v1 != -1 && nd[v1].cnt == nd[v].cnt) { v = v1; continue; } if (v2 != -1 && nd[v2].cnt == nd[v].cnt) { v = v2; continue; } if (v3 != -1 && nd[v3].cnt == nd[v].cnt) { v = v3; continue; } break; } return res; } int main() { ios::sync_with_stdio(0); cin.tie(0); int n, q; cin >> n >> q; vector<ll> v(q); for (int i = 0; i < 4; ++i) { int j = (i + 1) % 4; near_symbols['a' + i]['a' + j] = true; near_symbols['a' + j]['a' + i] = true; } dig[0] = ver[0] = hor[0] = { 1, 1 }; for (int i = 1; i <= n; ++i) { dig[i] = hor[i-1] * dig[i-1] * ver[i-1]; hor[i] = ver[i] = hor[i-1] * hor[i-1] + ver[i-1] * ver[i-1] * dig[i-1] * dig[i-1]; } int m_root = NewVertex(n); // make_root assert(m_root == 0); for (int i = 0; i < q; ++i) { string s; cin >> s; for (int j = 0; j < n; ++j) { v[i] += (s[j] == 'b' || s[j] == 'c' ? 1ll : 0) << (2*j); v[i] += (s[j] == 'c' || s[j] == 'd' ? 2ll : 0) << (2*j); } int w = 0; for (int j = 0; j < n; ++j) { int& next = nd[w].go[(v[i] >> (2*j)) & 3]; if (next == -1) next = NewVertex(n-j-1); w = next; } } for (ll msk : v) { UpdateCount(0, n, 0, msk, msk); auto [a, b] = GetAnswer(n); if (a > b) { cout << -1 << '\n'; } else { cout << a << " " << b << '\n'; } } }
1820
A
Yura's New Name
After holding one team contest, boy Yura got very tired and wanted to change his life and move to Japan. In honor of such a change, Yura changed his name to something nice. Fascinated by this idea he already thought up a name $s$ consisting only of characters "_" and "^". But there's a problem — Yura likes smiley faces "^_^" and "^^". Therefore any character of the name must be a part of at least one such smiley. Note that only the \textbf{consecutive} characters of the name can be a smiley face. More formally, consider all occurrences of the strings "^_^" and "^^" in the string $s$. Then all such occurrences must cover the whole string $s$, possibly with intersections. For example, in the string "^^__^_^^__^" the characters at positions $3,4,9,10$ and $11$ are not contained inside any smileys, and the other characters at positions $1,2,5,6,7$ and $8$ are contained inside smileys. In one operation Jura can insert one of the characters "_" and "^" into his name $s$ (you can insert it at any position in the string). He asks you to tell him the minimum number of operations you need to do to make the name fit Yura's criteria.
Let's see that if initial name contains "__" as a substring, we have to add character "^" between these two characters because both smiley faces start and end with character "^" and don't contain "__" as a substring. Also let's see that the resulting name have to start and end with character "^" and it's length have to be at least two. To calculate the answer we have to count the number of indices $i$ such that $s_i = s_{i + 1} =$ "_". After that we have to increment the answer if the first character of the name equals to "_" and increment the answer if the last character of the name equals to "_". Also we shouldn't forget about the case when the initials name equals to "^" - in this case the answer equals to one. Time complexity: $\mathcal{O}(\lvert s \rvert)$.
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; if (s == "^") { cout << 1 << '\n'; continue; } int ans = 0; if (s[0] == '_') ++ans; if (s.back() == '_') ++ans; for (int i = 0; i < (int) s.size() - 1; ++i) { if (s[i] == '_' && s[i + 1] == '_') ++ans; } cout << ans << '\n'; } }
1820
B
JoJo's Incredible Adventures
Did you think there was going to be a JoJo legend here? But no, that was me, Dio! Given a binary string $s$ of length $n$, consisting of characters 0 and 1. Let's build a \textbf{square} table of size $n \times n$, consisting of 0 and 1 characters as follows. In the first row of the table write the original string $s$. In the second row of the table write cyclic shift of the string $s$ by one to the right. In the third row of the table, write the cyclic shift of line $s$ by two to the right. And so on. Thus, the row with number $k$ will contain a cyclic shift of string $s$ by $k$ to the right. The rows \textbf{are numbered from $0$ to $n - 1$ top-to-bottom}. In the resulting table we need to find the rectangle consisting only of ones that has the largest area. We call a rectangle the set of all cells $(i, j)$ in the table, such that $x_1 \le i \le x_2$ and $y_1 \le j \le y_2$ for some integers $0 \le x_1 \le x_2 < n$ and $0 \le y_1 \le y_2 < n$. Recall that the cyclic shift of string $s$ by $k$ to the right is the string $s_{n-k+1} \ldots s_n s_1 s_2 \ldots s_{n-k}$. For example, the cyclic shift of the string "01011" by $0$ to the right is the string itself "01011", its cyclic shift by $3$ to the right is the string "01101".
First of all, consider the cases if the given string consists only of ones and only of zeros. It's easy to see that answers for these cases are $n^2$ and $0$. In all other cases let's split all strings into segments that consist only of ones. Also if the first and the last characters of the string equals to "1", these two characters will be in one segment. In other words, the pair of ones will lay inside one group if there exists some cyclic shift that these two ones are consecutive. Let the maximum length of such segment be equal to $k$. Then it can be shown that the answer equals to $\lfloor \frac{k+1}{2} \rfloor \cdot \lceil \frac{k+1}{2} \rceil$. We will proof this fact in such way. If there exists some rectangle of size $a \times b$. Considering its first row, we can see that it has $a+b-1$ consecutive ones. But it means that $a+b \leq k+1$. Without loss of generality, if $a \le b$, we can do the following replacements: $a = \lfloor \frac{k+1}{2} \rfloor - \lambda$, $b = \lceil \frac{k+1}{2} \rceil + \lambda$. It means that $ab = \lceil \frac{k+1}{2} \rceil \cdot \lfloor \frac{k+1}{2} \rfloor - \lambda^2 \le \lceil \frac{k+1}{2} \rceil \cdot \lfloor \frac{k+1}{2} \rfloor$. Time complexity: $\mathcal{O}(n)$.
[ "math", "strings", "two pointers" ]
1,100
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(0); cin.tie(0); int t = 1; cin >> t; while (t--) { string s; cin >> s; s += s; int k = 0, z = 0; for (char c : s) { z = c == '1' ? z+1 : 0; k = max(k, z); } const int n = s.size() / 2; if (k > n) { cout << (ll)n*n << '\n'; } else { const ll side_a = (k+1)/2; const ll side_b = (k+2)/2; cout << side_a * side_b << '\n'; } } }
1821
A
Matching
An integer template is a string consisting of digits and/or question marks. A positive (strictly greater than $0$) integer matches the integer template if it is possible to replace every question mark in the template with a digit in such a way that we get the decimal representation of that integer \textbf{without any leading zeroes}. For example: - $42$ matches 4?; - $1337$ matches ????; - $1337$ matches 1?3?; - $1337$ matches 1337; - $3$ does not match ??; - $8$ does not match ???8; - $1337$ does not match 1?7. You are given an integer template consisting of \textbf{at most $5$ characters}. Calculate the number of positive (strictly greater than $0$) integers that match it.
In a positive integer, the first digit is from $1$ to $9$, and every next digit can be any. This allows us to implement the following combinatorial approach: calculate the number of different values for the first digit, which is $0$ if the first character of $s$ is 0, $1$ if the first character of $s$ is any other digit, or $9$ if the first character of $s$ is ?; calculate the number of different values for each of the other digits, which is $1$ if the corresponding character of $s$ is a digit, or $10$ if it is ?; multiply all these values.
[ "combinatorics", "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { string s; cin >> s; int ans = 1; if(s[0] == '0') ans = 0; if(s[0] == '?') ans = 9; for(int j = 1; j < s.size(); j++) if(s[j] == '?') ans *= 10; cout << ans << endl; } }
1821
B
Sort the Subarray
Monocarp had an array $a$ consisting of $n$ integers. He has decided to choose two integers $l$ and $r$ such that $1 \le l \le r \le n$, and then sort the subarray $a[l..r]$ (the subarray $a[l..r]$ is the part of the array $a$ containing the elements $a_l, a_{l+1}, a_{l+2}, \dots, a_{r-1}, a_r$) in \textbf{non-descending order}. After sorting the subarray, Monocarp has obtained a new array, which we denote as $a'$. For example, if $a = [6, 7, 3, 4, 4, 6, 5]$, and Monocarp has chosen $l = 2, r = 5$, then $a' = [6, 3, 4, 4, 7, 6, 5]$. You are given the arrays $a$ and $a'$. Find the integers $l$ and $r$ that Monocarp could have chosen. If there are multiple pairs of values $(l, r)$, find the one which \textbf{corresponds to the longest subarray}.
Let's find the leftmost and the rightmost position in which the arrays $a$ and $a'$ differ. Since only the elements in the chosen subsegment might change, the subarray we sorted should contain these two positions. Let's start with the subarray from the leftmost "different" position to the rightmost one, and then expand it to get the longest subarray which meets the conditions. Suppose we want to expand it to the left. Let the current left border be $L$; how to decide if we can make it $L-1$ or less? If $a'_L < a_{L-1}$, then we cannot include $L-1$ in the subarray we sort, since otherwise the order of these two elements would have changed. Otherwise, $a_{L-1}$ is not greater than any element in the subarray we have chosen, so we can include it and reduce $L$ by $1$. We do this until it's impossible to reduce $L$ further. The same goes for the right border: we expand it to the right until we find an element which is less than the previous element, and we cannot include this element in the subarray.
[ "brute force", "greedy" ]
1,100
#include<bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { int n; scanf("%d", &n); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); vector<int> a1(n); for(int i = 0; i < n; i++) scanf("%d", &a1[i]); int diffl = -1, diffr = -1; for(int j = 0; j < n; j++) { if(a[j] != a1[j]) { diffr = j; if(diffl == -1) diffl = j; } } while(diffl > 0 && a1[diffl - 1] <= a1[diffl]) diffl--; while(diffr < n - 1 && a1[diffr + 1] >= a1[diffr]) diffr++; printf("%d %d\n", diffl + 1, diffr + 1); } }
1821
C
Tear It Apart
You are given a string $s$, consisting of lowercase Latin letters. In one operation, you can select several (one or more) positions in it such that no two selected positions are adjacent to each other. Then you remove the letters on the selected positions from the string. The resulting parts are concatenated without changing their order. What is the smallest number of operations required to make all the letters in $s$ the same?
The resulting string looks like a single letter repeated a number of times. That sounds too vague. Let's fix the exact letter $c$ that will be left. Since the size of the alphabet is only $26$, we can afford that. The letters now separate into letters $c$ and other letters. And all other letters can be treated as indistinguishable from each other. Let's make letter $c$ into a binary $1$ and any other letter into a binary $0$. Our goal is to remove all zeros from the string with the given operations. First, notice that it doesn't help you to removes ones. If some operation contains both ones and zeros, then taking ones out of it doesn't make any zeros in it adjacent. At the same time, these ones can only help you separate adjacent zeros later. Thus, we have some blocks of zeros, separated by the blocks of ones. We want to remove only zeros. Notice how these blocks can be solved completely independently of each other. If you solve block $1$ in $\mathit{cnt}_1$ operations, block $2$ in $\mathit{cnt}_2$ operations, ..., block $k$ in $\mathit{cnt}_k$ operations, then you can solve the entire string in $\max(\mathit{cnt}_1, \mathit{cnt}_2, \dots, \mathit{cnt}_k)$ operations. Since the blocks are separated by the blocks of ones, you can combine the first operations for all blocks into one big operation and so on. The only thing left is to calculate the number of operations for a single block. Let it have length $l$. Basically, in one operation, you can decrease its length to $\lfloor \frac l 2 \rfloor$. You can see that the longer the block, the greater answer it has. So you can find the longest block first, then calculate the answer for it. You can either use this iterative formula or notice that it's a logarithm of $l$ in base $2$ and calculate that however you want. To find the lengths of the blocks of zeros, you can use two pointers. Overall complexity: $O(|\mathit{AL}| \cdot n)$ per testcase. This problem can also be solved in $O(n \log n)$ on an arbitrarily large alphabet. Basically, when you fix a letter, you can tell the lengths of the blocks of other letters by looking at the occurrences of the letter. For occurrences $i_1, i_2, \dots, i_k$, the lengths of the blocks are $i_1 - 1, i_2 - i_1, \dots, i_k - i_{k-1}, n - i_{k}$. So we can calculate the answer for a letter in $O(\mathit{number\ of\ its\ occurrences})$. The total of that for all letters is $O(n)$.
[ "brute force", "implementation", "math", "strings" ]
1,300
for _ in range(int(input())): s = input() n = len(s) ans = n for x in range(26): c = chr(x + ord('a')) i = 0 cur = 0 while i < n: j = i while j < n and (s[j] == c) == (s[i] == c): j += 1 if s[i] != c: cur = max(cur, j - i) i = j if cur == 0: ans = 0 break pw = 0 while (1 << pw) <= cur: pw += 1 ans = min(ans, pw) print(ans)
1821
D
Black Cells
You are playing with a really long strip consisting of $10^{18}$ white cells, numbered from left to right as $0$, $1$, $2$ and so on. You are controlling a special pointer that is initially in cell $0$. Also, you have a "Shift" button you can press and hold. In one move, you can do one of three actions: - move the pointer to the right (from cell $x$ to cell $x + 1$); - press and hold the "Shift" button; - release the "Shift" button: the moment you release "Shift", all cells that were visited while "Shift" was pressed are colored in black. (Of course, you can't press Shift if you already hold it. Similarly, you can't release Shift if you haven't pressed it.)Your goal is to color at least $k$ cells, but there is a restriction: you are given $n$ segments $[l_i, r_i]$ — you can color cells only inside these segments, i. e. you can color the cell $x$ if and only if $l_i \le x \le r_i$ for some $i$. What is the minimum number of moves you need to make in order to color at least $k$ cells black?
Let's look at what's happening in the task: in the end the pointer will move into some position $p$ and some segments on the prefix $[0, p]$ will be colored. Note that it's optimal to stop only inside some segment (or $l_i \le p \le r_i$ for some $i$), and if we colored $x$ segments (including the last segment $[l_i, p]$ that may be colored partially) the answer will be equal to $p + 2 \cdot x$. Let's prove that it's not optimal to skip segments with length $len = r[i] - l[i] + 1 \ge 2$. By contradiction, suppose the optimal answer $a$ has a skipped segment $[l_i, r_i]$. If we color that segment instead, we will make $2$ more moves for pressing and releasing Shift, but we can make at least $len$ right move less. So the new answer $a' = a + 2 - len \le a$ - the contradiction. Now we are ready to write a solution. Let's iterate over $i$ - the last segment we will color (and therefore the segment where we stop). At first, let's imagine we colored the whole segment $[l_i, r_i]$ as well. Let $s$ be the total length of all segments on prefix $[0, r_i]$ that are longer than $1$ and $c$ be the number of segments of length $1$ on this prefix. There are three cases: if $s + c < k$, stopping inside the $i$-th segment is not enough; if $s < k$ but $s + c \ge k$, we will color all "long" segments plus several short ones. The current answer will be equal to $r_i + 2 ((i - c) + (k - s))$, where $r_i$ is where we stop, $(i - c)$ is the number of long segments and $(k - s)$ is the number of short segments we need; if $s \ge k$, then we don't need any short segments. More over, we can stop even before reaching $r_i$. So, the current answer will be equal to $r_i - (s - k) + 2 (i - c)$, where $r_i - (s - k)$ is the exact position to stop to get exactly $k$ black cells and $(i - c)$ is the number of long segments. The answer is the minimum among the answers we've got in the process. Since it's easy to update values $s$ and $c$ when we move from $i$ to $i + 1$, the total complexity is $O(n)$.
[ "binary search", "brute force", "greedy", "math" ]
1,900
fun main() { repeat(readln().toInt()) { val (n, k) = readln().split(' ').map { it.toInt() } val l = readln().split(' ').map { it.toInt() } val r = readln().split(' ').map { it.toInt() } var ans = 2e9.toInt() var cntShort = 0 var lenLong = 0 for (i in 0 until n) { val curLen = r[i] - l[i] + 1 if(curLen > 1) lenLong += curLen else cntShort++ if (lenLong < k) { if (lenLong + cntShort >= k) { val cntSegs = (i + 1 - cntShort) + (k - lenLong) ans = minOf(ans, r[i] + 2 * cntSegs) } } else { ans = minOf(ans, r[i] - (lenLong - k) + 2 * (i + 1 - cntShort)) break } } if (ans == 2e9.toInt()) ans = -1 println(ans) } }
1821
E
Rearrange Brackets
A regular 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 "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); - bracket sequences ")(", "(" and ")" are not. You are given a regular bracket sequence. In one move, you can remove a pair of \textbf{adjacent} brackets such that the left one is an opening bracket and the right one is a closing bracket. Then concatenate the resulting parts without changing the order. The cost of this move is the number of brackets to the right of the right bracket of this pair. The cost of the regular bracket sequence is the smallest total cost of the moves required to make the sequence empty. Actually, you are not removing any brackets. Instead, you are given a regular bracket sequence and an integer $k$. You can perform the following operation \textbf{at most $k$ times}: - extract some bracket from the sequence and insert it back at any position (between any two brackets, at the start or at the end; possibly, at the same place it was before). After all operations are performed, the bracket sequence has to be regular. What is the smallest possible cost of the resulting regular bracket sequence?
First, let's define the cost of an RBS a bit clearer. The absolute smallest cost of removing each pair of brackets is the number of bracket pairs it's inside of. That can actually be achieved - just remove the pairs right to left (according to the positions of the opening brackets in pairs). So you can instead say that the total cost is the sum of balance values after all closing brackets. Or before all opening brackets - these are actually the same. From that, we can code a classic dp. Imagine we are not moving brackets, but instead doing that in two separate movements: put a bracket in some buffer and place it in the string. We'd love to use $\mathit{dp}[\mathit{pos}][\mathit{open}][\mathit{close}][\mathit{moves}]$ - the smallest answer if we processed $\mathit{pos}$ brackets, $\mathit{open}$ opening brackets are in the buffer, $\mathit{close}$ closing brackets in the buffer and $\mathit{moves}$ are performed. Sadly, that doesn't really allow moving brackets to the left, since you would have to first place the bracket, then put in it the buffer. Does that actually break anything? Apparently, no. You can make these buffer states from $-k$ to $k$, and think of negative values as taking a loan. These states are enough to determine the current balance of the string. Thus, enough to both update the states and check if the string stops being an RBS after placing a closing bracket. Overall complexity: $O(nk^3)$. We can do it faster, but our proof isn't that convincing. Start by showing that there exists an optimal answer such that each move leaves the sequence an RBS. Consider a sequence of moves that ends up being an RBS. First, you can basically rearrange the moves (maybe adjusting the exact positions is required). Second, there exists a move that, performed first, leaves an RBS. Make it and propagate the proof. You can show that such a move exists by studying some cases. Then I found it more intuitive to switch to another representation - you can look at the forest induced by the bracket sequence. The roots of the trees in it are the topmost opening and closing brackets of the RBS. Their children are the inner topmost brackets for each of them, and so on. With that representation, the answer is actually the sum of depths of all vertices. Now for the moves. Let's move an opening bracket to the right. We won't move it after its corresponding closing bracket to not break an RBS. How will it change the tree? It will turn some children of the corresponding vertex into the children of its parent. Thus, it will decrease their depths by one, and the depths of their descendants as well. How about to the left? That will turn some children of its parent into its own children, increasing their depths (and the depths of their descendants) by one. Similar analysis can be performed for the closing brackets. The claim is that, in the optimal answer, you should only move opening brackets and only to the right. Then they decrease the answer independently of each other. It's pretty clear that the best position to move each bracket to is as much to the right as possible - place it next to its respective closing bracket. That will decrease the answer by the size of the subtree (excluding the vertex itself). Finally, we want to choose $k$ vertices that have the largest sum of their subtrees. That can be just done greedily - pick $k$ largest ones. You don't have to build the tree explicitly for that - the size of the subtree is half of the number of brackets between an opening bracket and a corresponding closing one. So, everything can be processed with a stack. Overall complexity: $O(n)$ or $O(n \log n)$.
[ "brute force", "dp", "greedy", "sortings", "strings" ]
2,100
for _ in range(int(input())): k = int(input()) s = input() n = len(s) st = [] cnt = [0 for i in range(n + 1)] ans = 0 for i in range(n): if s[i] == '(': ans += len(st) st.append(i) else: cnt[(i - st.pop()) // 2] += 1 for i in range(n, -1, -1): t = min(k, cnt[i]) ans -= t * i k -= t print(ans)
1821
F
Timber
There is a beautiful alley with trees in front of a shopping mall. Unfortunately, it has to go to make space for the parking lot. The trees on the alley all grow in a single line. There are $n$ spots for trees, index $0$ is the shopping mall, index $n+1$ is the road and indices from $1$ to $n$ are the spots for trees. Some of them are taken — there grow trees of the same height $k$. No more than one tree grows in each spot. When you chop down a tree in the spot $x$, you can make it fall either left or right. If it falls to the left, it takes up spots from $x-k$ to $x$, inclusive. If it falls to the right, it takes up spots from $x$ to $x+k$, inclusive. Let $m$ trees on the alley grow in some spots $x_1, x_2, \dots, x_m$. Let an alley be called unfortunate if all $m$ trees can be chopped down in such a way that: - no tree falls on the shopping mall or the road; - each spot is taken up by no more than one fallen tree. Calculate the number of different unfortunate alleys with $m$ trees of height $k$. Two alleys are considered different if there is a spot $y$ such that a tree grows in $y$ on the first alley and doesn't grow in $y$ on the second alley. Output the number modulo $998\,244\,353$.
People say that this problem can be bashed with generating functions. Sadly, I know nothing about them, so I'll explain the more adhoc solution I managed to come up. Let's investigate the general form of some placement of trees. Imagine we fixed some position $x_1, x_2, \dots, x_m$ for them. How to check if it's possible to cut them all down? Well, it's a simple greedy problem. Process trees left to right. If a tree can fall down to the left, make it fall to the left. Otherwise, if it can fall down to the right, make it fall to the right. Otherwise, no answer. Try a harder problem. Consider the spots the fallen trees take. How many constructions can these spots be induced by after the greedy algorithm is performed? First, these taken spots are actually segments of length $k+1$. Each tree can fall either from the left or the right side of the segment. To determine the answer, one has to look at the number of free spots to the left of each fallen tree. If there're at least $k$ free spots, then the tree can only fall from the left side of that segment. Otherwise, it can fall both ways. Thus, for $x$ trees that have less than $k$ free spots to the left of them, the answer is $2^x$. We can't really iterate over the constructions, so let's try yet another related problem. Would be cool if we could fix the exact number of trees that have more than $k$ free cells to the left of them. I don't really know how to do that. But I know how to fix at least the amount. Let that be at least $x$ trees. For $x$ trees, make their segments of length $2k+1$ - $k+1$ for the tree itself and $k$ extra cells to the left of it. For the rest $m-x$ trees, make their segments of length $k+1$. Then we have to place them on the given $n$ spots. The path is as follows. Rearrange the long and the short segments among each other - $\binom{m}{x}$. Then use stars and bars to choose the amount of space between the segments - $\binom{n-x\cdot(2k+1)-(m-x)\cdot(k+1)+m}{m}$. Finally, multiply by $2^{m-x}$ to fix the side for the short segments. Initially, we thought that we could just use PIE to calculate the exact answer from that - $\sum\limits_{x=0}^m f(x) \cdot (-1)^x$. And the results of this formula coincided with the naive solution, so we thought that everything should be fine. But unfortunately, even though the formula is right, using PIE in the described way is incorrect. Let us show you the correct way. Let $F(x)$ be the number of ways to choose the segments for the trees in such a way that $x$ fixed segments are "long" (i. e. at least of length $2k+1$). To calculate $F(x)$, we use the familiar stars and bars concept: $\binom{n-x\cdot(2k+1)-(m-x)\cdot(k+1)+m}{m}$ (we already had this formula earlier). Now, let $G(x)$ be the number of ways to choose the segments for the trees in such a way that $x$ fixed segments are "long", and all other segments are "short". The formula for $G(x)$ is a straightforward application of PIE: $G(x) = \sum\limits_{y=0}^{m-x} (-1)^y \binom{m-x}{y} F(x+y)$, where we iterate on $y$ - the number of segments that should be short, but are definitely long. The answer to the problem can be calculated as $\sum\limits_{x=0}^{m} 2^{m-x} \binom{m}{x} G(x)$ - we choose which $x$ segments are "long", and all others should be "short". Expanding $G(x)$ gives us the following formula: $\sum\limits_{x=0}^m \sum\limits_{y=0}^{m-x} (-1)^y 2^{m-x} \binom{m}{x} \binom{m-x}{y} F(x+y)$ which, after expanding binomial coefficients into factorials and getting rid of $(m-x)!$, becomes $\sum\limits_{x=0}^m \sum\limits_{y=0}^{m-x} (-1)^y 2^{m-x} \frac{m!}{x! y! (m-x-y)!} F(x+y)$ We introduce the substitution variable $z = x + y$, and the formula becomes $\sum\limits_{z=0}^m \sum\limits_{y=0}^{z} (-1)^y 2^{m-z+y} \frac{m!}{(z-y)! y! (m-z)!} F(z)$ By multiplying both the numerator and the denominator by $z!$, we then get $\sum\limits_{z=0}^m \sum\limits_{y=0}^{z} (-1)^y 2^{m-z+y} \binom{m}{z} \binom{z}{y} F(z)$ $\sum\limits_{z=0}^m \binom{m}{z} 2^{m-z} F(z) \sum\limits_{y=0}^{z} (-2)^y \binom{z}{y} F(z)$ And $\sum\limits_{y=0}^{z} (-2)^y \binom{z}{y}$ is just $(1-2)^z$. Thus, the answer is equal to $\sum\limits_{z=0}^m (-1)^z \binom{m}{z} 2^{m-z} F(z)$. Overall complexity: $O(n)$.
[ "combinatorics", "dp", "fft", "math" ]
2,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } int binpow(int a, int b){ int res = 1; while (b){ if (b & 1) res = mul(res, a); a = mul(a, a); b >>= 1; } return res; } int main(){ int n, m, k; scanf("%d%d%d", &n, &m, &k); vector<int> fact(2 * n + 1), rfact(2 * n + 1); fact[0] = 1; for (int i = 1; i <= 2 * n; ++i) fact[i] = mul(fact[i - 1], i); rfact[2 * n] = binpow(fact[2 * n], MOD - 2); for (int i = 2 * n - 1; i >= 0; --i) rfact[i] = mul(rfact[i + 1], i + 1); auto cnk = [&](int n, int k){ if (k < 0 || n < 0 || k > n) return 0; return mul(fact[n], mul(rfact[k], rfact[n - k])); }; auto snb = [&](int n, int k){ return cnk(n + k, k); }; int pw2 = 1; int ans = 0; for (int i = m; i >= 0; --i){ int cur = 0; if (n - (m - i) * 1ll * (k + 1) - i * 1ll * (2 * k + 1) >= 0) cur = mul(snb(n - (m - i) * (k + 1) - i * (2 * k + 1), m), mul(pw2, cnk(m, i))); ans = add(ans, i & 1 ? -cur : cur); pw2 = mul(pw2, 2); } printf("%d\n", ans); }
1822
A
TubeTube Feed
Mushroom Filippov cooked himself a meal and while having his lunch, he decided to watch a video on TubeTube. He can not spend more than $t$ seconds for lunch, so he asks you for help with the selection of video. The TubeTube feed is a list of $n$ videos, indexed from $1$ to $n$. The $i$-th video lasts $a_i$ seconds and has an entertainment value $b_i$. Initially, the feed is opened on the first video, and Mushroom can skip to the next video in $1$ second (if the next video exists). Mushroom can skip videos any number of times (including zero). Help Mushroom choose \textbf{one} video that he can open and watch in $t$ seconds. If there are several of them, he wants to choose the most entertaining one. Print the index of any appropriate video, or $-1$ if there is no such.
This problem can be solved by going through all the options of the video that the Mushroom will choose to watch. Let the Mushroom choose the $i$-th video. He can view it if $a[i] + i - 1$ does not exceed $t$. Since he will have to spend $i - 1$ a second scrolling the TubeTube feed and $a[i]$ watching the video. As an answer, it is enough to choose a video with the maximum entertainment value from the appropriate ones.
[ "brute force", "implementation" ]
800
def solve(): n, t = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] bst = -2 for i in range(n): if i + a[i] <= t and (bst == -2 or b[bst] < b[i]): bst = i print(bst + 1) t = int(input()) for _ in range(t): solve()
1822
B
Karina and Array
Karina has an array of $n$ integers $a_1, a_2, a_3, \dots, a_n$. She loves multiplying numbers, so she decided that the beauty of a pair of numbers is their product. And the beauty of an array is the maximum beauty of a pair of \textbf{adjacent} elements in the array. For example, for $n = 4$, $a=[3, 5, 7, 4]$, the beauty of the array is $\max$($3 \cdot 5$, $5 \cdot 7$, $7 \cdot 4$) = $\max$($15$, $35$, $28$) = $35$. Karina wants her array to be as beautiful as possible. In order to achieve her goal, she can remove some elements (possibly zero) from the array. After Karina removes all elements she wants to, the array must contain at least two elements. Unfortunately, Karina doesn't have enough time to do all her tasks, so she asks you to calculate the maximum beauty of the array that she can get by removing any number of elements (possibly zero).
In the problem, we are not required to minimize the number of deletions, so we will search for the answer greedily. First, let's find two numbers in the array whose product is maximal. Note that the product of this pair of numbers will be the answer, since we can remove all elements from the array except this pair, then they will become neighboring. It is easy to see that the product of a pair of positive numbers is maximal when both numbers in the pair are maximal. So we need to consider the product of the two largest numbers. But it's worth remembering that the product of two negative numbers is positive, so the product of the two smallest numbers is also worth considering. The answer to the problem will be the maximum of these two products. To find the two largest and two smallest numbers, you can simply sort the array. The final asymptotics of the solution will be $O(n\log n)$.
[ "greedy", "math", "sortings" ]
800
t = int(input()) for testCase in range(t): n = int(input()) a = list(map(int, input().split(' '))) a.sort() print(max(a[0] * a[1], a[-1] * a[-2]))
1822
C
Bun Lover
Tema loves cinnabon rolls — buns with cinnabon and chocolate in the shape of a "snail". Cinnabon rolls come in different sizes and are square when viewed from above. The most delicious part of a roll is the chocolate, which is poured in a thin layer over the cinnabon roll in the form of a spiral and around the bun, as in the following picture: \begin{center} {\small Cinnabon rolls of sizes 4, 5, 6} \end{center} For a cinnabon roll of size $n$, the length of the outer side of the square is $n$, and the length of the shortest vertical chocolate segment in the central part is one. Formally, the bun consists of two dough spirals separated by chocolate. A cinnabon roll of size $n + 1$ is obtained from a cinnabon roll of size $n$ by wrapping each of the dough spirals around the cinnabon roll for another layer. \textbf{It is important that a cinnabon roll of size $n$ is defined in a unique way.} Tema is interested in how much chocolate is in his cinnabon roll of size $n$. Since Tema has long stopped buying small cinnabon rolls, it is guaranteed that $n \ge 4$. Answer this non-obvious question by calculating the total length of the chocolate layer.
Let's separate the complex chocolate layer into three simple parts. Now it is not difficult to calculate the total length of the three parts. The length of the light-yellow segment $1$. Length of the cyan polyline $1 + 2 + \dots + n = \dfrac{n \cdot (n + 1)}{2}$. Length of the lilac polyline $1 + 2 + \dots + (n + 1) = \frac{(n + 1) \cdot (n + 2)}{2}$. Total length of chocolate $\dfrac{(n + 1) \cdot (n + 2)}{2} + \dfrac{n \cdot (n + 1)}{2} + 1 = \dfrac{(n + 1) \cdot (n + 2) + n \cdot (n + 1)}{2} + 1 = \dfrac{2 \cdot (n + 1)^2}{2} + 1 = (n + 1)^2 + 1$
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int q; cin >> q; while (q--) { int n; cin >> n; cout << ((n + 1) * n) + n + 2 << "\n"; } return 0; }