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
1290
D
Coffee Varieties (hard version)
This is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee. \textbf{This is an interactive problem.} You're considering moving to another city, where one of your friends already lives. There are $n$ cafés in this city, where $n$ is a power of two. The $i$-th café produces a single variety of coffee $a_i$. As you're a coffee-lover, before deciding to move or not, \textbf{you want to know the number $d$ of distinct varieties of coffees} produced in this city. You don't know the values $a_1, \ldots, a_n$. Fortunately, your friend has a memory of size $k$, where $k$ is a power of two. Once per day, you can ask him to taste a cup of coffee produced by the café $c$, and he will tell you if he tasted a similar coffee during the last $k$ days. You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most $30\ 000$ times. More formally, the memory of your friend is a queue $S$. Doing a query on café $c$ will: - Tell you if $a_c$ is in $S$; - Add $a_c$ at the back of $S$; - If $|S| > k$, pop the front element of $S$. Doing a reset request will pop all elements out of $S$. Your friend can taste at most $\dfrac{3n^2}{2k}$ cups of coffee in total. Find the diversity $d$ (number of distinct values in the array $a$). Note that asking your friend to reset his memory \textbf{does not count} towards the number of times you ask your friend to taste a cup of coffee. In some test cases the behavior of the interactor \textbf{is adaptive}. It means that the array $a$ may be \textbf{not fixed} before the start of the interaction and may \textbf{depend on your queries}. It is guaranteed that at any moment of the interaction, there is at least one array $a$ consistent with all the answers given so far.
Easy version (constant 2) Let's try to maintain representative positions for each value. In the beginning, when we know nothing, every position can be a potential representative. We will call them alive positions, and using queries, we will try to kill some positions and ending up with exactly one alive position per value. The answer will be the number of alive positions. Note that when we kill a position, there must be another alive position with the same value. The danger here is to compare a position to a dead position of the same value: we may end up killing the single representative of the value. Create blocks of size $\frac{k}{2}$, (or $1$ if $k = 1$). Query $1, 2, \ldots, n$ and kill the element if you get Yes answer. Each value has at least one alive occurrence, its leftmost one. Moreover, all equalities inside blocks are removed. In order to remove equalities between blocks, compare all unordered pairs of blocks (for each pair, reset the memory, look all elements in the first one, then all elements in the second one, and kill elements in the second one for each Yes answer). Note that we don't need to compare adjacent blocks. The number of queries is a bit less than $\frac{2n^2}{k}$. Hard version (constant 1.5) Querying $1, 2, \ldots, n$ allowed us to compare pairs $(i, i+1)$ in a very efficient manner because we reuse the memory of the previous comparison. Let's try to generalize this. Consider a complete graph where nodes are blocks. Comparing pairs of blocks can be seen as covering edges of the graph. We can take any elementary path (that doesn't pass through a node twice), reset the memory and explore blocks in the corresponding order (killing elements for each Yes answer). Each path will require $(\text{number of edges} + 1) \cdot \frac{k}{2}$ queries. It's optimal to have disjoint paths (if a path goes through an already visited edge, we can split it there). Hence, we want to use a few disjoint paths to cover all edges. A randomized DFS works experimentally well (constant around $1.2$). However, we can acheive constant $1$ using the following zig-zag pattern: $s \rightarrow s-1 \rightarrow s+1 \rightarrow s-2 \rightarrow s+2 \rightarrow \ldots$.
[ "constructive algorithms", "graphs", "interactive" ]
3,000
#include <bits/stdc++.h> using namespace std; bool ask(int pos) { cout << "? " << pos+1 << endl << flush; char c; cin >> c; if (c == 'E') exit(0); return (c == 'Y'); } int main() { int nbElem, memSize, nbBlocks; cin >> nbElem >> memSize; nbBlocks = nbElem / memSize; vector<bool> isAlive(nbElem, true); for (int startBlock = 0; startBlock < nbBlocks; ++startBlock) { int delta = 0; cout << "R" << endl << flush; for (int iDo = 0; iDo < nbBlocks; ++iDo) { int curBlock = (startBlock+delta+nbBlocks) % nbBlocks; int st = curBlock*memSize; for (int elem = st; elem < st+memSize; ++elem) { if (isAlive[elem]) { if (ask(elem)) isAlive[elem] = false; } } if (delta >= 0) ++delta; delta = -delta; } } int nbAlive = count(isAlive.begin(), isAlive.end(), true); cout << "! " << nbAlive << endl << flush; }
1290
E
Cartesian Tree
Ildar is the algorithm teacher of William and Harris. Today, Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William. A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: - If the sequence is empty, return an empty tree; - Let the position of the \textbf{maximum} element be $x$; - Remove element on the position $x$ from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); - Build cartesian tree for each part; - Create a new vertex for the element, that was on the position $x$ which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; - Return the tree we have gotten. For example, this is the cartesian tree for the sequence $4, 2, 7, 3, 5, 6, 1$: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence $a$. In the $i$-th round, he inserts an element with value $i$ somewhere in $a$. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence $a$? Node $v$ is in the node $u$ subtree if and only if $v = u$ or $v$ is in the subtree of one of the vertex $u$ children. The size of the subtree of node $u$ is the number of nodes $v$ such that $v$ is in the subtree of $u$. Ildar will do $n$ rounds in total. The homework is the sequence of answers to the $n$ questions. The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence $a$ from William. However, he has no idea how to find the answers to the $n$ questions. Help Harris!
Instead of inserting numbers one by one, let's imagine I have $n$ blanks in a row, and I will fill the blanks with integers from $[1,n]$ in order, and I want to know about the cartesian tree after each blank filled. In the following parts of the solution, I will use positions in the original array instead of positions in the contracted array to label things. In the process of building a cartesian tree, a node is created for each recursive call of building a tree for a subarray $[l,r]$. Let's label the node created at that moment to be $(l,r)$. We realize that $r-l+1$ will be the size of the subtree of that node. However, in our problem, some positions can be blanks, so the actual subtree size of a node $(l,r)$ is the number of positions that are not blanks in the subarray $[l,r]$. So now we are finding the sum of the number of non-blanks in the range for each node $(l,r)$ in our cartesian tree. Let $pf(r)$ be the number of non-blanks in the first $r$ positions of the sequence. Then we are finding sum of $pf(r)-pf(l-1)$ for each node $(l,r)$. To proceed, observe a property for a cartesian tree. Let's define for each integer $p$, let $maxr(p)$ to be the largest $r$ such that $(p,r)$ is a node, or just null if there is no nodes of the form $(p,r)$. Similarly, define $minl(p)$ to be the smallest $l$ such that $(l,p)$ is a node. Then, for each node $(l,r)$, exactly one of the following is true: $maxr(l)=r$. $minl(r)=l$. Except when $(l,r)$ is the root. If we know: sum of $pf(maxr(l))$ over all $maxr(l)$ that is not null. sum of $pf(l-1)$ over all $maxr(l)$ that is not null. sum of $pf(r)$ over all $minl(r)$that is not null. sum of $pf(minl(r)-1)$ over all $minl(r)$ that is not null. Then we can find out the answer. As it is more or less symmetric I will only care about part (1) and (2) from now on. Let's find out what would happen to nodes of our tree if we fill $i+1$ into position $x$, replacing a blank. Let's omit how the nodes connect each other and just track the labels of each node. For convenience, we will make the following definitions. Call $prv$ the nearest non-blank position on the left side of $x$. Call $nxt$ the nearest non-blank position on the right side of $x$. Call $head$ the leftmost non-blank position. Call $tail$ the rightmost non-blank position. Firstly, every node that is of the form $(p,q)$ where $p \le x \le q$, will be split into two halves of $(p,prv)$ and $(nxt,q)$. Then, duplicates (nodes that represent the same range) will be removed. Finally, there will be a new node that would represent the root, which is $(head,tail)$. Let's track how $maxr$ changes. $maxr(p)=\min(maxr(p),prv)$ for all p in the range $[head,prv]$. Some modification to values of $maxr(head)$, $maxr(x)$ and $maxr(nxt)$. As the first step doesn't change whether values are null or not, and modifications to the second step can be easily handled, part (2) can be easily maintained by a Fenwick tree. So it remains to compute part (1). Imagine instead of computing sum of $pf(maxr(l))$, we are computing sum of $maxr(l)$ Then, we realise that we are having a Segment Tree Beats problem. You have to maintain a sequence with 3 kinds of operation: Do $a[x]=\min(a[x],v)$ for $x$ in $[l,r]$. $a[x]=v$. Query the sum of the whole array. Check part 2 of this blog and this proof of time complexity. Then we can solve this variation of the problem in $O(n\log n)$. So, we have to modify the above variant into solving the real problem. Look at what we do every time we are doing query 1. We are doing a total of $O(n\log n)$ times of changing some occurrences of value $u$ to value $v$. Which means, we can maintain the frequency for values of $maxr$. Therefore, for each put-tag operation in our segment tree beats, we just modify a Fenwick tree that represents the frequency of values in $maxr$. Because we have $O(n\log n)$ updates to the segment tree, the total time complexity is $O(n\log^2 n)$. It is also possible to replace "segment tree beats" with "treap beats" and we can support online queries, but it is not required to pass this problem. We also allowed methods of slower complexity (i.e. $O(n \sqrt{n})$) to pass. It basically is the same but does the above things by sqrt decomposition instead. Care is needed to be sure that there is no extra $log$ factor.
[ "data structures" ]
3,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=3e5+1; const int ts=1<<21; int n; ll mx[ts],se[ts],mxc[ts];//max, 2nd max, max count int sz; ll ch[N];//which values are changed ll df[N];//change in frequency void pass(int id,int c){ if(mx[c]>mx[id]) mx[c]=mx[id]; } void push(int id){ pass(id,id*2); pass(id,id*2+1); } void pull(int id){ mx[id]=max(mx[id*2],mx[id*2+1]); mxc[id]=0; if(mx[id]==mx[id*2]) mxc[id]+=mxc[id*2]; if(mx[id]==mx[id*2+1]) mxc[id]+=mxc[id*2+1]; se[id]=max(se[id*2],se[id*2+1]); if(mx[id*2]!=mx[id]) se[id]=max(se[id],mx[id*2]); if(mx[id*2+1]!=mx[id]) se[id]=max(se[id],mx[id*2+1]); } void upd(int id,int l,int r,int ql,int qr,int v){ if(l>qr || r<ql || mx[id]<=v) return; if(ql<=l && r<=qr && se[id]<v){ ch[++sz]=mx[id];df[mx[id]]-=mxc[id]; mx[id]=v; ch[++sz]=mx[id];df[mx[id]]+=mxc[id]; return; } push(id); int mid=(l+r)/2; upd(id*2,l,mid,ql,qr,v); upd(id*2+1,mid+1,r,ql,qr,v); pull(id); } void upd2(int id,int l,int r,int p,int v){ if(l==r){ ch[++sz]=mx[id];df[mx[id]]-=mxc[id]; mx[id]=v; ch[++sz]=mx[id];df[mx[id]]+=mxc[id]; return; } push(id); int mid=(l+r)/2; if(p<=mid) upd2(id*2,l,mid,p,v); else upd2(id*2+1,mid+1,r,p,v); pull(id); } void build(int id,int l,int r){ mx[id]=0;mxc[id]=r-l+1;se[id]=-1e9; if(l==r) return; int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); } ///////////////////////////////////////////////// ll bit1[N],bit2[N]; void bupd1(int id,ll v){ for(int i=id; i<=n ;i+=i&-i) bit1[i]+=v; } void bupd2(int id,ll v){ for(int i=id; i<=n ;i+=i&-i) bit2[i]+=v; } ll bqry1(int id){ ll res=0; for(int i=id; i>=1 ;i-=i&-i) res+=bit1[i]; return res; } ll bqry2(int id){ ll res=0; for(int i=id; i>=1 ;i-=i&-i) res+=bit2[i]; return res; } int a[N],p[N]; ll ans[N]; set<int>s,t; void magic(int mg){ s.clear();t.clear();build(1,1,n); for(int i=1; i<=n ;i++) bit1[i]=bit2[i]=0; s.insert(p[1]);//set of existed elements t.insert(p[1]);//set of l that maxr[] is not null bupd1(p[1],1); int mx=p[1];//largest existed position upd2(1,1,n,p[1],p[1]); bupd2(p[1],-1); ll tot=-1; for(int i=2; i<=n ;i++){ int cur=p[i]; auto it=s.lower_bound(cur); bool rm=(it==s.end());//new element is rightmost int nxt=0; if(!rm) nxt=*it;//next if(it==s.begin()){//new element is leftmost tot-=bqry1(cur);bupd2(cur,-1); t.insert(cur); upd2(1,1,n,cur,mx); } else{ int prv=*(--it); upd(1,1,n,1,prv,prv); if(rm) mx=cur; else{ upd2(1,1,n,nxt,mx); if(t.find(nxt)==t.end()){ tot-=bqry1(nxt);bupd2(nxt,-1); t.insert(nxt); } } upd2(1,1,n,*s.begin(),mx); } s.insert(cur); tot+=bqry2(n)-bqry2(cur-1); bupd1(cur,1); for(int j=1; j<=sz ;j++){ if(ch[j]!=0 && df[ch[j]]!=0){ tot+=df[ch[j]]*bqry1(ch[j]); bupd2(ch[j],df[ch[j]]); df[ch[j]]=0; } } sz=0; ans[i]+=tot; } } void solve(){ for(int i=1; i<=n ;i++){ p[a[i]]=i;ans[i]=0; } magic(1); for(int i=1; i<=n ;i++) p[i]=n+1-p[i]; magic(0); for(int i=1; i<=n ;i++) ans[i]+=1; for(int i=1; i<=n ;i++) cout << ans[i] << '\n'; } int main(){ ios::sync_with_stdio(false); cin >> n; for(int i=1; i<=n ;i++) cin >> a[i]; solve(); }
1290
F
Making Shapes
You are given $n$ pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: - Start at the origin $(0, 0)$. - Choose a vector and add the segment of the vector to the current point. For example, if your current point is at $(x, y)$ and you choose the vector $(u, v)$, draw a segment from your current point to the point at $(x + u, y + v)$ and set your current point to $(x + u, y + v)$. - Repeat step 2 until you reach the origin again. You can reuse a vector as many times as you want. Count the number of different, non-degenerate (with an area greater than $0$) and convex shapes made from applying the steps, such that the shape can be contained within a $m \times m$ square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo $998244353$. Two shapes are considered the same if there exists some parallel translation of the first shape to another. A shape can be contained within a $m \times m$ square if there exists some parallel translation of this shape so that every point $(u, v)$ inside or on the border of the shape satisfies $0 \leq u, v \leq m$.
Notice that there is a one-to-one correspondent between a non-degenerate convex shape and a non-empty multiset of vectors. That is because, for each shape, we can generate exactly one multiset of vectors by starting at the lowest-leftest point going counter-clockwise (this is possible because no two vectors are parallel); and for each multiset of vectors, we can generate a single convex shape by sorting the vectors by angle then add them in order. Our problem is now counting the number of multisets of vectors that makes non-degenerate convex shapes that can be contained in a $m \times m$ square. Rather, we denote $c_i$ as the number of times the $i^{th}$ vector appears in our multiset. We need to count the number of arrays $c$ such that: $\displaystyle \sum_{i=1}^{n} c_ix_i = \sum_{i=1}^{n} c_iy_i = 0$ $\displaystyle \sum_{1 \leq i \leq n,\, x_i > 0} c_ix_i \leq m$ $\displaystyle \sum_{1 \leq i \leq n,\, y_i > 0} c_iy_i \leq m$ Note that the first conditions are equivalent to $\displaystyle \sum_{1 \leq i \leq n,\, x_i < 0} -c_ix_i = \sum_{1 \leq i \leq n,\, x_i > 0} c_ix_i$ and $\displaystyle \sum_{1 \leq i \leq n,\, y_i < 0} -c_iy_i = \sum_{1 \leq i \leq n,\, y_i > 0} c_iy_i$. For the sake of brevity, let's call $\displaystyle \sum_{1 \leq i \leq n,\, x_i < 0} -c_ix_i$, $\displaystyle \sum_{1 \leq i \leq n,\, x_i > 0} c_ix_i$, $\displaystyle \sum_{1 \leq i \leq n,\, y_i < 0} -c_iy_i$, and $\displaystyle \sum_{1 \leq i \leq n,\, y_i > 0} c_iy_i$ by $nx$, $px$, $ny$, and $py$ respectively. We will now focus on $\log_2{m}$ layers of the array $c$, the $i^{th}$ layer is represented by a bitmask of $n$ bits, where each bit $j$ is the $i^{th}$ bit in the binary representation of $c_j$. We see that if we iterate over these layers like this, we can slowly construct $nx$, $px$, $ny$, and $py$ bit by bit, and be able to compare them with each other and with $m$. So, we do a dynamic programming solution where we maintain these states: The current bit. The carry-over value for $nx$. The carry-over value for $px$. The carry-over value for $ny$. The carry-over value for $py$. Whether the suffix of $px$ is larger than the suffix of $m$. Whether the suffix of $py$ is larger than the suffix of $m$. When we iterate over the states, we iterate over the bitmask of the current layer and calculate and update on the next states. note that, for $px$ for example, the carry-over value has a limit of $\displaystyle \sum_{i=1}^{\infty} \lfloor \frac{px}{2^i} \rfloor = px$, and $px \leq 4n$, so each carry-over dimension is at most $4n$ (practically they cannot all be $4n$ at the same time, so pre-calculating the bound for each dimension is necessary). Complexity: $O(\log_2{m} \cdot n^4 \cdot 2^n)$.
[ "dp" ]
3,500
#include <bits/stdc++.h> using namespace std; const int N = 5, MX = 4 * N, LG = 31, MOD = 998244353; int n, m, x[N], y[N]; int px[1 << N], nx[1 << N], py[1 << N], ny[1 << N]; int dp[LG][MX][MX][MX][MX][2][2]; void add(int &x, int y) { x += y; if (x >= MOD) { x -= MOD; } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; for (int i = 0; i < n; i++) { cin >> x[i] >> y[i]; } for (int msk = 0; msk < (1 << n); msk++) { for (int i = 0; i < n; i++) { if (msk >> i & 1) { (x[i] < 0 ? nx : px)[msk] += abs(x[i]); (y[i] < 0 ? ny : py)[msk] += abs(y[i]); } } } int mpx = max(1, px[(1 << n) - 1]); int mpy = max(1, py[(1 << n) - 1]); int mnx = max(1, nx[(1 << n) - 1]); int mny = max(1, ny[(1 << n) - 1]); dp[0][0][0][0][0][0][0] = 1; for (int lg = 0; (1 << lg) <= m; lg++) { // bit position for (int cpx = 0; cpx < mpx; cpx++) { // carry of positive x for (int cpy = 0; cpy < mpy; cpy++) { // carry of positive y for (int cnx = 0; cnx < mnx; cnx++) { // carry of negative x for (int cny = 0; cny < mny; cny++) { // carry of negative y for (int sx = 0; sx < 2; sx++) { // is the suffix of x greater than the suffix of m for (int sy = 0; sy < 2; sy++) { // is the suffix of y greater than the suffix of m for (int msk = 0; msk < (1 << n); msk++) { // iterating over the mask of the current bit position int spx = cpx + px[msk]; int spy = cpy + py[msk]; int snx = cnx + nx[msk]; int sny = cny + ny[msk]; if (((spx ^ snx) & 1) || ((spy ^ sny) & 1)) { continue; } int bx = spx & 1, by = spy & 1; int nsx = (bx < (m >> lg & 1) ? 0 : bx > (m >> lg & 1) ? 1 : sx); int nsy = (by < (m >> lg & 1) ? 0 : by > (m >> lg & 1) ? 1 : sy); add(dp[lg + 1][spx / 2][spy / 2][snx / 2][sny / 2][nsx][nsy], dp[lg][cpx][cpy][cnx][cny][sx][sy]); } } } } } } } } cout << (dp[__lg(m) + 1][0][0][0][0][0][0] + MOD - 1) % MOD << '\n'; }
1291
A
Even But Not Even
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by $2$ but the number itself is not divisible by $2$. For example, $13$, $1227$, $185217$ are ebne numbers, while $12$, $2$, $177013$, $265918$ are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification. You are given a non-negative integer $s$, consisting of $n$ digits. You can delete some digits (they are \textbf{not} necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between $0$ (do not delete any digits at all) and $n-1$. For example, if you are given $s=$222373204424185217171912 then one of possible ways to make it ebne is: {\textbf{\sout{2}}22373\textbf{\sout{20}}442\textbf{\sout{4}}18521717191\textbf{\sout{2}}} $\rightarrow$ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to $70$ and is divisible by $2$, but number itself is not divisible by $2$: it means that the resulting number is ebne. Find \textbf{any} resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.
If the number of odd digits is smaller than or equal to $1$, it is impossible to create an ebne number. Otherwise, we can output any 2 odd digits of the number (in correct order of course).
[ "greedy", "math", "strings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; int odd = 0; for (char c : s) if ((c - '0') & 1) odd++; if (odd <= 1) { cout << "-1\n"; continue; } int cnt = 0; for (char c : s) { if ((c - '0') & 1) { cout << c; cnt++; } if (cnt == 2) break; } cout << '\n'; } return 0; }
1291
B
Array Sharpening
You're given an array $a_1, \ldots, a_n$ of $n$ non-negative integers. Let's call it sharpened if and only if there exists an integer $1 \le k \le n$ such that $a_1 < a_2 < \ldots < a_k$ and $a_k > a_{k+1} > \ldots > a_n$. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: - The arrays $[4]$, $[0, 1]$, $[12, 10, 8]$ and $[3, 11, 15, 9, 7, 4]$ are sharpened; - The arrays $[2, 8, 2, 8, 6, 5]$, $[0, 1, 1, 0]$ and $[2, 5, 6, 9, 8, 8]$ are \textbf{not} sharpened. You can do the following operation as many times as you want: choose any \textbf{strictly positive} element of the array, and decrease it by one. Formally, you can choose any $i$ ($1 \le i \le n$) such that $a_i>0$ and assign $a_i := a_i - 1$. Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.
How to know if we can make the prefix $[1 ; k]$ strictly increasing? We just have to consider the following simple greedy solution: take down values to $0, 1, \ldots, k-1$ (minimal possible values). It's possible if and only if $a_i \ge i-1$ holds in the whole prefix. Similarly, the suffix $[k ; n]$ can be made strictly decreasing if and only if $a_i \ge n-i$ holds in the whole suffix. Using these simple facts, we can compute the longest prefix we can make strictly increasing, and the longest suffix we can make strictly decreasing in $O(n)$. Then, we just have to check that their intersection is non-empty.
[ "greedy", "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int nbTests; cin >> nbTests; while (nbTests--) { int nbElem; cin >> nbElem; vector<int> tab(nbElem); for (int i = 0; i < nbElem; ++i) cin >> tab[i]; int prefixEnd = -1, suffixEnd = nbElem; for (int i = 0; i < nbElem; ++i) { if (tab[i] < i) break; prefixEnd = i; } for (int i = nbElem-1; i >= 0; --i) { if (tab[i] < (nbElem-1)-i) break; suffixEnd = i; } if (suffixEnd <= prefixEnd) // Non-empty intersection cout << "Yes\n"; else cout << "No\n"; } }
1292
A
NEKO's Maze Game
\begin{quote} 3R2 as DJ Mashiro - Happiness Breeze \end{quote} \begin{quote} Ice - DJ Mashiro is dead or alive \end{quote} NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a $2 \times n$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $(1, 1)$ to the gate at $(2, n)$ and escape the maze. The girl can only move between cells sharing a common side. However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type. After hours of streaming, NEKO finally figured out there are only $q$ such moments: the $i$-th moment toggles the state of cell $(r_i, c_i)$ (either from ground to lava or vice versa). Knowing this, NEKO wonders, after each of the $q$ moments, whether it is still possible to move from cell $(1, 1)$ to cell $(2, n)$ without going through any lava cells. Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?
The main observation is that, it is possible to travel from $(1, 1)$ to $(2, n)$ if and only if there exist no pair of forbidden cell $(1, a)$ and $(2, b)$ such that $|a - b| \le 1$. Therefore, to answer the query quickly, for every $d$ from $-1$ to $1$, one should keep track of the number of pair $(a, b)$ such that: $(1, a)$ and $(2, b)$ are both forbidden. $a - b = d$. One of the methods to do this is: after a cell $(x, y)$ has been swapped, check for all cells $(3-x, y-1)$, $(3-x, y)$, $(3-x, y+1)$ and update the number of pairs based on the status of those cells and new status of $(x, y)$. Since $n \le 10^5$, the status of all cells can be easily kept in a 2D boolean array, and accessed in $\mathcal{O}(1)$ time complexity. Total complexity: $\mathcal{O}(n + q)$. Video by Errichto: https://www.youtube.com/watch?v=mhrvlor1qH0
[ "data structures", "dsu", "implementation" ]
1,400
T = 1 for test_no in range(T): n, q = map(int, input().split()) lava = [[0 for j in range(n)] for i in range(2)] blockedPair = 0 while q > 0: q -= 1 x, y = map(lambda s: int(s)-1, input().split()) delta = +1 if lava[x][y] == 0 else -1 lava[x][y] = 1 - lava[x][y] for dy in range(-1, 2): if y + dy >= 0 and y + dy < n and lava[1-x][y+dy] == 1: blockedPair += delta if blockedPair == 0: print('Yes') else: print('No')
1292
B
Aroma's Search
\begin{quote} THE SxPLAY & KIVΛ - 漂流 \end{quote} \begin{quote} KIVΛ & Nikki Simmons - Perspectives \end{quote} With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space. The space can be considered a 2D plane, with an infinite number of data nodes, indexed from $0$, with their coordinates defined as follows: - The coordinates of the $0$-th node is $(x_0, y_0)$ - For $i > 0$, the coordinates of $i$-th node is $(a_x \cdot x_{i-1} + b_x, a_y \cdot y_{i-1} + b_y)$ Initially Aroma stands at the point $(x_s, y_s)$. She can stay in OS space for at most $t$ seconds, because after this time she has to warp back to the real world. She \textbf{doesn't} need to return to the entry point $(x_s, y_s)$ to warp home. While within the OS space, Aroma can do the following actions: - From the point $(x, y)$, Aroma can move to one of the following points: $(x-1, y)$, $(x+1, y)$, $(x, y-1)$ or $(x, y+1)$. This action requires $1$ second. - If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs $0$ seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within $t$ seconds?
First, keep a list of "important" nodes (nodes that are reachable from the starting point with $t$ seconds), and denote this list $[(x_1, y_1), (x_2, y_2), \ldots, (x_k, y_k)]$. Since $a_x, a_y \geq 2$, there are no more than $\log_2(t)$ important nodes (in other words, $k \leq \log_2(t))$. In an optimal route, we must first reach a data node in fastest time possible. Suppose that we reach node $z$ first, and we now have $t'$ seconds left. Let's denote $d(i, j)$ the time required to travel from the $i$-th node to the $j$-th node. $d(i, j)$ is also the Manhattan distance between the $i$-th and the $j$-th node - in other words, $d(i, j) = |x_j - x_i| + |y_j - y_i|$. Since $x_i \geq x_{i-1}$ and $y_i \geq y_{i-1}$, we have $d(u, v) + d(v, w) = d(u, w)$ for all $1 \leq u < v < w \leq k$. Therefore, if we consider all the nodes to stay in a line in such a way that $x_i = x_{i-1} + d(i-1, i)$, the problem is reduced to the following problem: To solve the above problem, one should notice that it is optimal to collect nodes in a continuous segment. Suppose that we collect all nodes from the $l$-th to $r$-th (for some $l \leq s \leq r$). An optimal route is one of the two below: Go from $z$ to $r$ and then go to $l$. The time required for this route is $d(r, z) + d(r, l)$. Go from $z$ to $l$ and then go to $r$. The time required for this route is $d(z, l) + d(r, l)$. Therefore, the minimum amount of energy required to collect all the nodes from $l$-th to $r$-th is $d(r, l) + \min(d(z, l), d(r, z))$. Since $k$ is small, one can brute-force through all triple of $(l, z, r)$ such that $1 \leq l \leq z \leq r \leq k$ and check if $t$ seconds are enough to go to $i$-th node and then collect all the nodes from $l$-th to $r$-th or not. The time complexity for that approach is $\mathcal{O}(\log_2(t)^3)$. However, we can notice that it's always the most optimal to choose $z$ as either $l$ or $r$, for a few reasons: As the aforementioned formula, either $d(z, l)$ or $d(r, z)$ will be counted twice (one there, and one within $d(r, l)$, so having it reduced to $0$ nullifies the exceeded step. The distance from $(x_z, y_z)$ to $(x_s, y_s)$ does not break the minimal properties of the endpoint(s) regardless of $(x_s, y_s)$'s position. We can prove it by considering all possible relative positions of $(x_s, y_s)$ over the segment (we'll consider the $x$-coordinates only, $y$-coordinates will have the same properties, without loss of generality): If $x_s \le x_l$, the distance is minimal at $z = l$. If $x_r \le x_s$, the distance is minimal at $z = r$. If $x_l \le x_s \le x_r$, the travelling time in $x$-coordinates is $d(s, z) + d(r, l) + \min(d(z, l), d(r, z))$. One can see that $d(s, z) + \min(d(z, l), d(r, z)) = \min(d(s, l), d(s, r))$, therefore any $z$ (including the endpoints, of course) is equally optimal. Proof for the above formula is trivial. If $x_s \le x_l$, the distance is minimal at $z = l$. If $x_r \le x_s$, the distance is minimal at $z = r$. If $x_l \le x_s \le x_r$, the travelling time in $x$-coordinates is $d(s, z) + d(r, l) + \min(d(z, l), d(r, z))$. One can see that $d(s, z) + \min(d(z, l), d(r, z)) = \min(d(s, l), d(s, r))$, therefore any $z$ (including the endpoints, of course) is equally optimal. Proof for the above formula is trivial. The optimal solution's time complexity is $\mathcal{O}(\log_2(t)^2)$.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
1,700
T = 1 for test_no in range(T): x0, y0, ax, ay, bx, by = map(int, input().split()) xs, ys, t = map(int, input().split()) LIMIT = 2 ** 62 - 1 x, y = [x0], [y0] while ((LIMIT - bx) / ax >= x[-1] and (LIMIT - by) / ay >= y[-1]): x.append(ax * x[-1] + bx) y.append(ay * y[-1] + by) n = len(x) ans = 0 for i in range(n): for j in range(i, n): length = x[j] - x[i] + y[j] - y[i] dist2Left = abs(xs - x[i]) + abs(ys - y[i]) dist2Right = abs(xs - x[j]) + abs(ys - y[j]) if (length <= t - dist2Left or length <= t - dist2Right): ans = max(ans, j-i+1) print(ans)
1292
C
Xenon's Attack on the Gangs
\begin{quote} INSPION FullBand Master - INSPION \end{quote} \begin{quote} INSPION - IOLITE-SUNSTONE \end{quote} On another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world. His target is a network of $n$ small gangs. This network contains exactly $n - 1$ direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links. By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from $0$ to $n - 2$ such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass $S$ password layers, with $S$ being defined by the following formula: $$S = \sum_{1 \leq u < v \leq n} mex(u, v)$$ Here, $mex(u, v)$ denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang $u$ to gang $v$. Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of $S$, so that the AIs can be deployed efficiently. Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible $S$ before he returns?
The first observation is that, the formula can be rewritten as: $S = \sum_{1 \leq u < v \leq n} mex(u, v) = \sum_{1 \leq x \leq n} \left( \sum_{mex(u, v) = x} x \right) = \sum_{1 \leq x \leq n} \left( \sum_{mex(u, v) \geq x} 1 \right) = \sum_{1 \leq x \leq n} f(x)$ Where $f(x)$ is number of pairs $(u, v)$ such that $1 \leq u < v \leq n$ and $mex(u, v) \geq x$ (in other word, the path from $u$ to $v$ contains all numbers from $0$ to $x-1$). Consider the process of placing numbers in order from $0$ to $n-1$ (first place number $0$, then place number $1$, etc.) on edges of the tree. Suppose that the placement for all numbers from $0$ to $x-1$ are fixed, and now we need to place number $x$. To maximize $S$, we should try to place $x$ in a way that there exists a path contain all numbers from $0$ to $x$ (if this is possible). In other word, in the optimal solution, there will be a path connecting two leaf vertices that contain all numbers from $0$ to $l - 1$ (where $l$ is the number of vertices in that path). The placement of numbers from $l$ to $n-2$ does not matter, since it will not affect the result. Now, suppose that the location of such path is fixed, and its length is $l$. Let $a$ the sequence of number on edges on the path from $u$ to $v$. One can show that, in other to archive maximum $S$, $a$ must be a 'valley' sequence (there exist some position $p$ such that $a_1 > a_2 > \ldots > a_p < \ldots < a_{l-1} < a_l$. All the observation above leads to the following dynamic programming solution: Let $dp[u][v]$ the maximum value of $\sum_{1 \leq x \leq l} f(x)$ if all number from $0$ to $l-1$ are written on the edges on the path from $u$ to $v$ (with $l$ denote the length of that path). We also define: $par(r, u)$: the parent of vertex $u$ if we root the tree at vertex $r$. $sub(r, u)$: the number of vertices in the subtree of vertex $u$ if we root the tree at vertex $r$. The figure below demonstrate $par(u, v)$ and $par(v, u)$ for two vertices $u$ and $v$ (in the figure, $p_{u,v}$ is $par(u, v)$ and $p_{v,u}$ is $par(v, u)$). To calculate $dp[u][v]$, there are two cases: Putting number $l$ on the edge $(u, par(v, u))$. In this case: $\sum_{1 \leq x \leq l} f(x) = f(l) + \sum_{1 \leq x \leq l-1} f(x) = sub(u, v) \times sub(v, u) + dp[par(v, u)][v]$ $\sum_{1 \leq x \leq l} f(x) = f(l) + \sum_{1 \leq x \leq l-1} f(x) = sub(u, v) \times sub(v, u) + dp[par(v, u)][v]$ Putting number $l$ on the edge $(v, par(u, v))$. Similarly, $\sum_{1 \leq x \leq l} f(x) = sub(u, v) \times sub(v, u) + dp[u][par(u, v)]$ The final formula to calculate $dp[u][v]$ is: $dp[u][v] = sub(u, v) \times sub(v, u) + \max(dp[par(v, u)][v], dp[u][par(u, v)])$ The formula can be calculated in $O(1)$ if all the values of $par(r, u)$ and $sub(r, u)$ are calculated (we can preprocess to calculate these value in $\mathcal{O}(n^2)$. by doing performing DFS once from each vertex). Therefore, the overall complexity for this algorithm is $\mathcal{O}(n^2)$.
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
2,300
import sys # Read input and build the graph inp = [int(x) for x in sys.stdin.buffer.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) # Relabel to speed up n^2 operations later on bfs = [0] found = [0]*n found[0] = 1 for node in bfs: for nei in coupl[node]: if not found[nei]: found[nei] = 1 bfs.append(nei) new_label = [0]*n for i in range(n): new_label[bfs[i]] = i coupl = [coupl[i] for i in bfs] for c in coupl: c[:] = [new_label[x] for x in c] ##### DP using multisource bfs DP = [0] * (n * n) size = [1] * (n * n) P = [-1] * (n * n) # Create the bfs ordering bfs = [root * n + root for root in range(n)] for ind in bfs: P[ind] = ind for ind in bfs: node, root = divmod(ind, n) for nei in coupl[node]: ind2 = nei * n + root if P[ind2] == -1: bfs.append(ind2) P[ind2] = ind del bfs[:n] # Do the DP for ind in reversed(bfs): node, root = divmod(ind, n) ind2 = root * n + node pind = P[ind] parent = pind//n # Update size of (root, parent) size[pind] += size[ind] # Update DP value of (root, parent) DP[pind] = max(DP[pind], max(DP[ind], DP[ind2]) + size[ind] * size[ind2]) print(max(DP[root * n + root] for root in range(n)))
1292
D
Chaotic V.
\begin{quote} Æsir - CHAOS \end{quote} \begin{quote} Æsir - V. \end{quote} "Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect. The time right now...... 00:01:12...... It's time." The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa. The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($1, 2, 3, \ldots$). The node with a number $x$ ($x > 1$), is directly connected with a node with number $\frac{x}{f(x)}$, with $f(x)$ being the lowest prime divisor of $x$. Vanessa's mind is divided into $n$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $i$-th fragment is now located at the node with a number $k_i!$ (a factorial of $k_i$). To maximize the chance of successful awakening, Ivy decides to place the samples in a node $P$, so that the total length of paths from each fragment to $P$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $P$ needs to be counted multiple times. In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node. But for a mere human like you, is this still possible? For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $P$.
First of all, one can see that the network is a tree rooted at vertex $1$, thus for each pair of vertices in it there can only be one simple path. Also, the assembly node $P$ must be on at least one simple path of a fragment to the root (proof by contradiction, explicit solution is trivial). Let's start with $P$ being node $1$. From here, moving down to any branch will increase $1$ for each element not being in that branch and decrease $1$ for each element being in, thus we'll only move down to the branch having the most elements until the decreasing cannot outmatch the increasing (in other words, the number of fragments in a branch must be more than half for that branch to be reached). Given the criteria of the graph, we can see that: two nodes are in the same branch from the root if having the same one largest factor from the prime factorization, they are in the same branch from a depth-1-node if having the same two largest factors, ..., in the same branch from a depth-$k$-node if having the same $k+1$ largest factors. Keep in mind that here the largest factors can be the duplicated, i.e. in the case of $576 = 2^6 \cdot 3^2$, the two largest factors are $3$ and $3$, and the three largest factors are $3$, $3$ and $2$. The process will now become factorizing the numbers, and then, cycle by cycle, pop the current largest factor of each number and group them, find out the group (branch) with most occurences and either move on (if the total sum can be lowered) or stop the process. Since all of these are factorials, the factorizing can be done with a bottom-up dynamic programming fashion. Also, as $k \le 5000$ and $n \le 10^6$, consider grouping duplicated elements to reduce calculating complexity. Both factorization and processing has the worst-case complexity of $\mathcal{O}(MAXK^2 \cdot f(MAXK))$, with $k \cdot f(k)$ being the estimated quantity of prime divisors of $k!$. It's proven that $f(k) = M + \ln \ln k$, with $M$ being the Meissel-Mertens constant. The proof of this formula is based on the fact this number is calculated through the sum of the reciprocals of the primes.
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
2,700
T = 1 for test_no in range(T): MAXK = 5000 n = int(input()) cnt = [0] * (MAXK + 1) primeExponential = [[0 for j in range(MAXK + 1)] for i in range(MAXK + 1)] line, num = (input() + ' '), 0 for c in line: if c != ' ': num = num * 10 + (ord(c) - 48) else: cnt[num] += 1 num = 0 for i in range(2, MAXK + 1): for j in range(0, MAXK + 1): primeExponential[i][j] += primeExponential[i-1][j] tmp, x = i, 2 while x * x <= tmp: while tmp % x == 0: primeExponential[i][x] += 1 tmp //= x x += 1 if tmp > 1: primeExponential[i][tmp] += 1 bestPD = [1] * (MAXK + 1) ans, cur = 0, 0 for i in range(1, MAXK + 1): if cnt[i] == 0: continue for j in range(1, MAXK + 1): ans += primeExponential[i][j] * cnt[i] cur += primeExponential[i][j] * cnt[i] if primeExponential[i][j]: bestPD[i] = j frequency = [0] * (MAXK + 1) while max(bestPD) > 1: for i in range(MAXK + 1): frequency[i] = 0 for i in range(MAXK + 1): frequency[bestPD[i]] += cnt[i] bestGroup = max(frequency) bestPrime = frequency.index(bestGroup) if bestGroup * 2 <= n: break if bestPrime == 1: break cur -= bestGroup cur += (n - bestGroup); ans = min(ans, cur) for i in range(MAXK + 1): if bestPD[i] != bestPrime: bestPD[i] = 1 if bestPD[i] == 1: continue primeExponential[i][bestPD[i]] -= 1 while bestPD[i] > 1 and primeExponential[i][bestPD[i]] == 0: bestPD[i] -= 1 print(ans)
1292
E
Rin and The Unknown Flower
\begin{quote} MisoilePunch♪ - 彩 \end{quote} This is an interactive problem! On a normal day at the hidden office in A.R.C. Markland-N, Rin received an artifact, given to her by the exploration captain Sagar. After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily. The chemical structure of this flower can be represented as a string $p$. From the unencrypted papers included, Rin already knows the length $n$ of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen). At each moment, Rin can input a string $s$ of an arbitrary length into the artifact's terminal, and it will return every starting position of $s$ as a substring of $p$. However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: - The artifact only contains $\frac{7}{5}$ units of energy. - For each time Rin inputs a string $s$ of length $t$, the artifact consumes $\frac{1}{t^2}$ units of energy. - If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?
To be fair, this is a complicated decision tree problem. I recommend instead of heading straight to read the main solutions for this, try to spend some time and come up with at least 2 solutions for the case when the query limit is 5/3 first. <spoilers> There are many solutions when limit = 5/3, and I'll point 2 of them out. The difference between the two solutions is how you approach the string and build a decision tree out of those queries: 1. The easiest to come up with: disclose every joint of the string (which is equivalent to find every position $i$ that S[i]==S[i+1]). All remaining letters can be filled up with the nearest disclosed letter to it. This can be done by asking 6 queries: "CH", "HC", "CO", "OC", "OH", "HO". If none of the letters is disclosed, then all of the letters are the same. You can disclose all of them by asking 2 more queries of length n and determine what letter is it. 2. The most natural solution (in my opinion): The idea of this is to disclose at least one letter of the string, to disclose the rest with at most one string of length $2$ to $n$ each. We could do this by simply asking "C". This could go either way: If a 'C' is disclosed at a position $i$, we can disclose the position $i+1$ with one query of length $2$, $i+2$ with one query of length $3$, ... and so on. From there, undisclose position $i-1$ with a query of length $n-i+1$, $i-2$ with a query of length $n-i+2$, ... and so on. If no letter is disclosed, the problem narrows down to solve with a binary string and total cost of $2/3$. There are multiple ways to tackle this so I won't spend any more time to explain this case. The key here is to come up with a strategy that works in all branches of the decision tree. And to do that, we must find a good starting query/set of queries to begin with. In the two strategies above, number 1 is too brutal, and number 2 is too naive. But my main solution contains the essences which can be seen in both solutions. The main idea is to find a set of queries to begin with like strat #2 but would give us more hints and cost us less when things go the other way. We'll start by asking queries with "CH", "CO", "HC", "HO", which in total have cost of $1$. That way, the non-disclosed parts can be one of those: Consecutive similar characters. A joint starting with "O". Supposed that after four above queries and no occurrences were found at all, the string can now be only in one of those kinds: An entire string constructed by a single character. A string of form "OO...XX", with "X" being either "C" or "H". In other words, the string is constructed by $n_0$ characters "O", followed by $n_1$ characters "X" ($n_0 + n_1 = n$). Proof for this is trivial. We'll find the trace of large chunks of "C" or "H" (cannot find every trace since the cost limit is very tight here, the minimum length allowed should only be $3$). To do this, we'll ask queries "CCC" and "HHH" sequentially. If any of the two queries return occurrence(s), that means all occurrences of "C" or "H" has been revealed (and also guaranteed to completely inherit the right side of the string), any undisclosed characters on the left will obviously be "O". From here, we can conclude and return the original string. However, if both queries return nothing, this means either the string contains only "O" characters or there are at most $2$ rightmost characters being "C" or "H". Given this, we ought to find the chunk of "O" by asking query "OOO" (similar logic to the former step). If it returns occurrence(s) and there are still undisclosed characters, we'll need another query of length $n$ to finalize: replacing all of the undisclosed positions to "C" then ask a query with that string, if it returns occurrence then "C" is for the missing characters, otherwise "H" is. This method works because there will always be one chunk with length at least $3$ (on either end of the string), except two cases: "OOCC" and "OOHH". You will get to this if all three above queries failed to return anything. However, since this is a matter of picking one from two, a single query of either string will work: the original string is the asked string if occurrence found, otherwise the other. This is also the worst case in this branch. Total cost would be $1 + 3 \cdot \frac{1}{9} + \frac{1}{16} = 1.3958(3)$ - very close to the limit. Back to the case that some occurrence(s) are found when after asking the $4$ joint queries. The logic now is pretty similar to strat #2 mentioned above however due to the more varied undisclosed patterns, we'll need to take some extra caution. First of all, we'll start at the leftmost revealed segment, and disclose any hidden characters to the left of it. It's easy to see that the leftmost revealed character can never be "O", and since the leftmost hidden segment always come in one of two forms similar to the no-occurrence case branch above, you can always reveal the nearest character by assuming it is the same as the current leftmost revealed character and use it as a query to ask. If the assumption is incorrect, then it and any remaining hidden letters to the left of it will be "O". Now that we have a fully revealed prefix, we'll extend it by revealing letters to the right. For simplicity, let's split into two cases: one when there are revealed letter(s) not within our current prefix, one when there is none. If such revealed letters are found, consider the one being closest to our prefix. We can see that the hidden gap between our prefix and it can only be produced by some (probably none) characters being the same as our rightmost character in the prefix, followed by some (probably none) characters being the same as our leftmost character outside of the prefix. Thus, we can simply assume the next hidden character is the same as our rightmost in-prefix character, then ask the query. If the assumption is incorrect, fill it and all the remaining hidden characters in that segment with the other one. If there are none, then the last hidden segment is again, similar to the no-occurrence case branch. However, we have a significant clue this time: our rightmost in-prefix character. If it is not "O", we can quickly fill all the hidden positions with it, otherwise, we'll keep asking query again, assuming the next hidden character is still "O": if incorrect, take another query to ask if either it is "C" or "H", and then fill it and all the other hidden ones. ** Example interaction: The string is "COHHHH..." ($n = 50$, in other words the string is construct by appending $48$ character "H" to the string "CO"). => 50 (Finding joints not starting at O) ? CH => 0 ? CO => 1 1 ? HC => 0 ? HO => 0 (Now, the string can be deduced as "CO????...") ? COO => 0 (Assuming that the third character is still "O", sadly it isn't.) ? COC => 0 (Assuming that the third character is still "C", and it isn't either.) (By now we can deduce the string to be "COHHHH....", since the fourth character and beyond cannot be anything other than "H" (otherwise it would have raised a signal in the joints queries)). ! COHHHH... => 1 ** End of example. The maximum cost for this will be ($i = 3$ because starting from a joint means we have at least $2$ found characters, incremented by $1$ by the character we're about to guess): $\displaystyle \max_{4 \le n \le 50} \left( 1 + \sum_{i = 3}^{n} \frac{1}{i^2} + \frac{1}{n^2} \right)$ With $n$ going to positive infinity, the limit of this function will be $\frac{2 \pi^2 - 3}{12} < 1.4$, therefore this solution still works. </spoilers> Big credits to Sooke for making this problem more interesting by pointing out a way to reduce the initial limit (5/3) and make this problem much less trivial.
[ "constructive algorithms", "greedy", "interactive", "math" ]
3,500
import sys n, L, minID = None, None, None s = [] def fill(id, c): global n, L, s, minID L -= (s[id] == 'L') s = s[0:id] + c + s[id+1:] minID = min(minID, id) def query(cmd, str): global n, L, s, minID print(cmd, ''.join(str)) print(cmd, ''.join(str), file=sys.stderr) sys.stdout.flush() if (cmd == '?'): result = list(map(int, input().split())) assert(result[0] != -1) for z in result[1:]: z -= 1 for i in range(len(str)): assert(s[z+i] == 'L' or s[z+i] == str[i]) fill(z+i, str[i]) elif (cmd == '!'): correct = int(input()) assert(correct == 1) T = int(input()) for test_no in range(T): n = int(input()) L, minID = n, n s = 'L' * n query('?', "CH") query('?', "CO") query('?', "HC") query('?', "HO") if (L == n): # the string exists in form O...OX...X, with X=C or X=H # or it's completely mono-character query('?', "CCC") if (minID < n): for x in range(minID-1, -1, -1): fill(x, 'O') else: query('?', "HHH") if (minID < n): for x in range(minID-1, -1, -1): fill(x, 'O') else: query('?', "OOO") if (minID == n): # obviously n=4 query('?', "OOCC") if (minID == n): fill(0, 'O') fill(1, 'O') fill(2, 'H') fill(3, 'H') if (s[n-1] == 'L'): t = s[0:n-1] + 'C' if (t[n-2] == 'L'): t = t[0:n-2] + 'C' + t[n-1:] query('?', t) if (s[n-1] == 'L'): fill(n-1, 'H') if (s[n-2] == 'L'): fill(n-2, 'H') else: maxID = minID while (maxID < n-1 and s[maxID+1] != 'L'): maxID += 1 for i in range(minID-1, -1, -1): query('?', s[i+1:i+2] + s[minID:maxID+1]) if (minID != i): for x in range(i+1): fill(x, 'O') break nextFilled = None i = maxID + 1 while i < n: if (s[i] != 'L'): i += 1 continue nextFilled = i while (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1 query('?', s[0:i] + s[i-1]) if (s[i] == 'L'): if (s[i-1] != 'O'): fill(i, 'O') else: if (nextFilled == n): query('?', s[0:i] + 'C') if (s[i] == 'L'): fill(i, 'H') for x in range(i+1, nextFilled): fill(x, s[i]) else: for x in range(i, nextFilled): fill(x, s[nextFilled]) i = nextFilled - 1 i += 1 query('!', s)
1292
F
Nora's Toy Boxes
\begin{quote} SIHanatsuka - EMber \end{quote} \begin{quote} SIHanatsuka - ATONEMENT \end{quote} Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities. One day, Nora's adoptive father, Phoenix Wyle, brought Nora $n$ boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO. She labelled all $n$ boxes with $n$ distinct integers $a_1, a_2, \ldots, a_n$ and asked ROBO to do the following action several (possibly zero) times: - Pick three distinct indices $i$, $j$ and $k$, such that $a_i \mid a_j$ and $a_i \mid a_k$. In other words, $a_i$ divides both $a_j$ and $a_k$, that is $a_j \bmod a_i = 0$, $a_k \bmod a_i = 0$. - After choosing, Nora will give the $k$-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. - After doing so, the box $k$ becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the \textbf{largest} amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes. Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them? As the number of such piles can be very large, you should print the answer modulo $10^9 + 7$.
We consider a directed graph $G$, where we draw an edge from vertex $i$ to vertex $j$ if $a_i \mid a_j$. Notice that $G$ is a DAG and is transitive (if $(u, v), (v, w) \in G$ then $(u, w) \in G$). For each vertex, we consider two states: "on" (not deleted) and "off" (deleted). An edge is "on" if both end vertices are not deleted, and "off" otherwise. The operation is equivalent to choosing a vertices triple $(u, v, w)$ such that $u$, $v$, $w$ are on and $(u, v), (u, w) \in G$; then turn off vertex $w$ and append $a_w$ to the end of $b$. We first solve the problem for a weakly connected component $C$ (only choosing vertices triple belong to this component in each operation). Define $S$ the set of all vertices with no incoming edges, and $T$ the set of remaining vertices ($T = C - S$). Obviously, vertices in $S$ can't be turned off. We need to figure out the maximum number of vertices in $T$ we can turn off. We consider the reversed process. Initially, some vertices in $T$ are turned off, and we can turn on a vertex with the following operation: choose a vertices triple $(u, v, w)$ such that $u$, $v$ are on, $w$ is off, and $(u, v), (u, w) \in G$; then turn on $w$ and append $a_w$ to the beginning of $b$. Lemma 1: For each vertex $u \in T$, there exist a vertex in $S$ that has an outgoing edge to $u$. Proof: Consider a vertex $u \in T$. If $u$ has no incoming edge from another vertex in $T$, $u$ must has an incoming edge from a vertex in $S$ (if not, $u$ have no incoming edge, which mean $u$ should be in $S$ instead of $T$, contradiction). Otherwise, let $v$ the vertex with minimum $a_v$ among all vertices in $T$ with an outgoing edge to $u$. $v$ has no incoming edge from another vertex in $T$, so there exist a vertex $s \in S$ that has an outgoing edge to $v$. Since $G$ is transitive and $(v, u), (s, v) \in G$, $s$ has an outgoing edge to $u$. $\blacksquare$ Lemma 2: If at least one vertex in $T$ is on, we can turn all other vertices in $T$ on. Proof: Let's $X$ the set of all vertices in $T$ that is currently on, and $Y$ the set of remaining vertices in $T$ ($Y = T - X$). We will prove that, if $X$ is not empty, we can always turn on a vertex in $Y$. If this is true, starting from the state where $X$ contain only one vertex (and $Y$ contain the remaining vertices of $T$), one can repeat turning on a vertex in $Y$ until all vertices in $T$ are on. To prove it, we need to show that there exist a vertex in $S$ that has an outgoing edge to some vertex in $X$ and some vertex in $Y$ (so we can choose the triple of three mentioned vertices to turn on a vertex in $Y$). Consider two cases: Case 1: There exist some edge $(v, w)$ with $v \in X$ and $w \in Y$.Let $s$ a vertex in $S$ that has an outgoing edge to $v$. Since $G$ is transitive and $(s, v)$, $(v, w)$ are in $G$, $(s, w)$ are also in $G$. In other word, $s \in S$ has an outgoing edge to both $v \in X$ and $w \in Y$. Let $s$ a vertex in $S$ that has an outgoing edge to $v$. Since $G$ is transitive and $(s, v)$, $(v, w)$ are in $G$, $(s, w)$ are also in $G$. In other word, $s \in S$ has an outgoing edge to both $v \in X$ and $w \in Y$. Case 2: There is no edge from a vertex in $X$ to a vertex in $Y$. In this case, if there exist no vertex in $S$ that has an outgoing edge to some vertex in $X$ and some vertex in $Y$, the component would be divided into two smaller component (one with all vertices in $X$ with their incoming vertices, one with all vertices in $Y$ with their incoming vertices). This contradict the fact that $S$, $X$ and $Y$ are weakly connected. $\blacksquare$ In this case, if there exist no vertex in $S$ that has an outgoing edge to some vertex in $X$ and some vertex in $Y$, the component would be divided into two smaller component (one with all vertices in $X$ with their incoming vertices, one with all vertices in $Y$ with their incoming vertices). This contradict the fact that $S$, $X$ and $Y$ are weakly connected. $\blacksquare$ The lemma above give us the maximum length of sequence $B$ we can construct: $|T| - 1$. Now we need to count the number of such sequence $B$. Equivalently, for each vertex $u \in T$, we need to count the number of orders to turn on all other vertices in $T$ (given that $u$ is initially on and all other vertices in $T$ are initially off). Let $s_1, s_2, \ldots, s_p$ the vertices in $S$ and $t_1, t_2, \ldots, t_m$ the vertices in $T$. First, how can we know whether we can turn on a vertex in $T$, without having to consider the states of other vertices in $T$? Lemma 3: When perform the above operation, it is sufficient to consider only all triples $(u, v, w)$ such that $u \in S$ and $v, w \in T$. Proof: For a vertex $w$ in $T$ that is off, assume that we can turn on $w$ by choosing a triple $(u, v, w)$ such that $u, v \in T$. In other to choose the triple, $u$, $v$ must be on and $(u, v), (u, w) \in G$. Let $s$ the vertex in $S$ that has an outgoing edge to $u$ ($s$ is always on since $s \in S$). Since the graph is transitive, $s$ also has outgoing edges to $v$ and $w$. Therefore, we can turn on $w$ by choosing the triple $(s, v, w)$ instead. $\blacksquare$ With the above lemma, it is sufficient to only consider, for each vertex $u \in S$, whether there is an on outgoing edge from $u$. We can use a bitmask of length $p$ to represent this information, with $x$-th bit equal $1$ if $s_x$ has an on outgoing edge (and equal $0$ otherwise). For each vertex $t_i \in T$, let $inMask[i]$ the bitmask of length $p$, with $x$-th bit equal $1$ if $s_x$ has an outgoing edge to $t_i$ in $G$. Let $dp[mask][k]$ the number of distinct box piles of length $k$ ROBO can have, with the $x$-th bit of $mask$ equals $1$ if $s_x$ has an on outgoing edge to a vertex in $T$ that is turned on. For a vertex $t_j$ that is currently off, we can turn on $t_j$ if $inMask[j] \; \& \; mask \neq 0$. There are two cases: Turn on a currently-off vertex $t_j$ in a way that $mask$ is expanded (some bit(s) $0$ turn into bit(s) $1$). To archive this, we must select $t_j$ in such a way that $inMask[j]$ must not be a subset of $mask$, and we can turn on $t_j$ (if a $t_j$ satisfy these two conditions, we know for sure that $t_j$ is currently off). Therefore, for $1 \le j \leq m$ such that $inMask[j] \nsubseteq mask$ and $inMask[j] \; \& \; mask \neq 0$, we update the following: $dp[mask \; | \; inMask[j]][k + 1] = dp[mask \; | \; inMask[j]][k + 1] + dp[mask][k]$ $dp[mask \; | \; inMask[j]][k + 1] = dp[mask \; | \; inMask[j]][k + 1] + dp[mask][k]$ Turn on a currently-off vertex $t_j$ in a way that $mask$ is not expanded. Let $cnt(mask)$ be the number of indices j such that $inMask[j] \subseteq mask$. We can turn on one of the $cnt(mask) - k$ vertices that is currently off. Therefore, we update the following: $dp[mask][k + 1] = dp[mask][k + 1] + dp[mask][k] * (cnt(mask) - k)$ $dp[mask][k + 1] = dp[mask][k + 1] + dp[mask][k] * (cnt(mask) - k)$ To solve the general case, we can calculate the number of orders for each weakly connected component separately and then combine the result with some combinatorics formula. Complexity: $O(2^r * n^2)$, with $r$ the maximum number of vertices with no incoming vertices (number of vertices in set $S$) among all weakly connected component. We will prove that $r \leq \frac{X}{4}$ (where $X$ is the constraint of $n$ and $a_i$), therefore the algorithm fit the given time limit. Proof: For simplicity, assume that $X$ is divisible by $4$. Let's focus only on the weakly connected component $C$ with maximum number of vertices (which will equal $r$). Let's define $S$ and $T$ in the same manner as the above solution. Notice that, for all $x$ from $\frac{X}{2}$ to $X$, if $x$ in $S$, then $x$ is a separate weakly connected component. Therefore, all numbers in $S$ should range from $1$ to $\frac{X}{2}$. On another hand, there should be no number in $S$ that divide another one in $S$. In other word, consider the divisibility graph of all integer from $1$ to $\frac{X}{2}$. Therefore, the size of $S$ cannot exceed the size of the maximum anti-chain (a subset of vertices such that no pair of vertices is connected by an edge) of the graph. The size of the maximum anti-chain of the divisibility graph with vertices from $1$ to $n$ is $\frac{n}{2}$ (proof below). Therefore, the size of $S$ cannot exceed $\frac{\frac{X}{2}}{2} = \frac{X}{4}$, or $r \leq \frac{X}{4}$. $\blacksquare$ Though, for an anti-chain of the divisibility graph with $\frac{X}{2}$ vertices, even if we include all the numbers from $\frac{X}{2} + 1$ to $X$, it may happen that vertices of the anti-chain belong to different weakly connected component. In reality, our brute-force program figure out that in the worst case, $r = 11$ (achieved with $a = [2, 11, 13, \ldots, 27, 29, 30, 31, \ldots, 59, 60]$). We still need to prove that, for even $n$, the maximum anti-chain of the divisibility graph with vertices from $1$ to $n$ is $\frac{n}{2}$. Proof: For any number $x$, let $f(x)$ the number received by continuously divide $x$ by $2$. In other word, let $k$ the maximum value of $i$ such that $x$ is divisible by $2^i$, then $f(x) = \frac{x}{2^k}$. Notice that, for two number $x$ and $y$, if $f(x) = f(y)$ then $x$ divides $y$ or $y$ divides $x$. For all $x$ from $1$ to $n$, $f(x)$ has at most $\frac{n}{2}$ different value (all odd number from $1$ to $n-1$). For any subset $s$ of integers from $1$ to $n$, if $s$ has $\frac{n}{2} + 1$ elements or more, according to Pigeonhole principle, there are two elements in $s$ that have the same value of $f$. One of these two numbers will divide the other, so $s$ is not an anti-chain. $\blacksquare$
[ "bitmasks", "combinatorics", "dp" ]
3,500
MOD = 1000000007 def isSubset(a, b): return (a & b) == a def isIntersect(a, b): return (a & b) != 0 # Solve for each weakly connected component (WCC) def cntOrder(s, t): p = len(s) m = len(t) inMask = [0 for i in range(m)] for x in range(p): for i in range(m): if t[i] % s[x] == 0: inMask[i] |= 1 << x cnt = [0 for mask in range(1<<p)] for mask in range(1<<p): for i in range(m): if isSubset(inMask[i], mask): cnt[mask] += 1 dp = [[0 for mask in range(1<<p)] for k in range(m+1)] for i in range(m): dp[1][inMask[i]] += 1 for k in range(m): for mask in range(1<<p): for i in range(m): if not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask): dp[k+1][mask | inMask[i]] = (dp[k+1][mask | inMask[i]] + dp[k][mask]) % MOD dp[k+1][mask] = (dp[k+1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD return dp[m][(1<<p)-1] def dfs(u): global a, graph, degIn, visited, s, t visited[u] = True if degIn[u] == 0: s.append(a[u]) else: t.append(a[u]) for v in graph[u]: if not visited[v]: dfs(v) def main(): global a, graph, degIn, visited, s, t # Reading input n = int(input()) a = list(map(int, input().split())) # Pre-calculate C(n, k) c = [[0 for j in range(n)] for i in range(n)] for i in range(n): c[i][0] = 1 for j in range(1, i+1): c[i][j] = (c[i-1][j-1] + c[i-1][j]) % MOD # Building divisibility graph degIn = [0 for u in range(n)] graph = [[] for u in range(n)] for u in range(n): for v in range(n): if u != v and a[v] % a[u] == 0: graph[u].append(v) graph[v].append(u) degIn[v] += 1 # Solve for each WCC of divisibility graph and combine result ans = 1 curLen = 0 visited = [False for u in range(n)] for u in range(n): if not visited[u]: s = [] t = [] dfs(u) if len(t) > 0: sz = len(t) - 1 cnt = cntOrder(s, t) # Number of orders for current WCC ans = (ans * cnt) % MOD # Number of ways to insert <sz> number to array of <curLen> elements ans = (ans * c[curLen + sz][sz]) % MOD curLen += sz print(ans) if __name__ == "__main__": main()
1293
A
ConneR and the A.R.C. Markland-N
\begin{quote} Sakuzyo - Imprinting \end{quote} A.R.C. Markland-N is a tall building with $n$ floors numbered from $1$ to $n$. Between each two adjacent floors in the building, there is a staircase connecting them. It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal. ConneR's office is at floor $s$ of the building. On each floor (including floor $s$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $k$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there. CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant. Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
Since there's only $k$ closed restaurants, in the worst case we'll only have to walk for $k$ staircases only (one such case would be $s = n$ and all the restaurants from floor $s-k+1$ to $s$ are closed). Therefore, a brute force solution is possible: try out every distance $x$ from $0$ to $k$. For each, determine if either $s-x$ or $s+x$ is within range $[1, n]$ and not being in the closed list. The check of an element being a list or not can be done easily by a built-in function in most programming languages, for C++ it would be the "find" function with linear time complexity. Of course one would love to check with set/TreeSet, but for this problem it's an overkill. Time complexity: $\mathcal{O}(k^2)$.
[ "binary search", "brute force", "implementation" ]
1,100
T = int(input()) for test_no in range(T): n, s, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(0, k+1): if s-i >= 1 and not s-i in a: print(i); break if s+i <= n and not s+i in a: print(i); break else: assert(False) # if reached this line, the solution failed to find a free floor
1293
B
JOE is on TV!
\begin{quote} 3R2 - Standby for Action \end{quote} Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. $n$"! The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!). For each question JOE answers, if there are $s$ ($s > 0$) opponents remaining and $t$ ($0 \le t \le s$) of them make a mistake on it, JOE receives $\displaystyle\frac{t}{s}$ dollars, and consequently there will be $s - t$ opponents left for the next question. JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?
This is a greedy problem, with the optimal scenario being each question eliminating a single opponent. It is easy to see that we will want each question to eliminate one opponent only, since after each elimination, the ratio $t/s$ will be more and more rewarding (as $s$ lowers overtime) - as a result, each elimination should have the lowest possible $t$ (i.e. $t = 1$) so more opponents would have their rewards increased. Time complexity is $\mathcal{O}(n)$.
[ "combinatorics", "greedy", "math" ]
1,000
T = 1 for test_no in range(T): n = int(input()) ans = sum([1.0 / i for i in range(1, n+1)]) print(ans)
1294
A
Collecting Coins
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $a$ coins, Barbara has $b$ coins and Cerene has $c$ coins. Recently Polycarp has returned from the trip around the world and brought $n$ coins. He wants to distribute \textbf{all} these $n$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $A$ coins to Alice, $B$ coins to Barbara and $C$ coins to Cerene ($A+B+C=n$), then $a + A = b + B = c + C$. \textbf{Note} that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0. Your task is to find out if it is possible to distribute \textbf{all} $n$ coins between sisters in a way described above. You have to answer $t$ independent test cases.
Suppose $a \le b \le c$. If it isn't true then let's rearrange our variables. Then we need at least $2c - b - a$ coins to make $a$, $b$ and $c$ equal. So if $n < 2c - b - a$ then the answer is "NO". Otherwise, the answer if "YES" if the number $n - (2c - b - a)$ is divisible by $3$. This is true because after making $a, b$ and $c$ equal we need to distribute all remaining candies between three sisters.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int a[3], n; cin >> a[0] >> a[1] >> a[2] >> n; sort(a, a + 3); n -= 2 * a[2] - a[1] - a[0]; if (n < 0 || n % 3 != 0) { cout << "NO" << endl; } else { cout << "YES" << endl; } } return 0; }
1294
B
Collecting Packages
There is a robot in a warehouse and $n$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $(0, 0)$. The $i$-th package is at the point $(x_i, y_i)$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $(0, 0)$ doesn't contain a package. The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $(x, y)$ to the point ($x + 1, y$) or to the point $(x, y + 1)$. As we say above, the robot wants to collect all $n$ packages (\textbf{in arbitrary order}). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path. The string $s$ of length $n$ is lexicographically less than the string $t$ of length $n$ if there is some index $1 \le j \le n$ that for all $i$ from $1$ to $j-1$ $s_i = t_i$ and $s_j < t_j$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.
It is obvious that if there is a pair of points $(x_i, y_i)$ and $(x_j, y_j)$ such that $x_i < x_j$ and $y_i > y_j$ then the answer is "NO". It means that if the answer is "YES" then there is some ordering of points such that $x_{i_1} \le x_{i_2} \le \dots \le x_{i_n}$ and $y_{i_1} \le y_{i_2} \le \dots \le y_{i_n}$ because we can only move right or up. But what is this ordering? it is just sorted order of points (firstly by $x_i$ then by $y_i$). So we can sort all points, check if this ordering is valid and traverse among all these points. For each $k$ from $2$ to $n$ firstly do $x_{i_k} - x_{i_{k-1}}$ moves to the right then do $y_{i_k} - y_{i_{k-1}}$ moves to the up (because this order minimizing the answer lexicographically). Time complexity: $O(n \log n)$ or $O(n^2)$.
[ "implementation", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; for (int tt = 0; tt < t; tt++) { int n; cin >> n; vector<pair<int, int>> a(n); for (int i = 0; i < n; ++i) { cin >> a[i].first >> a[i].second; } sort(a.begin(), a.end()); pair<int, int> cur = make_pair(0, 0); string ans; bool ok = true; for (int i = 0; i < n; ++i) { int r = a[i].first - cur.first; int u = a[i].second - cur.second; if (r < 0 || u < 0) { cout << "NO" << endl; ok = false; break; } ans += string(r, 'R'); ans += string(u, 'U'); cur = a[i]; } if (ok) cout << "YES" << endl << ans << endl; } return 0; }
1294
C
Product of Three Numbers
You are given one integer number $n$. Find three \textbf{distinct integers} $a, b, c$ such that $2 \le a, b, c$ and $a \cdot b \cdot c = n$ or say that it is impossible to do it. If there are several answers, you can print any. You have to answer $t$ independent test cases.
Suppose $a < b < c$. Let's try to minimize $a$ and maximize $c$. Let $a$ be the minimum divisor of $n$ greater than $1$. Then let $b$ be the minimum divisor of $\frac{n}{a}$ that isn't equal $a$ and $1$. If $\frac{n}{ab}$ isn't equal $a$, $b$ and $1$ then the answer is "YES", otherwise the answer is "NO". Time complexity: $O(\sqrt{n})$ per query.
[ "greedy", "math", "number theory" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; set<int> used; for (int i = 2; i * i <= n; ++i) { if (n % i == 0 && !used.count(i)) { used.insert(i); n /= i; break; } } for (int i = 2; i * i <= n; ++i) { if (n % i == 0 && !used.count(i)) { used.insert(i); n /= i; break; } } if (int(used.size()) < 2 || used.count(n) || n == 1) { cout << "NO" << endl; } else { cout << "YES" << endl; used.insert(n); for (auto it : used) cout << it << " "; cout << endl; } } return 0; }
1294
D
MEX maximizing
Recall that \textbf{MEX} of an array is a \textbf{minimum non-negative integer} that does not belong to the array. Examples: - for the array $[0, 0, 1, 0, 2]$ MEX equals to $3$ because numbers $0, 1$ and $2$ are presented in the array and $3$ is the minimum non-negative integer not presented in the array; - for the array $[1, 2, 3, 4]$ MEX equals to $0$ because $0$ is the minimum non-negative integer not presented in the array; - for the array $[0, 1, 4, 3]$ MEX equals to $2$ because $2$ is the minimum non-negative integer not presented in the array. You are given an empty array $a=[]$ (in other words, a zero-length array). You are also given a positive integer $x$. You are also given $q$ queries. The $j$-th query consists of one integer $y_j$ and means that you have to append one element $y_j$ to the array. The array length increases by $1$ after a query. In one move, you can choose any index $i$ and set $a_i := a_i + x$ or $a_i := a_i - x$ (i.e. increase or decrease any element of the array by $x$). The only restriction is that \textbf{$a_i$ cannot become negative}. Since initially the array is empty, you can perform moves only after the first query. You have to maximize the \textbf{MEX} (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element). You have to find the answer after each of $q$ queries (i.e. the $j$-th answer corresponds to the array of length $j$). \textbf{Operations are discarded before each query. I.e. the array $a$ after the $j$-th query equals to $[y_1, y_2, \dots, y_j]$.}
Firstly, let's understand what the operation does. It changes the element but holds the remainder modulo $x$. So we can consider all elements modulo $x$. Let $cnt_0$ be the number of elements with the value $0$ modulo $x$, $cnt_1$ be the number of elements with the value $1$ modulo $x$, and so on. Let's understand, where is the "bottleneck" of MEX. Obviously, we can always fill exactly $min(cnt_0, cnt_1, \dots, cnt_{x - 1})$ full blocks, so MEX is at least $min(cnt_0, cnt_1, \dots, cnt_{x - 1}) \cdot x$. MEX will be among all elements $y \in [0; x - 1]$ such that $cnt_y = min(cnt_0, cnt_1, \dots, cnt_{x - 1})$. Among all such elements MEX will be the minimum such $y$. Let it be $mn$. So the final value of MEX is $cnt_{mn} \cdot x + mn$. How to deal with queries? Let's maintain the sorted set of pairs ($cnt_y, y$) for all $y \in [0; x - 1]$ and change it with respect to appended values. During each query let's change the set correspondingly and take the answer as the first element of this set using the formula above. Time complexity: $O(n \log n)$. There is also an easy linear solution that uses the same idea but in a different way.
[ "data structures", "greedy", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q, x; cin >> q >> x; vector<int> mods(x); set<pair<int, int>> vals; for (int i = 0; i < x; ++i) { vals.insert(make_pair(mods[i], i)); } for (int i = 0; i < q; ++i) { int cur; cin >> cur; cur %= x; vals.erase(make_pair(mods[cur], cur)); ++mods[cur]; vals.insert(make_pair(mods[cur], cur)); cout << vals.begin()->first * x + vals.begin()->second << endl; } return 0; }
1294
E
Obtain a Permutation
You are given a rectangular matrix of size $n \times m$ consisting of integers from $1$ to $2 \cdot 10^5$. In one move, you can: - choose \textbf{any element} of the matrix and change its value to \textbf{any} integer between $1$ and $n \cdot m$, inclusive; - take \textbf{any column} and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some $j$ ($1 \le j \le m$) and set $a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$ \textbf{simultaneously}. \begin{center} Example of cyclic shift of the first column \end{center} You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ (i.e. $a_{i, j} = (i - 1) \cdot m + j$) with the \textbf{minimum number of moves} performed.
At first, let's decrease all elements by one and solve the problem in $0$-indexation. The first observation is that we can solve the problem independently for each column. Consider the column $j$ $(j \in [0; m-1])$. It consists of elements $[j; m + j, 2m + j, \dots, (n-1)m + j]$. Now consider some element $a_{i, j}$ $(i \in [0; n - 1])$. We don't need to replace it with some other number in only one case: if we shift the column such that $a_{i, j}$ will coincide with the corresponding number of the required matrix. Obviously, there is only one cyclic shift of the column that can rid us of replacing $a_{i, j}$. So, the idea is the following: let's calculate for each cyclic shift the number of elements we don't need to replace if we use this cyclic shift. Let for the $i$-th cyclic shift ($0$-indexed) it be $cnt_i$. Then the answer for this column can be taken as $\min\limits_{i=0}^{n-1} n - cnt_i + i$. How to calculate for the element $a_{i, j}$ the corresponding cyclic shift? Firstly, if $a_{i, j} \% m \ne j$ ($\%$ is modulo operation) then there is no such cyclic shift. Otherwise, let $pos = \lfloor\frac{a_{i, j}}{m}\rfloor$. If $pos < n$ then there is such cyclic shift ($pos$ can be greater than or equal to $n$ because $a_{i, j}$ can be up to $2 \cdot 10^5$) and the number of such cyclic shift is $(i - pos + n) \% n$. So let's increase $cnt_{(i - pos + n) \% n}$ and continue. After considering all elements of this column take the answer by the formula above and go to the next column. Time complexity: $O(nm)$.
[ "greedy", "implementation", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int>(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; --a[i][j]; } } long long ans = 0; for (int j = 0; j < m; ++j) { vector<int> cnt(n); for (int i = 0; i < n; ++i) { if (a[i][j] % m == j) { int pos = a[i][j] / m; if (pos < n) { ++cnt[(i - pos + n) % n]; } } } int cur = n - cnt[0]; for (int i = 1; i < n; ++i) { cur = min(cur, n - cnt[i] + i); } ans += cur; } cout << ans << endl; return 0; }
1294
F
Three Paths on a Tree
You are given an unweighted tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles. Your task is to choose \textbf{three distinct} vertices $a, b, c$ on this tree such that the number of edges which belong to \textbf{at least} one of the simple paths between $a$ and $b$, $b$ and $c$, or $a$ and $c$ is the maximum possible. See the notes section for a better understanding. The simple path is the path that visits each vertex at most once.
There is some obvious dynamic programming solution that someone can describe in the comments, but I will describe another one, that, in my opinion, much easier to implement. Firstly, let's find some diameter of the tree. Let $a$ and $b$ be the endpoints of this diameter (and first two vertices of the answer). You can prove yourself why it is always good to take the diameter and why any diameter can be taken in the answer. Then there are two cases: the length of the diameter is $n-1$ or the length of the diameter is less than $n-1$. In the first case, you can take any other vertex as the third vertex of the answer $c$, it will not affect the answer anyway. Otherwise, we can run multi-source bfs from all vertices of the diameter and take the farthest vertex as the third vertex of the answer. It is always true because we can take any diameter and the farthest vertex will increase the answer as much as possible. Time complexity: $O(n)$.
[ "dfs and similar", "dp", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; #define x first #define y second vector<int> p; vector<vector<int>> g; pair<int, int> dfs(int v, int par = -1, int dist = 0) { p[v] = par; pair<int, int> res = make_pair(dist, v); for (auto to : g[v]) { if (to == par) continue; res = max(res, dfs(to, v, dist + 1)); } return res; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; p = vector<int>(n); g = vector<vector<int>>(n); for (int i = 0; i < n - 1; ++i) { int x, y; cin >> x >> y; --x, --y; g[x].push_back(y); g[y].push_back(x); } pair<int, int> da = dfs(0); pair<int, int> db = dfs(da.y); vector<int> diam; int v = db.y; while (v != da.y) { diam.push_back(v); v = p[v]; } diam.push_back(da.y); if (int(diam.size()) == n) { cout << n - 1 << " " << endl << diam[0] + 1 << " " << diam[1] + 1 << " " << diam.back() + 1 << endl; } else { queue<int> q; vector<int> d(n, -1); for (auto v : diam) { d[v] = 0; q.push(v); } while (!q.empty()) { int v = q.front(); q.pop(); for (auto to : g[v]) { if (d[to] == -1) { d[to] = d[v] + 1; q.push(to); } } } pair<int, int> mx = make_pair(d[0], 0); for (int v = 1; v < n; ++v) { mx = max(mx, make_pair(d[v], v)); } cout << int(diam.size()) - 1 + mx.x << endl << diam[0] + 1 << " " << mx.y + 1 << " " << diam.back() + 1 << endl; } return 0; }
1295
A
Display The Number
You have a large electronic screen which can display up to $998244353$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $7$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $10$ decimal digits: As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $1$, you have to turn on $2$ segments of the screen, and if you want to display $8$, all $7$ segments of some place to display a digit should be turned on. You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $n$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $n$ segments. Your program should be able to process $t$ different test cases.
First of all, we don't need to use any digits other than $1$ and $7$. If we use any other digit, it consists of $4$ or more segments, so it can be replaced by two $1$'s and the number will become greater. For the same reason we don't need to use more than one $7$: if we have two, we can replace them with three $1$'s. Obviously, it is always optimal to place $7$ before $1$. So our number is either a sequence of $1$'s, or a $7$ and a sequence of $1$'s. We should use $7$ only if $n$ is odd, because if $n$ is even, it will decrease the number of digits in the result.
[ "greedy" ]
900
t = int(input()) for i in range(t): n = int(input()) if(n % 2 == 1): print(7, end='') n -= 3 while(n > 0): print(1, end='') n -= 2 print()
1295
B
Infinite Prefixes
You are given string $s$ of length $n$ consisting of 0-s and 1-s. You build an infinite string $t$ as a concatenation of an infinite number of strings $s$, or $t = ssss \dots$ For example, if $s =$ 10010, then $t =$ 100101001010010... Calculate the number of prefixes of $t$ with balance equal to $x$. The balance of some string $q$ is equal to $cnt_{0, q} - cnt_{1, q}$, where $cnt_{0, q}$ is the number of occurrences of 0 in $q$, and $cnt_{1, q}$ is the number of occurrences of 1 in $q$. The number of such prefixes can be infinite; if it is so, you must say that. A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
Let's denote a prefix of length $i$ as $pref(i)$. We can note that each $pref(i) = k \cdot pref(n) + pref(i \mod n)$ where $k = \left\lfloor \frac{i}{n} \right\rfloor$ and $+$ is a concatenation. Then balance $bal(i)$ of prefix of length $i$ is equal to $k \cdot bal(n) + bal(i \mod n)$. Now there two cases: $bal(n)$ is equal to $0$ or not. If $bal(n) = 0$ then if exist such $j$ ($0 \le j < n$) that $bal(j) = x$ then for each $k \ge 0$ $bal(j + kn) = x$ and answer is $-1$. Otherwise, for each such $j$ there will no more than one possible $k$: since there are zero or one solution to the equation $bal(j) + k \cdot bal(n) = x$. The solution exists if and only if $x - bal(j) \equiv 0 \mod bal(n)$ and $k = \frac{x - bal(j)}{bal(n)} \ge 0$. So, just precalc $bal(n)$ and for each $0 \le j < n$ check the equation.
[ "math", "strings" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long li; int n, x; string s; inline bool read() { if(!(cin >> n >> x >> s)) return false; return true; } inline void solve() { int ans = 0; bool infAns = false; int cntZeros = (int)count(s.begin(), s.end(), '0'); int total = cntZeros - (n - cntZeros); int bal = 0; for(int i = 0; i < n; i++) { if(total == 0) { if(bal == x) infAns = true; } else if(abs(x - bal) % abs(total) == 0) { if((x - bal) / total >= 0) ans++; } if(s[i] == '0') bal++; else bal--; } if(infAns) ans = -1; cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int tc; cin >> tc; while(tc--) { read(); solve(); } return 0; }
1295
C
Obtain The String
You are given two strings $s$ and $t$ consisting of lowercase Latin letters. Also you have a string $z$ which is initially empty. You want string $z$ to be equal to string $t$. You can perform the following operation to achieve this: append any subsequence of $s$ at the end of string $z$. 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. For example, if $z = ac$, $s = abcde$, you may turn $z$ into following strings in one operation: - $z = acace$ (if we choose subsequence $ace$); - $z = acbcd$ (if we choose subsequence $bcd$); - $z = acbce$ (if we choose subsequence $bce$). Note that after this operation string $s$ doesn't change. Calculate the minimum number of such operations to turn string $z$ into string $t$.
The answer is $-1$ when in string $t$ there is a character that is not in string $s$. Otherwise let's precalculate the following array $nxt_{i, j}$ = minimum index $x$ from $i$ to $|s|$ such that $s_x = j$ (if there is no such index then $nxt_{i, j} = inf$). Now we can solve this problem by simple greed. Presume that now $z = t_0 t_1 \dots t_{i-1}$, and last taken symbol in $s$ is $s_{pos}$. Then there are two options: if $nxt_{pos, i} \neq inf$, then $i = i + 1$, $pos = nxt_{pos+1, i}$; if $nxt_{pos, i} = inf$, then $pos = 0$ and $ans = ans + 1$ ($ans$ is equal to $0$ initially);
[ "dp", "greedy", "strings" ]
1,600
#include<bits/stdc++.h> using namespace std; const int N = int(2e5) + 99; const int INF = int(1e9) + 99; int tc; string s, t; int nxt[N][26]; int main() { cin >> tc; while(tc--){ cin >> s >> t; for(int i = 0; i < s.size() + 5; ++i) for(int j = 0; j < 26; ++j) nxt[i][j] = INF; for(int i = int(s.size()) - 1; i >= 0; --i){ for(int j = 0; j < 26; ++j) nxt[i][j] = nxt[i + 1][j]; nxt[i][s[i] - 'a'] = i; } int res = 1, pos = 0; for(int i = 0; i < t.size(); ++i){ if(pos == s.size()){ pos = 0; ++res; } if(nxt[pos][t[i] - 'a'] == INF){ pos = 0; ++res; } if(nxt[pos][t[i] - 'a'] == INF && pos == 0){ res = INF; break; } pos = nxt[pos][t[i] - 'a'] + 1; } if(res >= INF) cout << -1 << endl; else cout << res << endl; } return 0; }
1295
D
Same GCDs
You are given two integers $a$ and $m$. Calculate the number of integers $x$ such that $0 \le x < m$ and $\gcd(a, m) = \gcd(a + x, m)$. Note: $\gcd(a, b)$ is the greatest common divisor of $a$ and $b$.
The Euclidean algorithm is based on the next fact: if $a \ge b$ then $\gcd(a, b) = \gcd(a - b, b)$. So, if $(a + x) \ge m$ then $\gcd(a + x, m) = \gcd(a + x - m, m)$. So we can declare that we are looking at $m$ different integers $x' = (a + x) \mod m$ with $0 \le x' < m$, so all $x'$ forms a segment $[0, m - 1]$. So, we need to find the number of $x'$ ($0 \le x' < m$) such that $\gcd(x', m) = \gcd(a, m)$. Let's denote $g = \gcd(a, m)$, then $a = ga'$ and $m = gm'$. So, $\gcd(a, m) = \gcd(ga', gm') = g \cdot \gcd(a', m') = g$ or $\gcd(a', m') = 1$. Since $\gcd(x', m) = \gcd(a, m) = g$ so we also can represent $x' = x^{"}g$ and, therefore $gcd(x^{"}, m') = 1$. Since $0 \le x' < m$, then $0 \le x^{"} < m'$ or we need to calaculate the number of $x^{"}$ ($0 \le x^{"} < m'$) such that $\gcd(x^{"}, m') = 1$. Since $gcd(0, m') = m' > 1$ so we can consider $x^{"} \in [1, m' - 1]$ and this is the definition of Euler's totient function $\varphi(m')$ which is the answer. Euler's totient function $\varphi(m')$ can be calculated using factorization of $m' = \prod\limits_{i=1}^{l}{p_i^{a_i}}$. Then $\varphi(m') = m' \prod\limits_{i=1}^{l}{(1 - \frac{1}{p_i})}$.
[ "math", "number theory" ]
1,800
fun gcd(a : Long, b : Long) : Long { return if (a == 0L) b else gcd(b % a, a) } fun phi(a : Long) : Long { var (tmp, ans) = listOf(a, a) var d = 2L while (d * d <= tmp) { var cnt = 0 while (tmp % d == 0L) { tmp /= d cnt++ } if (cnt > 0) ans -= ans / d d++ } if (tmp > 1L) ans -= ans / tmp return ans } fun main() { val t = readLine()!!.toInt() for (tc in 1..t) { val (a, m) = readLine()!!.split(' ').map { it.toLong() } println(phi(m / gcd(a, m))) } }
1295
E
Permutation Separation
You are given a permutation $p_1, p_2, \dots , p_n$ (an array where each integer from $1$ to $n$ appears exactly once). The weight of the $i$-th element of this permutation is $a_i$. At first, you separate your permutation into two \textbf{non-empty} sets — prefix and suffix. More formally, the first set contains elements $p_1, p_2, \dots , p_k$, the second — $p_{k+1}, p_{k+2}, \dots , p_n$, where $1 \le k < n$. After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay $a_i$ dollars to move the element $p_i$. Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met. For example, if $p = [3, 1, 2]$ and $a = [7, 1, 4]$, then the optimal strategy is: separate $p$ into two parts $[3, 1]$ and $[2]$ and then move the $2$-element into first set (it costs $4$). And if $p = [3, 5, 1, 6, 2, 4]$, $a = [9, 1, 9, 9, 1, 9]$, then the optimal strategy is: separate $p$ into two parts $[3, 5, 1]$ and $[6, 2, 4]$, and then move the $2$-element into first set (it costs $1$), and $5$-element into second set (it also costs $1$). Calculate the minimum number of dollars you have to spend.
"All elements in the left set smaller than all elements in the right set" means that there is such value $val$ that all elements from the first set less than $val$ and all elements from the second set are more or equal to $val$. So let's make a sweep line on $val$ from $1$ to $n + 1$ while trying to maintain all answers for each prefix $pos$. Let's maintain for each $pos$ the total cost $t[pos]$ to make sets "good" if we split the permutation $p$ on sets $[p_1, \dots, p_{pos}]$ and $[p_{pos} + 1, \dots, p_n]$ in such way that after transformations all elements in the first set less than $val$. It's easy to see that the total cost is equal to sum of weights $a_i$ where $i \le pos$ and $p_i \ge val$ and $a_i$ where $i > pos$ and $p_i < val$. So what will happen if we increase $val$ by $1$? Let's define the position of $p_k = val$ as $k$. For each $pos \ge k$ we don't need to move $p_k$ to the second set anymore, so we should make $t[pos] -= a_k$. On the other hand, for each $pos < k$ we need to move $p_k$ from the second set to the first one now, so we should make $t[pos] += a_k$. The answer will be equal to the $\min\limits_{1 \le pos < n}(t[pos])$. It means that we should handle two operations: add some value on the segment and ask minimum on the segment. So we can store all $t[pos]$ in pretty standart Segment Tree with "add on segment" and "minimum on segment" while iterating over $val$. So the total complexity is $O(n \log{n})$.
[ "data structures", "divide and conquer" ]
2,200
#include<bits/stdc++.h> using namespace std; const int N = int(2e5) + 99; int n; int p[N]; int rp[N]; int a[N]; long long b[N]; long long t[4 * N]; long long add[4 * N]; void build(int v, int l, int r){ if(r - l == 1){ t[v] = b[l]; return; } int mid = (l + r) / 2; build(v * 2 + 1, l, mid); build(v * 2 + 2, mid, r); t[v] = min(t[v * 2 + 1], t[v * 2 + 2]); } void push(int v, int l, int r){ if(add[v] != 0){ if(r - l > 1) for(int i = v+v+1; i < v+v+3; ++i){ add[i] += add[v]; t[i] += add[v]; } add[v] = 0; } } void upd(int v, int l, int r, int L, int R, int x){ if(L >= R) return; if(l == L && r == R){ add[v] += x; t[v] += x; push(v, l, r); return; } push(v, l, r); int mid = (l + r) / 2; upd(v * 2 + 1, l, mid, L, min(mid, R), x); upd(v * 2 + 2, mid, r, max(mid, L), R, x); t[v] = min(t[v * 2 + 1], t[v * 2 + 2]); } void upd(int l, int r, int x){ upd(0, 0, n, l, r, x); } long long get(int v, int l, int r, int L, int R){ if(L >= R) return 1e18; push(v, l, r); if(l == L && r == R) return t[v]; int mid = (l + r) / 2; return min(get(v * 2 + 1, l, mid, L, min(R, mid)), get(v * 2 + 2, mid, r, max(L, mid), R)); } long long get(int l, int r){ return get(0, 0, n, l, r); } int main() { scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%d", p + i); --p[i]; rp[p[i]] = i; } for(int i = 0; i < n; ++i) scanf("%d", a + i); b[0] = a[0]; for(int i = 1; i < n; ++i) b[i] = a[i] + b[i - 1]; build(0, 0, n); long long res = get(0, n - 1); //for(int i = 0; i < n; ++i) cout << get(i, i+1) << ' ';cout << endl; for(int i = 0; i < n; ++i){ int pos = rp[i]; upd(pos, n, -a[pos]); upd(0, pos, a[pos]); res = min(res, get(0, n - 1)); //for(int i = 0; i < n; ++i) cout << get(i, i+1) << ' ';cout << endl; } cout << res << endl; return 0; }
1295
F
Good Contest
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $n$ problems; and since the platform is very popular, $998244351$ coder from all over the world is going to solve them. For each problem, the authors estimated the number of people who would solve it: for the $i$-th problem, the number of accepted solutions will be between $l_i$ and $r_i$, inclusive. The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $(x, y)$ such that $x$ is located earlier in the contest ($x < y$), but the number of accepted solutions for $y$ is \textbf{strictly} greater. Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be \textbf{no} inversions in the problem order, assuming that for each problem $i$, any \textbf{integral} number of accepted solutions for it (between $l_i$ and $r_i$) is equally probable, and all these numbers are independent.
Model solution (slow, complicated and not cool): The naive solution is dynamic programming: let $dp_{i, x}$ be the probability that the first $i$ problems don't have any inversions, and the $i$-th one got $x$ accepted solutions. Let's somehow speed it up. For convenience, I will modify the variable denoting the maximum number of accepted solutions for each problem: $L_i = l_i$, $R_i = r_i + 1$; and I will also reverse the problem order, so that we don't want the number of solutions to decrease from problem to problem. We know that $dp_{i, x} = \frac{1}{R_i - L_i} \sum\limits_{j = 0}^{x} dp_{i - 1, j}$, if $x \in [L_i, R_i)$, and $dp_{i, x} = 0$ otherwise. Let's divide the whole segment between $0$ and $998244351$ into $O(n)$ segments with the values of $L_i$ and $R_i$ and analyse the behavior of $dp$ values on each such segment. Let $f_i(x) = dp_{i, x}$. If we consider the behavior of $f_i(x)$ on some segment we got, we can prove by induction that it is a polynomial of degree not exceeding $i$. All that is left is to carefully calculate and maintain these polynomials on segments. The main thing we will use to calculate the polynomials is interpolation. To transition from $f_i$ to $f_{i + 1}$, we will consider each segment separately, calculate the first several values of $f_{i + 1}$ on each segment (we need to calculate the sum $\sum\limits_{x = L}^{R} P(x)$ fast, if $P(x)$ is a polynomial, this can also be done with interpolation), and then interpolate it on the whole segment. This is actually slow (we have to interpolate at least $O(n^2)$ polynomials) and not easy to write. Let's consider a better solution. Participants' solution (much faster and easier to code): We will use combinatoric approach: instead of calculating probabilities, we will count all the non-descending sequences $(a_1, a_2, \dots, a_n)$ such that $i \in [L_i, R_i)$, and divide it by the number of all sequences without the non-descending condition (that is just $\prod_{i=1}^{n} R_i - L_i$). Let's again divide $[0, 998244353]$ into $O(n)$ segments using the points $L_i$, $R_i$, and enumerate these segments from left to right. If there are two neighboring values $a_i$ and $a_{i + 1}$, they either belong to the same segment, or the segment $a_{i + 1}$ belongs to is to the right of the segment $a_i$ belongs to. We could try to write the following dynamic programming solution: $cnt_{i, j}$ is the number of non-descending prefixes of the sequence such that there are $i$ elements in the prefix, and the last one belongs to segment $j$. It's easy to model transitions from $cnt_{i, j}$ to $cnt_{i + 1, k}$ where $k > j$, but we don't know how to model the transition to $cnt_{i + 1, j}$. Let's get rid of them altogether! We will introduce an additional constraint in our dynamic programming: $cnt_{i, j}$ is the number of prefixes of the sequence of length $i$ such that all elements on prefix belong to one of the first $j$ segments, but next element should not belong to it. The transitions in this dynamic programming are different: we iterate on the number of elements $k$ belonging to the next segment and transition into $cnt_{i + k, j + 1}$ (if possible). Calculating the number of ways to take $k$ elements from an interval $[L, R)$ in sorted order can be reduced to calculating the number of ways to compose $k$ as the sum of $R - L$ non-negative summands (order matters). We should be able to calculate binomial coefficients with fairly large $n$ and not so large $k$, but that's not really hard if we use the formula $\binom{n}{k} = \binom{n}{k - 1} \cdot \frac{n - k + 1}{k}$.
[ "combinatorics", "dp", "probabilities" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y) { if(y & 1) z = mul(z, x); x = mul(x, x); y >>= 1; } return z; } int inv(int x) { return binpow(x, MOD - 2); } int divide(int x, int y) { return mul(x, inv(y)); } typedef vector<int> poly; void norm(poly& p) { while(p.size() > 0 && p.back() == 0) p.pop_back(); } poly operator +(const poly& a, const poly& b) { poly c = a; while(c.size() < b.size()) c.push_back(0); for(int i = 0; i < b.size(); i++) c[i] = add(c[i], b[i]); norm(c); return c; } poly operator +(const poly& a, int b) { return a + poly(1, b); } poly operator +(int a, const poly& b) { return b + a; } poly operator *(const poly& a, int b) { poly c = a; for(int i = 0; i < c.size(); i++) c[i] = mul(c[i], b); norm(c); return c; } poly operator /(const poly& a, int b) { return a * inv(b); } poly operator *(const poly& a, const poly& b) { poly c(a.size() + b.size() - 1); for(int i = 0; i < a.size(); i++) for(int j = 0; j < b.size(); j++) c[i + j] = add(c[i + j], mul(a[i], b[j])); norm(c); return c; } poly interpolate(const vector<int>& x, const vector<int>& y) { int n = int(x.size()) - 1; vector<vector<int> > f(n + 1); f[0] = y; for(int i = 1; i <= n; i++) for(int j = 0; j <= n - i; j++) f[i].push_back(divide(add(f[i - 1][j + 1], -f[i - 1][j]), add(x[i + j], -x[j]))); poly cur = poly(1, 1); poly res; for(int i = 0; i <= n; i++) { res = res + cur * f[i][0]; cur = cur * poly({add(0, -x[i]), 1}); } return res; } int eval(const poly& a, int x) { int res = 0; for(int i = int(a.size()) - 1; i >= 0; i--) res = add(mul(res, x), a[i]); return res; } poly sumFromL(const poly& a, int L, int n) { vector<int> x; for(int i = 0; i <= n; i++) x.push_back(L + i); vector<int> y; int cur = 0; for(int i = 0; i <= n; i++) { cur = add(cur, eval(a, x[i])); y.push_back(cur); } return interpolate(x, y); } int sumOverSegment(const poly& a, int L, int R) { return eval(sumFromL(a, L, a.size()), R - 1); } int main() { int n; cin >> n; vector<int> L(n), R(n); for(int i = 0; i < n; i++) { cin >> L[i] >> R[i]; R[i]++; } reverse(L.begin(), L.end()); reverse(R.begin(), R.end()); vector<int> coord = {0, MOD - 2}; for(int i = 0; i < n; i++) { coord.push_back(L[i]); coord.push_back(R[i]); } sort(coord.begin(), coord.end()); coord.erase(unique(coord.begin(), coord.end()), coord.end()); vector<int> cL = coord, cR = coord; cL.pop_back(); cR.erase(cR.begin()); int cnt = coord.size() - 1; vector<poly> cur(cnt); for(int i = 0; i < cnt; i++) if(cL[i] >= L[0] && cR[i] <= R[0]) cur[i] = poly(1, inv(R[0] - L[0])); for(int i = 1; i < n; i++) { vector<poly> nxt(cnt); int curSum = 0; for(int j = 0; j < cnt; j++) { nxt[j] = sumFromL(cur[j], cL[j], i) + curSum; curSum = add(curSum, sumOverSegment(cur[j], cL[j], cR[j])); } for(int j = 0; j < cnt; j++) nxt[j] = nxt[j] * (cL[j] >= L[i] && cR[j] <= R[i] ? inv(R[i] - L[i]) : 0); cur = nxt; } int ans = 0; for(int i = 0; i < cnt; i++) ans = add(ans, sumOverSegment(cur[i], cL[i], cR[i])); cout << ans << endl; }
1296
A
Array with Odd Sum
You are given an array $a$ consisting of $n$ integers. In one move, you can choose two indices $1 \le i, j \le n$ such that $i \ne j$ and set $a_i := a_j$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $i$ and $j$ and replace $a_i$ with $a_j$). Your task is to say if it is possible to obtain an array with an odd (not divisible by $2$) sum of elements. You have to answer $t$ independent test cases.
Firstly, if the array already has an odd sum, the answer is "YES". Otherwise, we need to change the parity of the sum, so we need to change the parity of some number. We can do in only when we have at least one even number and at least one odd number. Otherwise, the answer is "NO".
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; int sum = 0; bool odd = false, even = false; for (int i = 0; i < n; ++i) { int x; cin >> x; sum += x; odd |= x % 2 != 0; even |= x % 2 == 0; } if (sum % 2 != 0 || (odd && even)) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
1296
B
Food Buying
Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some \textbf{positive integer number} $1 \le x \le s$, buy food that costs exactly $x$ burles and obtain $\lfloor\frac{x}{10}\rfloor$ burles as a cashback (in other words, Mishka spends $x$ burles and obtains $\lfloor\frac{x}{10}\rfloor$ back). The operation $\lfloor\frac{a}{b}\rfloor$ means $a$ divided by $b$ rounded down. It is guaranteed that you can always buy some food that costs $x$ for any possible value of $x$. Your task is to say the maximum number of burles Mishka can spend if he buys food optimally. For example, if Mishka has $s=19$ burles then the maximum number of burles he can spend is $21$. Firstly, he can spend $x=10$ burles, obtain $1$ burle as a cashback. Now he has $s=10$ burles, so can spend $x=10$ burles, obtain $1$ burle as a cashback and spend it too. You have to answer $t$ independent test cases.
Let's do the following greedy solution: it is obvious that when we buy food that costs exactly $10^k$ for $k \ge 1$, we don't lose any burles because of rounding. Let's take the maximum power of $10$ that is not greater than $s$ (let it be $10^c$), buy food that costs $10^c$ (and add this number to the answer) and add $10^{c-1}$ to $s$. Apply this process until $s < 10$ and then add $s$ to the answer. Time complexity: $O(\log s)$ per test case.
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int s; cin >> s; int ans = 0; int pw = 1000 * 1000 * 1000; while (s > 0) { while (s < pw) pw /= 10; ans += pw; s -= pw - pw / 10; } cout << ans << endl; } return 0; }
1296
C
Yet Another Walking Robot
There is a robot on a coordinate plane. Initially, the robot is located at the point $(0, 0)$. Its path is described as a string $s$ of length $n$ consisting of characters 'L', 'R', 'U', 'D'. Each of these characters corresponds to some move: - 'L' (left): means that the robot moves from the point $(x, y)$ to the point $(x - 1, y)$; - 'R' (right): means that the robot moves from the point $(x, y)$ to the point $(x + 1, y)$; - 'U' (up): means that the robot moves from the point $(x, y)$ to the point $(x, y + 1)$; - 'D' (down): means that the robot moves from the point $(x, y)$ to the point $(x, y - 1)$. The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove \textbf{any non-empty substring} of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point $(x_e, y_e)$, then after optimization (i.e. removing some single substring from $s$) the robot also ends its path at the point $(x_e, y_e)$. This optimization is a low-budget project so you need to remove \textbf{the shortest} possible \textbf{non-empty} substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string $s$). Recall that the substring of $s$ is such string that can be obtained from $s$ by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL". You have to answer $t$ independent test cases.
Formally, the problem asks you to remove the shortest cycle from the robot's path. Because the endpoint of the path cannot be changed, the number of 'L's should be equal to the number of 'R's and the same with 'U' and 'D'. How to find the shortest cycle? Let's create the associative array $vis$ (std::map for C++) which will say for each point of the path the maximum number of operations $i$ such that if we apply first $i$ operations we will stay at this point. Initially, this array will contain only the point $(0, 0)$ with the value $0$. Let's go over all characters of $s$ in order from left to right. Let the current point be $(x_i, y_i)$ (we applied first $i+1$ operations, $0$-indexed). If this point is in the array already, let's try to update the answer with the value $i - vis[(x_i, y_i)] + 1$ and left and right borders with values $vis[(x_i, y_i)]$ and $i$ correspondingly. Then let's assign $vis[(x_i, y_i)] := i + 1$ and continue. If there were no updates of the answer, the answer is -1. Otherwise, you can print any substring you found. Time complexity: $O(n \log n)$ per test case.
[ "data structures", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; string s; cin >> n >> s; int l = -1, r = n; map<pair<int, int>, int> vis; pair<int, int> cur = {0, 0}; vis[cur] = 0; for (int i = 0; i < n; ++i) { if (s[i] == 'L') --cur.first; if (s[i] == 'R') ++cur.first; if (s[i] == 'U') ++cur.second; if (s[i] == 'D') --cur.second; if (vis.count(cur)) { if (i - vis[cur] + 1 < r - l + 1) { l = vis[cur]; r = i; } } vis[cur] = i + 1; } if (l == -1) { cout << -1 << endl; } else { cout << l + 1 << " " << r + 1 << endl; } } return 0; }
1296
D
Fight with Monsters
There are $n$ monsters standing in a row numbered from $1$ to $n$. The $i$-th monster has $h_i$ health points (hp). You have your attack power equal to $a$ hp and your opponent has his attack power equal to $b$ hp. You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to $0$. The fight with a monster happens in turns. - You hit the monster by $a$ hp. If it is dead after your hit, \textbf{you gain one point} and you both proceed to the next monster. - Your opponent hits the monster by $b$ hp. If it is dead after his hit, \textbf{nobody gains a point} and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most $k$ times \textbf{in total} (for example, if there are two monsters and $k=4$, then you can use the technique $2$ times on the first monster and $1$ time on the second monster, but not $2$ times on the first monster and $3$ times on the second monster). Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.
Let's calculate the minimum number of secret technique uses we need to kill each of the monsters. Let the current monster has $h$ hp. Firstly, it is obvious that we can take $h$ modulo $a+b$ (except one case). If it becomes zero, let's "rollback" it by one pair of turns. Then the number of uses of the secret technique we need is $\lceil\frac{h}{a}\rceil - 1$. Let's sort all $n$ monsters by this value and take the "cheapest" set of monsters (prefix of the sorted array) with the sum of values less than or equal to $k$. Time complexity: $O(n \log n)$.
[ "greedy", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, a, b, k; cin >> n >> a >> b >> k; vector<int> h(n); for (int i = 0; i < n; ++i) { cin >> h[i]; h[i] %= a + b; if (h[i] == 0) h[i] += a + b; h[i] = ((h[i] + a - 1) / a) - 1; } sort(h.begin(), h.end()); int ans = 0; for (int i = 0; i < n; ++i) { if (k - h[i] < 0) break; ++ans; k -= h[i]; } cout << ans << endl; return 0; }
1296
E1
String Coloring (easy version)
\textbf{This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different}. You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to color \textbf{all} its characters \textbf{one of the two colors} (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$). After coloring, you can swap \textbf{any} two neighboring characters of the string that are colored \textbf{different} colors. You can perform such an operation arbitrary (possibly, zero) number of times. The goal is to make the string sorted, i.e. all characters should be in alphabetical order. Your task is to say if it is possible to color the given string so that after coloring it can become sorted by \textbf{some} sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.
Note that the actual problem is to divide the string into two subsequences that both of them are non-decreasing. You can note that this is true because you cannot the relative order of the elements colored in the same color, but you can write down subsequences of different colors in any order you want. In this problem, you can write the following dynamic programming: $dp_{pos, c_1, c_2}$ is $1$ if you can split the prefix of the string $s[1..pos]$ into two non-decreasing sequences such that the first one ends with the character $c_1$ and the second one - with $c_2$ (characters are numbered from $0$ to $25$), otherwise $dp_{pos, c_1, c_2}$ is zero. Initially, only $dp_{0, 0, 0} = 1$, other values are zeros. Transitions are very easy: if the current value of dp is $dp_{i, c_1, c_2}$ then we can make a transition to $dp_{i + 1, c, c_2}$ if $c \ge c_1$ and to $dp_{i + 1, c_1, c}$ if $c \ge c_2$. Then you can restore the answer by carrying parent values. But there is another very interesting solution. Let's go from left to right and carry two sequences $s_1$ and $s_2$. If the current character is not less than the last character of $s_1$ then let's append it to $s_1$, otherwise, if this character is not less than the last character of $s_2$ then append it to $s_2$, otherwise the answer is "NO". If the answer isn't "NO" then $s_1$ and $s_2$ are required sequences. The proof and other stuff will be in the editorial of the hard version. Time complexity: $O(n \cdot AL^2)$ or $O(n \cdot AL)$ or $O(n)$.
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; string res; char lst0 = 'a', lst1 = 'a'; for (int i = 0; i < n; ++i) { if (s[i] >= lst0) { res += '0'; lst0 = s[i]; } else if (s[i] >= lst1) { res += '1'; lst1 = s[i]; } else { cout << "NO" << endl; return 0; } } cout << "YES" << endl << res << endl; return 0; }
1296
E2
String Coloring (hard version)
\textbf{This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different}. You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to color \textbf{all} its characters \textbf{the minimum number of colors} (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$). After coloring, you can swap \textbf{any} two neighboring characters of the string that are colored \textbf{different} colors. You can perform such an operation arbitrary (possibly, zero) number of times. The goal is to make the string sorted, i.e. all characters should be in alphabetical order. Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by \textbf{some} sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.
The solution of this problem is based on Dilworth's theorem. You can read about it on Wikipedia. In two words, this theorem says that the minimum number of non-decreasing sequences we need to cover the whole sequence equals the length of longest decreasing subsequence. Let's calculate the dynamic programming $dp_i$ - the length of longest decreasing sequence that ends in the position $i$. To recalculate this dynamic, let's carry the array $maxdp$ of length $26$, where $maxdp_c$ means the maximum value of $dp$ for the character $c$ on the prefix we already considered. So, initially all $dp_i$ are ones, all values of $maxdp$ are zeros. For the position $i$ we update $dp_i$ with $max(maxdp_{s_i + 1}, maxdp_{s_i + 2}, \dots, maxdp_{25}) + 1$ and update $maxdp_{s_i}$ with $dp_i$. Okay, how to restore the answer? That's pretty easy. The color of the $i$-th character is exactly $dp_i$. Why it is so? If $dp_i$ becomes greater than $max(maxdp_{s_i + 1}, maxdp_{s_i + 2}, \dots, maxdp_{25})$ then we surely need to use the new color for this character because we cannot append it to the end of any existing sequence. Otherwise, we will append it to some existing sequence (with the maximum possible number) and because it has the maximum number and we didn't update the value of $dp$ with the number of this sequence plus one, the current character is not less than the last in this sequence. Time complexity: $O(n \cdot AL)$ or $O(n \log n)$.
[ "data structures", "dp" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; vector<int> maxdp(26); vector<int> dp(n, 1); for (int i = 0; i < n; ++i) { for (int c = 25; c > s[i] - 'a'; --c) { dp[i] = max(dp[i], maxdp[c] + 1); } maxdp[s[i] - 'a'] = max(maxdp[s[i] - 'a'], dp[i]); } cout << *max_element(maxdp.begin(), maxdp.end()) << endl; for (int i = 0; i < n; ++i) cout << dp[i] << " "; cout << endl; return 0; }
1296
F
Berland Beauty
There are $n$ railway stations in Berland. They are connected to each other by $n-1$ railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the $n-1$ sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from $1$ to $10^6$ inclusive. You asked $m$ passengers some questions: the $j$-th one told you three values: - his departure station $a_j$; - his arrival station $b_j$; - minimum scenery beauty along the path from $a_j$ to $b_j$ (the train is moving along the shortest path from $a_j$ to $b_j$). You are planning to update the map and set some value $f_i$ on each railway section — the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values $f_1, f_2, \dots, f_{n-1}$, which the passengers' answer is consistent with or report that it doesn't exist.
Firstly, let's precalculate $n$ arrays $p_1, p_2, \dots, p_n$. The array $p_v$ is the array of "parents" if we run dfs from the vertex $v$. So, $p_{v, u}$ is the vertex that is the previous one before $u$ on the directed path $(v, u)$. This part can be precalculated in time $O(n^2)$ and we need it just for convenience. Initially, all values $f_j$ (beauties of the edges) are zeros. Let's consider queries in order of non-decreasing $g_i$. For the current query, let's consider the whole path $(a_i, b_i)$ and update the value $f_j$ for each $j$ on this path in the following way: $f_j = max(f_j, g_i)$. After processing all queries, let's replace all values $f_j = 0$ with $f_j = 10^6$. This part works also in time $O(n^2)$. And the last part of the solution is to check if the data we constructed isn't contradictory. We can iterate over all paths $(a_i, b_i)$ and find the minimum value $f_j$ on this path. We have to sure if it equals $g_i$. If it isn't true for at least one query, then the answer is -1. Otherwise, we can print the resulting tree. Time complexity: $O(n^2)$, but it can be done in at least $O(n \log n)$ (I hope someone can explain this solution because I am too lazy to do it now).
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> val; vector<vector<pair<int, int>>> g; void dfs(int v, int pv, int pe, vector<pair<int, int>> &p) { p[v] = make_pair(pv, pe); for (auto it : g[v]) { int to = it.first; int idx = it.second; if (to == pv) continue; dfs(to, v, idx, p); } } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif cin >> n; g = vector<vector<pair<int, int>>>(n); for (int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; --u, --v; g[u].push_back(make_pair(v, i)); g[v].push_back(make_pair(u, i)); } vector<vector<pair<int, int>>> p(n, vector<pair<int, int>>(n)); for (int i = 0; i < n; ++i) { dfs(i, -1, -1, p[i]); } val = vector<int>(n - 1, 1000000); cin >> m; vector<pair<pair<int, int>, int>> q(m); for (int i = 0; i < m; ++i) { cin >> q[i].first.first >> q[i].first.second >> q[i].second; --q[i].first.first; --q[i].first.second; } sort(q.begin(), q.end(), [&](pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) { return a.second < b.second; }); for (int i = 0; i < m; ++i) { int u = q[i].first.first; int v = q[i].first.second; while (v != u) { int pv = p[u][v].first; int pe = p[u][v].second; val[pe] = q[i].second; v = pv; } } for (int i = 0; i < m; ++i) { int u = q[i].first.first; int v = q[i].first.second; int mx = 1000000; while (v != u) { int pv = p[u][v].first; int pe = p[u][v].second; mx = min(mx, val[pe]); v = pv; } if (mx != q[i].second) { cout << -1 << endl; return 0; } } for (int i = 0; i < n - 1; ++i) { cout << val[i] << " "; } cout << endl; return 0; }
1299
A
Anu Has a Function
Anu has created her own function $f$: $f(x, y) = (x | y) - y$ where $|$ denotes the bitwise OR operation. For example, $f(11, 6) = (11|6) - 6 = 15 - 6 = 9$. It can be proved that for any nonnegative numbers $x$ and $y$ value of $f(x, y)$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems. A value of an array $[a_1, a_2, \dots, a_n]$ is defined as $f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$ (see notes). You are given an array with \textbf{not necessarily distinct} elements. How should you reorder its elements so that the value of the array is maximal possible?
If you work on the bits, you may see $f(a, b)$ can easily be written as $a \& (\sim b)$. And so, value of an array $[a_1, a_2, \dots, a_n]$ would be $a_1 \& (\sim a_2) \& \dots (\sim a_n)$, meaning that if we are to reorder, only the first element matters. By keeping prefix and suffix $AND$ after we apply $\sim$ to the given array, we can find $(\sim a_2) \& \dots (\sim a_n)$ in $O(1)$. Or notice that if a bit was to be in the answer, it must be in $a_1$ and not in any of $a_2, a_3, \dots a_n$. So you can start from the most significant bit and check if that bit can be in the answer to find $a_1$, resulting in $O(n)$.
[ "brute force", "greedy", "math" ]
1,500
null
1299
B
Aerodynamic
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a \textbf{strictly convex} (i. e. no three points are collinear) polygon $P$ which is defined by coordinates of its vertices. Define $P(x,y)$ as a polygon obtained by translating $P$ by vector $\overrightarrow {(x,y)}$. The picture below depicts an example of the translation: Define $T$ as a set of points which is the union of all $P(x,y)$ such that the origin $(0,0)$ lies in $P(x,y)$ (both strictly inside and on the boundary). There is also an equivalent definition: a point $(x,y)$ lies in $T$ only if there are two points $A,B$ in $P$ such that $\overrightarrow {AB} = \overrightarrow {(x,y)}$. One can prove $T$ is a polygon too. For example, if $P$ is a regular triangle then $T$ is a regular hexagon. At the picture below $P$ is drawn in black and some $P(x,y)$ which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if $P$ and $T$ are similar. Your task is to check whether the polygons $P$ and $T$ are similar.
$T$ has the central symmetry: indeed, if $P(x,y)$ covers $(0,0)$ and $(x_0,y_0)$ then $P(x-x_0,y-y_0)$ covers $(-x_0,-y_0)$ and $(0,0)$. So the answer for polygons which don't have the sentral symmetry is NO. Let's prove if $P$ has the central symmetry then the answer is YES. Translate $P$ in such a way that the origin becomes its center of symmetry. Let's show that the homothety with the center at the origin and the coefficient $2$ transforms $P$ into $T$: if a point $(x_0,y_0)$ lies in $P$, then $P(x_0,y_0)$ covers both $(0,0)$ and $(2x_0,2y_0)$; if a point $(x_0,y_0)$ doesn't lie in $P$, then consider a segment connecting the center of symmetry of the polygon $P$ (also known as origin) and $(x_0,y_0)$; it crosses some side of $P$; WLOG, assume this side is parallel to the $x$-axis and lies in the line $y=y_1, y_1>0$ (otherwise we can rotate the plane). Since the polygon is convex, it completely lies in the stripe $y \in [-y_1;y_1]$, that's why there isn't any vector which connects two points in $P$ with a $y$-coordinate greater than $2y_1$. Since $2y_0 > 2y_1$, there isn't any vector which connects two points in $P$ with a $y$-coordinate equal to $2y_0$, that's why the point $(2x_0,2y_0)$ doesn't lie in $T$. To find whether a polygon has the central symmetry, check whether the midpoints of segments connecting the opposite vertexes coincide; if a polygon has an odd number of vertexes it can't have the central symmetry.
[ "geometry" ]
1,800
null
1299
C
Water Balance
There are $n$ water tanks in a row, $i$-th of them contains $a_i$ liters of water. The tanks are numbered from $1$ to $n$ from left to right. You can perform the following operation: choose some subsegment $[l, r]$ ($1\le l \le r \le n$), and redistribute water in tanks $l, l+1, \dots, r$ evenly. In other words, replace each of $a_l, a_{l+1}, \dots, a_r$ by $\frac{a_l + a_{l+1} + \dots + a_r}{r-l+1}$. For example, if for volumes $[1, 3, 6, 7]$ you choose $l = 2, r = 3$, new volumes of water will be $[1, 4.5, 4.5, 7]$. \textbf{You can perform this operation any number of times}. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence $a$ is lexicographically smaller than a sequence $b$ of the same length if and only if the following holds: in the first (leftmost) position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.
Let's try to make the operation simpler. When we apply the operation, only the sum of the segment matters. And so let's instead define the operation on prefix sum array: Replace each of $p_l, p_{l+1}, \dots, p_r$ by $p_i = p_{l-1} + \frac{p_r - p_{l - 1} }{r-l+1} \cdot (i - l + 1)$. You may see how similar it is to a line function. Hence we get the idea to plot points $(i, p_i)$ ($(0, p_0 = 0)$ included), and our operation is just drawing a line between $2$ points on integer $x$ coordinates. Nicely if sequence $a$ is lexicographically smaller than sequence $b$, then prefix sum array of $a$ is smaller than prefix sum array of $b$. So we need to find the lexicographically smallest array $p$. And then it is easy to see the lexicographically smallest sequence $p$ will be the lower part of the convex hull. If you're interested you can solve IMO 2018 SL A4 by plotting similar points. I have written my solutionhere
[ "data structures", "geometry", "greedy" ]
2,100
null
1299
D
Around the World
Guy-Manuel and Thomas are planning $144$ trips around the world. You are given a simple weighted undirected connected graph with $n$ vertexes and $m$ edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than $3$ which passes through the vertex $1$. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it. But the trips with cost $0$ aren't exciting. You may choose any subset of edges incident to the vertex $1$ and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to $0$ which passes through the vertex $1$ in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo $10^9+7$.
It's common knowledge that in an undirected graph there is some subset (not necessarily unique) of simple cycles called basis such that any Eulerian subgraph (in connected graphs also known as a cyclic path) is a xor-combination of exactly one subset of basis cycles. In a given connected graph consider any spanning tree; any edge which isn't in that spanning tree forms a cycle with some tree's edges of some cost $c$. These cycles form the basis. A cost of a cyclic path is an XOR of costs of basis cycles that form this path. Now we can move from cycle space to the space of $5$-dimensional vectors $\mathbb{Z}_2^5$. If the costs of basis cycles are linear dependent, then there is a cycle of cost $0$, else they form the basis of some subspace of $\mathbb{Z}_2^5$. In the given graph there are two types of "components" connected to $1$, and after removing the edges each component contributes some subspace (possibly an empty one); these subspaces shouldn't intersect. These two types are components connected with an edge and components connected with two edges: In the first picture, the basis cycles are formed by the blue edges. We can cut the edge incident to $1$ or keep it; if we don't cut that edge, this component contributes a subspace formed by costs of basis cycles unless they are linear dependent, else it contributes the empty subspace. In the second picture, the basis cycles are formed by the blue edges and the red edge. We can cut both edges, and then this component contributes an empty subspace; if we cut one edge, the red edge moves to the spanning tree and no longer form a basis cycle, so this component contributes a subspace formed by costs of basis cycles formed by blue edges; if we don't cut any edges, then this component contributes a subspace formed by costs of basis cycles formed by blue and red edges. If any choice leads to keeping a set of linear dependent basis cycles' costs, then this choice is invalid. Now for every component, we have from $1$ to $4$ valid choices of choosing the contributing subspace. There are $374$ subspaces of $\mathbb{Z}_2^5$, which can be precalculated as well as their sums. Now we can calculate a dp $dp_{i,j}$ - the number of ways to get the subspace $j$ using the first $i$ components. The transitions are obvious: if we can get the subspace $X$ at the $i$-th component, then for each existing subspace $Y$, if $X$ and $Y$ don't intersect, do $dp_{i,X+Y} := dp_{i,X+Y} + dp_{i-1,Y}$, where $X+Y$ is the sum of subspaces. The answer is a sum of dp values for the last component.
[ "bitmasks", "combinatorics", "dfs and similar", "dp", "graphs", "math", "trees" ]
3,000
null
1299
E
So Mean
\textbf{This problem is interactive}. We have hidden a permutation $p_1, p_2, \dots, p_n$ of numbers from $1$ to $n$ from you, where $n$ \textbf{is even}. You can try to guess it using the following queries: $?$ $k$ $a_1$ $a_2$ $\dots$ $a_k$. In response, you will learn if the average of elements with indexes $a_1, a_2, \dots, a_k$ is an integer. In other words, you will receive $1$ if $\frac{p_{a_1} + p_{a_2} + \dots + p_{a_k}}{k}$ is integer, and $0$ otherwise. You have to guess the permutation. You can ask \textbf{not more than $18n$ queries}. Note that permutations $[p_1, p_2, \dots, p_k]$ and $[n + 1 - p_1, n + 1 - p_2, \dots, n + 1 - p_k]$ are indistinguishable. Therefore, \textbf{you are guaranteed that $p_1 \le \frac{n}{2}$}. Note that the permutation $p$ is fixed before the start of the interaction and doesn't depend on your queries. In other words, \textbf{interactor is not adaptive}. Note that you don't have to minimize the number of queries.
Let's solve this problem in several steps. First, let's ask a query about each group of $n-1$ numbers. Note that $1 + 2 + \dots + (i-1) + (i+1) + \dots + n = \frac{n(n+1)}{2} - i \equiv \frac{1\cdot 2}{2} - i \bmod (n-1)$. Therefore, answer will be YES only for numbers $1$ and $n$. Find the positions where $1$ and $n$ lie, assign one of them to be $1$ and the other one to be $n$ (it doesn't matter how to assign $1$ and $n$ to these $2$ spots, as permutations $[p_1, p_2, \dots, p_k]$ and $[n + 1 - p_1, n + 1 - p_2, \dots, n + 1 - p_k]$ are indistinguishable). $n$ queries. First, let's ask a query about each group of $n-1$ numbers. Note that $1 + 2 + \dots + (i-1) + (i+1) + \dots + n = \frac{n(n+1)}{2} - i \equiv \frac{1\cdot 2}{2} - i \bmod (n-1)$. Therefore, answer will be YES only for numbers $1$ and $n$. Find the positions where $1$ and $n$ lie, assign one of them to be $1$ and the other one to be $n$ (it doesn't matter how to assign $1$ and $n$ to these $2$ spots, as permutations $[p_1, p_2, \dots, p_k]$ and $[n + 1 - p_1, n + 1 - p_2, \dots, n + 1 - p_k]$ are indistinguishable). $n$ queries. Note that knowing $1$, we can find parity of every other number. Indeed, just ask about $1$ and $p_i$, if answer is YES, $p_i$ is odd, else it is even. $n$ queries. Note that knowing $1$, we can find parity of every other number. Indeed, just ask about $1$ and $p_i$, if answer is YES, $p_i$ is odd, else it is even. $n$ queries. Suppose that we have found numbers $1, 2, \dots, k, n-k+1, n-k+2, \dots, n$ at some point. Let's find numbers $k+1$ and $n-k$. Consider all numbers except $1, 2, \dots, k, n-k+1, n-k+2, \dots, n$ now. Ask a query about each subset of $n - 2k - 1$ numbers among them. Again, we can see that we will get answer YES only when we omit $k+1$ and $n-k$. Indeed, $k+1 + \dots (i-1) + (i+1) + \dots + (n-k) = k\cdot (n - 2k - 1) + \frac{(n-2k)(n-2k+1)}{2} - (i-k) \equiv 1 - (i-k) \bmod (n-2k-1)$, which is $0$ only for $i = k+1$ and $n-k$. Now that we know parities of all numbers, we can distinguish between $k+1$ and $n-k$. So, we determined $k+1$ and $n-k$ in $n - 2k$ queries. Suppose that we have found numbers $1, 2, \dots, k, n-k+1, n-k+2, \dots, n$ at some point. Let's find numbers $k+1$ and $n-k$. Consider all numbers except $1, 2, \dots, k, n-k+1, n-k+2, \dots, n$ now. Ask a query about each subset of $n - 2k - 1$ numbers among them. Again, we can see that we will get answer YES only when we omit $k+1$ and $n-k$. Indeed, $k+1 + \dots (i-1) + (i+1) + \dots + (n-k) = k\cdot (n - 2k - 1) + \frac{(n-2k)(n-2k+1)}{2} - (i-k) \equiv 1 - (i-k) \bmod (n-2k-1)$, which is $0$ only for $i = k+1$ and $n-k$. Now that we know parities of all numbers, we can distinguish between $k+1$ and $n-k$. So, we determined $k+1$ and $n-k$ in $n - 2k$ queries. Note that this already means that we can solve our problem in $n + n + (n - 2) + (n - 4) + (n - 6) \dots + (n - (n-2))$ queries, which is $\frac{n^2 + 6n}{4}$ queries. Unfortunately, this is much larger than we are allowed. However, we will use this method for $n\le 8$. Note that this already means that we can solve our problem in $n + n + (n - 2) + (n - 4) + (n - 6) \dots + (n - (n-2))$ queries, which is $\frac{n^2 + 6n}{4}$ queries. Unfortunately, this is much larger than we are allowed. However, we will use this method for $n\le 8$. Let's use the procedure above to find numbers $1, 2, 3, 4, n-3, n-2, n-1, n$. We have used $5n - 12$ queries by now, but let's round this up to $5n$. Now, we are going to find the remainders of each element of permutation modulo $3$, $5$, $7$, $8$. As $3\cdot 5 \cdot 7 \cdot 8 = 840 \ge 800 \ge n$, we will be able to restore each number uniquely. Let's use the procedure above to find numbers $1, 2, 3, 4, n-3, n-2, n-1, n$. We have used $5n - 12$ queries by now, but let's round this up to $5n$. Now, we are going to find the remainders of each element of permutation modulo $3$, $5$, $7$, $8$. As $3\cdot 5 \cdot 7 \cdot 8 = 840 \ge 800 \ge n$, we will be able to restore each number uniquely. To find remainders modulo $3$, we will first ask each number with already found $1$ and $2$. We will get YES only for numbers, divisible by $3$. Next, we will ask each number whose remainder under division by $3$ we haven't yet found with $1$, $3$. This way we find all the numbers which give the remainder $2$. All others give the remainder $1$. We spend $n + \frac{2n}{3}$ queries. To find remainders modulo $3$, we will first ask each number with already found $1$ and $2$. We will get YES only for numbers, divisible by $3$. Next, we will ask each number whose remainder under division by $3$ we haven't yet found with $1$, $3$. This way we find all the numbers which give the remainder $2$. All others give the remainder $1$. We spend $n + \frac{2n}{3}$ queries. Similarly, we find remainders mod $5$ and mod $7$. For mod $5$, at step $i$ ask each number whose remainder we don't know yet with $n, n-2, n-3, i$ (for $i$ from $1$ to $4$). We spend $n + \frac{4n}{5} + \frac{3n}{5} + \frac{2n}{5}$ queries. For mod $7$, first ask all numbers whose remainders we don't know yet with $\{1, 2, 3, n-3, n-2, n-1\}$, then with $\{1, 2, 3, n-3, n-2, n\}$, $\{1, 2, 3, n-3, n-1, n\}$, $\{1, 2, 3, n-2, n-1, n\}$, $\{1, 2, 4, n-2, n-1, n\}$, $\{1, 3, 4, n-2, n-1, n\}$ (sums of all these sets are different mod $7$). We spend $n + \frac{6n}{7} + \dots + \frac{2n}{7}$ queries. Similarly, we find remainders mod $5$ and mod $7$. For mod $5$, at step $i$ ask each number whose remainder we don't know yet with $n, n-2, n-3, i$ (for $i$ from $1$ to $4$). We spend $n + \frac{4n}{5} + \frac{3n}{5} + \frac{2n}{5}$ queries. For mod $7$, first ask all numbers whose remainders we don't know yet with $\{1, 2, 3, n-3, n-2, n-1\}$, then with $\{1, 2, 3, n-3, n-2, n\}$, $\{1, 2, 3, n-3, n-1, n\}$, $\{1, 2, 3, n-2, n-1, n\}$, $\{1, 2, 4, n-2, n-1, n\}$, $\{1, 3, 4, n-2, n-1, n\}$ (sums of all these sets are different mod $7$). We spend $n + \frac{6n}{7} + \dots + \frac{2n}{7}$ queries. Now time to find remainders mod $4$. We already know all remainders mod $2$. To distinguish $4k$ from $4k+2$, ask with $1, 2, 3$. To distinguish $4k+1$ from $4k+3$, ask with $1, 2, 4$. We spend $n$ queries. Now time to find remainders mod $8$. We already know all remainders mod $4$. Similarly, to distinguish $8k$ from $8k+4$, ask with $n, n-1, n-2, n-3, 1, 2, 3$, $\dots$, to distinguish $8k+3$ from $8k+7$, ask with $n, n-1, n-2, n-3, 1, 2, 4$. We spend $n$ queries. Now time to find remainders mod $4$. We already know all remainders mod $2$. To distinguish $4k$ from $4k+2$, ask with $1, 2, 3$. To distinguish $4k+1$ from $4k+3$, ask with $1, 2, 4$. We spend $n$ queries. Now time to find remainders mod $8$. We already know all remainders mod $4$. Similarly, to distinguish $8k$ from $8k+4$, ask with $n, n-1, n-2, n-3, 1, 2, 3$, $\dots$, to distinguish $8k+3$ from $8k+7$, ask with $n, n-1, n-2, n-3, 1, 2, 4$. We spend $n$ queries. Overall, we spend $5n + (n + \frac{2n}{3}) + (n + \frac{4n}{5} + \frac{3n}{5} + \frac{2n}{5}) + (n + \frac{6n}{7} + \dots + \frac{2n}{7}) + n + n \sim 15.324 n$. Note that this bound is easy to optimize (for example, determine all remainders mod $3$ and $4$ from $1, 2, n, n-1$, and after that check only candidates which work mod $12$ in phase $5$. This will reduce the number of operations to $13.66 n$ operations. Of course, a lot of other optimizations are possible.
[ "interactive", "math" ]
3,400
null
1300
A
Non-zero
Guy-Manuel and Thomas have an array $a$ of $n$ integers [$a_1, a_2, \dots, a_n$]. In one step they can add $1$ to any element of the array. Formally, in one step they can choose any integer index $i$ ($1 \le i \le n$) and do $a_i := a_i + 1$. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time. What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array \textbf{different from zero}? Formally, find the minimum number of steps to make $a_1 + a_2 +$ $\dots$ $+ a_n \ne 0$ and $a_1 \cdot a_2 \cdot$ $\dots$ $\cdot a_n \ne 0$.
While there are any zeros in the array, the product will be zero, so we should add $1$ to each zero. Now, if the sum is zero, we should add $1$ to any positive number, so the sum becomes nonzero. So the answer is the number of zeroes in the array plus $1$ if the sum of numbers is equal to zero after adding $1$ to zeros.
[ "implementation", "math" ]
800
null
1300
B
Assigning to Classes
\textbf{Reminder: the median} of the array $[a_1, a_2, \dots, a_{2k+1}]$ of odd number of elements is defined as follows: let $[b_1, b_2, \dots, b_{2k+1}]$ be the elements of the array in the sorted order. Then median of this array is equal to $b_{k+1}$. There are $2n$ students, the $i$-th student has skill level $a_i$. It's \textbf{not guaranteed} that all skill levels are distinct. Let's define \textbf{skill level of a class} as the median of skill levels of students of the class. As a principal of the school, you would like to assign each student to one of the $2$ classes such that each class has \textbf{odd number of students} (not divisible by $2$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized. What is the minimum possible absolute difference you can achieve?
Let's sort the array. From now on, $a_1 \le a_2 \dots \le a_{2n}$. Consider any partition. Suppose that the first class has $2k+1$ students, and the skill level of this class is $a_i$, and the second class had $2l+1$ students, and the skill level of this class is $a_j$, where $(2k + 1) + (2l + 1) = 2n \implies k + l = n-1$. Without losing generality, $i<j$. At least $n+1$ students have skill level at least $a_i$. Indeed, as $a_i$ is a median of his class, he and $k$ other students have skill level at least $a_i$. As $a_j\ge a_i$ and at least $l$ other students of the second class have skill level at least $a_j\ge a_i$, we get at least $k + l + 2 = n + 1$ students (including $a_i$) with skill level at least $a_i$. Therefore, $a_i\le a_n$. Similarly, we get that at least $n + 1$ students have skill level at most $a_j$. Therefore, $a_j\ge a_{n+1}$. So, $|a_j - a_i| \ge a_{n+1} - a_n$. However, $a_{n+1} - a_n$ is achievable. Let's put student $a_n$ into the class alone, and all other students into other class. $a_{n+1}$ will be the median skill level of that class, so the absolute difference will be exactly $a_{n+1} - a_n$. Therefore, it's enough to sort the array and to output the difference between two middle elements.
[ "greedy", "implementation", "sortings" ]
1,000
null
1301
A
Three Strings
You are given three strings $a$, $b$ and $c$ of the same length $n$. The strings consist of lowercase English letters only. The $i$-th letter of $a$ is $a_i$, the $i$-th letter of $b$ is $b_i$, the $i$-th letter of $c$ is $c_i$. For every $i$ ($1 \leq i \leq n$) you \textbf{must} swap (i.e. exchange) $c_i$ with either $a_i$ or $b_i$. So in total you'll perform exactly $n$ swap operations, each of them either $c_i \leftrightarrow a_i$ or $c_i \leftrightarrow b_i$ ($i$ iterates over all integers between $1$ and $n$, inclusive). For example, if $a$ is "code", $b$ is "true", and $c$ is "help", you can make $c$ equal to "crue" taking the $1$-st and the $4$-th letters from $a$ and the others from $b$. In this way $a$ becomes "hodp" and $b$ becomes "tele". Is it possible that after these swaps the string $a$ becomes exactly the same as the string $b$?
For every $i$ $(1 \leq i \leq n)$ where $n$ is the length of the strings. If $c_i$ is equal to $a_i$ we can swap it with $b_i$ or if $c_i$ is equal to $b_i$ we can swap it with $a_i$, otherwise we can't swap it. So we only need to check that $c_i$ is equal $a_i$ or $c_i$ is equal to $b_i$. Complexity is $O(n)$.
[ "implementation", "strings" ]
800
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000000\n#define mod 998244353\nconst int N = 500000;\nstring a , b , c;\n\nvoid solve(){\n cin >> a >> b >> c;\n for(int i = 0 ;i < (int)a.size();i++){\n if(c[i] != a[i] && c[i] != b[i]){\n puts(\"NO\");\n return;\n }\n }\n puts(\"YES\");\n return;\n}\n\nint main(){\n int t;\n cin >> t;\n while(t--){\n solve();\n }\n return 0;\n}"
1301
B
Motarack's Birthday
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $a$ of $n$ non-negative integers. Dark created that array $1000$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $k$ ($0 \leq k \leq 10^{9}$) and replaces all missing elements in the array $a$ with $k$. Let $m$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $|a_i - a_{i+1}|$ for all $1 \leq i \leq n - 1$) in the array $a$ after Dark replaces all missing elements with $k$. Dark should choose an integer $k$ so that $m$ is minimized. Can you help him?
Let's take all non missing elements that are adjacent to at least one missing element, we need to find a value $k$ that minimises the maximum absolute difference between $k$ and these values. The best $k$ is equal to (minimum value + maximum value) / 2. Then we find the maximum absolute difference between all adjacent pairs. Complexity is $O(n)$.
[ "binary search", "greedy", "ternary search" ]
1,500
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000010\n#define mod 1000000007\nconst int N = 300010;\nint n , arr[N] ; \n\nvoid solve(){\n int mn = oo , mx = -oo;\n\tscanf(\"%d\",&n);\n\tfor(int i=0;i<n;i++){\n\t\tscanf(\"%d\",&arr[i]);\n\t}\n\tfor(int i = 0;i<n;i++){\n\t\tif(i > 0 && arr[i] == -1 && arr[i - 1] != -1)\n\t\t\tmn = min(mn , arr[i - 1]) , mx = max(mx , arr[i - 1]);\n\t\tif(i < n - 1 && arr[i] == - 1 && arr[i + 1] != -1)\n\t\t\tmn = min(mn , arr[i + 1]) , mx = max(mx , arr[i + 1]);\n\t}\n\tint res = (mx + mn) / 2;\n\tint ans = 0;\n\tfor(int i=0;i<n;i++){\n\t\tif(arr[i] == -1)\n\t\t\tarr[i] = res;\n\t\tif(i)\n\t\t\tans = max(ans,abs(arr[i] - arr[i - 1]));\n\t}\n\tprintf(\"%d %d\\n\",ans,res);\n}\n\n\nint main(){\n\tint t;\n\tcin >> t;\n\twhile(t--){\n\t solve();\n\t}\n\treturn 0;\n}"
1301
C
Ayoub's function
Ayoub thinks that he is a very smart person, so he created a function $f(s)$, where $s$ is a binary string (a string which contains only symbols "0" and "1"). The function $f(s)$ is equal to the number of substrings in the string $s$ that contains at least one symbol, that is equal to "1". More formally, $f(s)$ is equal to the number of pairs of integers $(l, r)$, such that $1 \leq l \leq r \leq |s|$ (where $|s|$ is equal to the length of string $s$), such that at least one of the symbols $s_l, s_{l+1}, \ldots, s_r$ is equal to "1". For example, if $s = $"01010" then $f(s) = 12$, because there are $12$ such pairs $(l, r)$: $(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$. Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers $n$ and $m$ and asked him this problem. For all binary strings $s$ of length $n$ which contains exactly $m$ symbols equal to "1", find the maximum value of $f(s)$. Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
We can calculate the number of sub-strings that has at least one symbol equals to "1" like this: $f(s)$ $=$ (number of all sub-strings) $-$ (number of sub-strings that doesn't have any symbol equals to "1"). if the size of $s$ is equal to $n$, $f(s)$ $=$ $\frac{n\cdot(n+1)}{2}$ $-$ (number of sub-strings that doesn't have any symbol equals to "1"). if we want to calculate them, we only need to find every continuous sub-string of 0's if it's length was $l$, then we subtract $\frac{l\cdot(l+1)}{2}$. now we have a string contains $(n - m)$ "0" symobol, and we want to divide these symbols into $(m+1)$ groups so that the summation of $\frac{l\cdot(l+1)}{2}$ for every group is minimised. The best way is to divide them into equal groups or as equal as possible. let $z$ be the number of zeroes in the string, $z=(n - m)$, and g be the number of groups, $g=m+1$. let $k$ equal to $\lfloor$ $\frac{z}{g}$ $\rfloor$. we should give every group $k$ zeroes, except for the first $(z\mod g)$ groups, we should give them $k+1$ zeroes. So the answer is $\frac{n.(n+1)}{2}$ $-$ $\frac{k.(k+1)}{2} \cdot g$ $-$ $(k + 1) \cdot (z\mod g)$. Complexity is $O(1)$.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
1,700
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000010\n#define mod 1000000007\nconst int N = 1010;\n\n\nvoid solve(){\n\tint n , m;\n\tscanf(\"%d%d\",&n,&m);\n\tlong long ans = (long long)n * (long long)(n + 1) / 2LL;\n\tint z = n - m;\n\tint k = z / (m + 1);\n\tans -= (long long)(m + 1) * (long long)k * (long long)(k + 1) / 2LL;\n\tans -= (long long)(z % (m + 1)) * (long long)(k + 1);\n\tprintf(\"%lld\\n\",ans);\n}\n\nint main(){\n\tint t;\n\tcin >> t;\n\twhile(t--){\n\t\tsolve();\n\t}\t\n\treturn 0;\n}"
1301
D
Time to Run
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight. In order to lose weight, Bashar is going to run for $k$ kilometers. Bashar is going to run in a place that looks like a grid of $n$ rows and $m$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $(4 n m - 2n - 2m)$ roads. Let's take, for example, $n = 3$ and $m = 4$. In this case, there are $34$ roads. It is the picture of this case (arrows describe roads): Bashar wants to run by these rules: - He starts at the top-left cell in the grid; - In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $i$ and in the column $j$, i.e. in the cell $(i, j)$ he will move to: - in the case 'U' to the cell $(i-1, j)$; - in the case 'D' to the cell $(i+1, j)$; - in the case 'L' to the cell $(i, j-1)$; - in the case 'R' to the cell $(i, j+1)$; - He wants to run exactly $k$ kilometers, so he wants to make exactly $k$ moves; - Bashar can finish in any cell of the grid; - He can't go out of the grid so at any moment of the time he should be on some cell; - Bashar doesn't want to get bored while running so he must \textbf{not} visit the same road twice. \textbf{But he can visit the same cell any number of times}. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run. You should give him $a$ steps to do and since Bashar can't remember too many steps, $a$ should not exceed $3000$. In every step, you should give him an integer $f$ and a string of moves $s$ of length at most $4$ which means that he should repeat the moves in the string $s$ for $f$ times. He will perform the steps in the order you print them. For example, if the steps are $2$ RUD, $3$ UUL then the moves he is going to move are RUD $+$ RUD $+$ UUL $+$ UUL $+$ UUL $=$ RUDRUDUULUULUUL. Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $k$ kilometers or say, that it is impossible?
A strategy that guarantees that you can visit all the edges exactly once: 1- keep going right until you reach the last column in the first row. 2- keep going left until you reach the first column in the first row again. 3- go down. 4- keep going right until you reach the last column in the current row. 5- keep going {up, down, left} until you reach the first column in the current row again. 6- if you were at the last row, just keep going up until you reach the top left cell again, otherwise repeat moves 3, 4 and 5. We need only to take the first $k$ moves, and we can print them in about $3 \cdot n$ steps. complexity $O(n)$
[ "constructive algorithms", "graphs", "implementation" ]
2,000
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000000\n#define mod 998244853\nconst int N = 100010;\n\nvector< pair< int , string > > v , v2;\n\nint n , m , k , all = 0 , cur;\n\nstring tmp;\n\nvoid fix(vector< pair< int , string > > &v){\n v2 = v;\n v.clear();\n for(int i = 0 ;i < (int)v2.size();i++){\n if(v2[i].first != 0)\n v.push_back(v2[i]);\n }\n}\n\nint main(){\n scanf(\"%d%d%d\",&n,&m,&k);\n for(int i = 1;i <= n;i++){\n v.push_back(make_pair(m - 1 , \"R\"));\n all += (v.back().first * (int)v.back().second.size());\n if(i == 1)\n v.push_back(make_pair(m - 1 , \"L\"));\n else\n v.push_back(make_pair(m - 1 , \"UDL\"));\n all += (v.back().first * (int)v.back().second.size());\n if(i == n)\n v.push_back(make_pair(n - 1 , \"U\"));\n else\n v.push_back(make_pair(1 , \"D\"));\n all += (v.back().first * (int)v.back().second.size());\n }\n if(all < k){\n puts(\"NO\");\n return 0;\n }\n while(all > k){\n tmp = v.back().second;\n cur = (v.back().first * (int)v.back().second.size());\n v.pop_back();\n all -= cur;\n if(all >= k)\n continue;\n cur = k - all;\n if(cur / (int)tmp.size() > 0) v.push_back(make_pair(cur / (int)tmp.size() , tmp));\n tmp.resize(cur % (int)tmp.size());\n if((int)tmp.size() > 0) v.push_back(make_pair(1,tmp));\n all = k;\n }\n puts(\"YES\");\n fix(v);\n printf(\"%d\\n\",(int)v.size());\n for(int i = 0 ;i < (int)v.size();i++){\n printf(\"%d %s\\n\",v[i].first,v[i].second.c_str());\n }\n return 0;\n}"
1301
E
Nanosoft
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: An Example of some incorrect logos: Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of $n$ rows and $m$ columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh $q$ options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is $0$. Warawreh couldn't find the best option himself so he asked you for help, can you help him?
For each cell, we will calculate the maximum size of a Nanosoft logo in which it is the bottom right cell, in the top left square. The cell marked with $x$ in this picture: If we had a grid like this: If we take the cell in the second row, second column, it can make a Nanosoft logo with size $4 \times 4$, being the bottom right cell in the top left square. We can calculate the answer for every cell using binary search , and checking every sub-square using 2D cumulative sum. Now we build a 2D array that contains that previous calculated answer, lets call it $val[n][m]$. For the previous picture $val$ will be like this: Now for each query we can do binary search on its answer. We check the current mid this way: The mid will tell us the length of one of the sides divided by 2. Like if mid = 2, the area of the square we are checking is $(4 \cdot 4 = 16)$. Now we should check the maximum element in the 2D array val, in the 2D range: $(r_1 + mid - 1, c_1 + mid - 1,r_2 - mid , c_2 - mid)$. The current mid is correct if the maximum element in that 2D range is greater than or equal to $(4 \cdot mid \cdot mid)$. We can get the maximum value in a 2D range using 2D sparse table, with build in $O(n \cdot m \cdot \log{n} \cdot \log{m})$ and query in $O(1)$. total Complexity is $O(n \cdot m \cdot \log{n} \cdot \log{m} + q \cdot \log{m})$.
[ "binary search", "data structures", "dp", "implementation" ]
2,500
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000010\n#define mod 1000000007\nconst int N = 510 , LOG = 10;\nchar grid[N][N];\nint val[N][N] , sum[N][N][4];\nint st[N][N][LOG][LOG] , lg[N];\nint n , q , m , r1 , c1 , r2, c2 , nr , nc;\n\nstring S = \"RGYB\";\nint dr[4] = {0 , 0 , 1 , 1};\nint dc[4] = {0 , 1 , 0 , 1};\n\ninline bool check(int r1,int c1,int r2,int c2,int k){\n r1++,c1++,r2++,c2++;\n return ((sum[r2][c2][k] - sum[r1 - 1][c2][k] - sum[r2][c1 - 1][k] + sum[r1 - 1][c1 - 1][k]) == (r2 - r1 + 1) * (c2 - c1 + 1));\n} \n\ninline bool can(int r,int c,int s){\n if(r < 0 || c < 0) return false;\n if(r + (s << 1) - 1 >= n || c + (s << 1) - 1 >= m) return false;\n for(int i =0 ;i < 4;i++){\n nr = r + dr[i] * s ;\n nc = c + dc[i] * s;\n if(!check(nr , nc , nr + s - 1 , nc + s - 1 , i))\n return false;\n }\n return true;\n}\n\nvoid build(){\n lg[1] = 0;\n for(int i = 2;i<N;i++){\n lg[i] = lg[i - 1];\n if((1 << (lg[i] + 1)) == i)\n lg[i]++;\n }\n for(int k = 1;k < LOG;k++){\n for(int i=0;i + (1 << k) <= n;i++){\n for(int j=0;j<m;j++){\n st[i][j][k][0] = max(st[i][j][k - 1][0] , st[i + (1 << (k - 1))][j][k - 1][0]);\n }\n }\n }\n for(int l = 1;l < LOG;l++){\n for(int k = 0;k < LOG;k++){\n for(int i=0;i+(1 << k) <= n;i++){\n for(int j = 0;j + (1 << l) <= m;j++){\n st[i][j][k][l] = max(st[i][j][k][l - 1] , st[i][j + (1 << (l - 1))][k][l-1]);\n }\n }\n }\n }\n}\n\nint a , b;\n\ninline int getmax(int r1,int c1,int r2,int c2){\n if(r2 < r1 || c2 < c1 || r1 < 0 || r2 >= n || c1 < 0 || c2 >= m) return -oo;\n a = lg[(r2 - r1) + 1];\n b = lg[(c2 - c1) + 1];\n return max(max(st[r1][c1][a][b] , st[r2 - (1 << a) + 1][c1][a][b]) , max(st[r1][c2 - (1 << b) + 1][a][b] , st[r2 - (1 << a) + 1][c2 - (1 << b) + 1][a][b]));\n}\n\n\nint main(){\n scanf(\"%d%d%d\",&n,&m,&q);\n for(int i=0;i<n;i++){\n scanf(\" %s\",grid[i]);\n for(int j=0;j<m;j++){\n for(int k=0;k<4;k++){\n sum[i + 1][j + 1][k] = sum[i][j + 1][k] + sum[i + 1][j][k] - sum[i][j][k] + (S[k] == grid[i][j]);\n }\n }\n }\n int low , high , mid , res;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n low = 1 , high = min(min(i + 1,n - i) , min(j + 1,m - j));\n while(high >= low){\n mid = ((low + high) >> 1);\n if(can(i - mid + 1,j - mid + 1,mid))\n st[i][j][0][0] = mid, low = mid + 1;\n else\n high = mid - 1;\n }\n }\n }\n build();\n while(q--){\n scanf(\"%d%d%d%d\",&r1,&c1,&r2,&c2);\n r1--,c1--,r2--,c2--;\n low = 1 , high = (n >> 1) , res = 0;\n while(high >= low){\n mid = ((low + high) >> 1);\n if(getmax(r1 + mid - 1,c1 + mid - 1,r2 - mid , c2 - mid) >= mid)\n res = mid, low = mid + 1;\n else\n high = mid - 1;\n }\n printf(\"%d\\n\",res * res * 4);\n }\n return 0;\n}"
1301
F
Super Jaber
Jaber is a superhero in a large country that can be described as a grid with $n$ rows and $m$ columns, where every cell in that grid contains a different city. Jaber gave every city in that country a specific color between $1$ and $k$. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color. Jaber has to do $q$ missions. In every mission he will be in the city at row $r_1$ and column $c_1$, and he should help someone in the city at row $r_2$ and column $c_2$. Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.
In the shortest path between any two cells, you may use an edge that goes from a cell to another one with the same color at least once, or you may not. If you didn't use an edge that goes from a cell to another one with the same color then the distance will be the Manhattan distance. Otherwise you should find the best color that you will use that edge in it, the cost will be (the minimum cost between any cell of that color with first cell + the minimum cost between any cell of that color with the second cell + 1). In order to find the minimum cost from every color to each cell, we can run multi-source BFS for every color. But visiting all other cells that has the same color every time is too slow, so we can only visit these cells when we reach the first cell from every color. Complexity is $O(n \cdot m \cdot k + q \cdot k)$.
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
2,600
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000000\n#define mod 998244353\nconst int N = 1010 , K = 45; \nint n , m , k , r1 , r2 , c1 , c2 , grid[N][N] , ans = 0;\n\nint cost[K][N][N];\nbool done[K];\n\nqueue < pair<int,int> > q;\n\nint dr[4] = {0 , 1 , 0 , -1};\nint dc[4] = {1 , 0 ,-1 , 0};\n\nvector < pair<int,int> > cells[K];\n\nvoid BFS(int col){\n for(int i = 0; i < (int)cells[col].size();i++){\n cost[col][cells[col][i].first][cells[col][i].second] = 0;\n q.push(make_pair(cells[col][i].first,cells[col][i].second));\n }\n for(int i = 1;i <= k;i++) done[i] = false;\n int r , c , nr , nc;\n while(!q.empty()){\n r = q.front().first;\n c = q.front().second;\n q.pop();\n if(!done[grid[r][c]]){\n done[grid[r][c]] = true;\n for(int i = 0 ; i < (int)cells[grid[r][c]].size() ;i++){\n nr = cells[grid[r][c]][i].first;\n nc = cells[grid[r][c]][i].second;\n if(cost[col][nr][nc] == -1){\n cost[col][nr][nc] = cost[col][r][c] + 1;\n q.push(make_pair(nr , nc));\n }\n }\n }\n for(int i = 0 ;i < 4;i++){\n nr = r + dr[i];\n nc = c + dc[i];\n if(nr >= 0 && nr < n && nc >= 0 && nc < m && cost[col][nr][nc] == -1){\n cost[col][nr][nc] = cost[col][r][c] + 1;\n q.push(make_pair(nr , nc));\n }\n }\n }\n}\n\n\nint main(){\n scanf(\"%d%d%d\",&n,&m,&k);\n for(int i = 0 ;i < n;i++){\n for(int j = 0 ;j < m;j++){\n scanf(\"%d\",&grid[i][j]);\n cells[grid[i][j]].push_back(make_pair(i , j));\n }\n }\n memset(cost, -1, sizeof(cost));\n for(int i = 1;i <= k;i++)\n BFS(i);\n int q;\n scanf(\"%d\",&q);\n while(q--){\n scanf(\"%d%d%d%d\",&r1,&c1,&r2,&c2);\n r1--,c1--,r2--,c2--;\n ans = abs(r1 - r2) + abs(c1 - c2);\n for(int i = 1;i <= k;i++)\n ans = min(ans , 1 + cost[i][r1][c1] + cost[i][r2][c2]);\n printf(\"%d\\n\",ans);\n }\n return 0;\n}"
1303
A
Erasing Zeroes
You are given a string $s$. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?
Let's find the first and the last position of $1$-characters (denote them as $l$ and $r$ respectively). Since the can't delete $1$-characters, all $1$-characters between $s_l$ and $s_r$ will remain. So, we have to delete all $0$-characters between $s_l$ and $s_r$.
[ "implementation", "strings" ]
800
for t in range(int(input())): print(input().strip('0').count('0'))
1303
B
National Project
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing. Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on. You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good. You don't really care about the quality of the highway, you just want to make sure that \textbf{at least half of the highway} will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality. What is the minimum number of days is needed to finish the repair of \textbf{the whole highway}?
There are two conditions that should be met according to the statement. On the one hand, we should repair the whole highway, so we must spend at least $n$ days to do it. On the other hand, at least half of it should have high-quality pavement or at least $needG = \left\lceil \frac{n}{2} \right\rceil$ units should be laid at good days. How to calculate the minimum number of days (name it as $totalG$) for the second condition to meet? Note that the first $totalG$ days can be represented as several (maybe zero) blocks of $g + b$ days, where exactly $g$ days in each block are good and some remaining days $1 \le rem \le g$. The $rem > 0$ because $totalG$ will not be minimum otherwise. There are plenty of ways to calculate $totalG$. One of them is the following: Firstly, let's calculate the number of $g + b$ cycles we need: $totatG = \left\lfloor \frac{needG}{g} \right\rfloor \cdot (g + b)$. Now, if $needG \mod g > 0$ we just add it (since it's exactly the $rem$) or $totalG = totalG + (needG \mod g)$. But if $needG \mod g = 0$ we added to $totalG$ last $b$ block and should subtract it or $totalG = totalG - b$. The answer is $\max(n, totalG)$.
[ "math" ]
1,400
fun main() { val t = readLine()!!.toInt() for (tc in 1..t) { val (n, g, b) = readLine()!!.split(' ').map { it.toLong() } val needG = (n + 1) / 2 var totalG = needG / g * (b + g) totalG += if (needG % g == 0L) -b else needG % g println(maxOf(n, totalG)) } }
1303
C
Perfect Keyboard
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $26$ lowercase Latin letters will be arranged in some order. Polycarp uses the same password $s$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $s$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $s$, so, for example, the password cannot be password (two characters s are adjacent). Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?
The problem can be solved using a greedy algorithm. We will maintain the current layout of the keyboard with letters that have already been encountered in the string, and the current position on the layout. If the next letter of the string is already on the layout, it must be adjacent to the current one, otherwise there is no answer. If there was no such letter yet, we can add it to the adjacent free position, if both of them is occupied, then there is no answer. At the end, you have to add letters that were not in the string $s$.
[ "dfs and similar", "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i < int(n); ++i) void solve() { string s; cin >> s; vector<bool> used(26); used[s[0] - 'a'] = true; string t(1, s[0]); int pos = 0; for (int i = 1; i < sz(s); i++) { if (used[s[i] - 'a']) { if (pos > 0 && t[pos - 1] == s[i]) { pos--; } else if (pos + 1 < sz(t) && t[pos + 1] == s[i]) { pos++; } else { cout << "NO" << endl; return; } } else { if (pos == 0) { t = s[i] + t; } else if (pos == sz(t) - 1) { t += s[i]; pos++; } else { cout << "NO" << endl; return; } } used[s[i] - 'a'] = true; } forn(i, 26) if (!used[i]) t += char(i + 'a'); cout << "YES" << endl << t << endl; } int main() { int tc; cin >> tc; forn(i, tc) solve(); }
1303
D
Fill The Bag
You have a bag of size $n$. Also you have $m$ boxes. The size of $i$-th box is $a_i$, where each $a_i$ is an integer non-negative power of two. You can divide boxes into two parts of equal size. Your goal is to fill the bag completely. For example, if $n = 10$ and $a = [1, 1, 32]$ then you have to divide the box of size $32$ into two parts of size $16$, and then divide the box of size $16$. So you can fill the bag with boxes of size $1$, $1$ and $8$. Calculate the minimum number of divisions required to fill the bag of size $n$.
If $\sum\limits_{i=1}^{n} a_i \ge n$, then the answer is YES, because the just can divide all boxes to size $1$ and then fill the bag. Otherwise the answer is NO. If the answer is YES, let's calculate the minimum number of divisions. Let's consider all boxes from small to large. Presume that now we consider boxes of size $2^i$. Then there are three cases: if in binary representation of $n$ the $i$-th bit is equal to $0$, then we don't need boxes of size $2^i$ and we can merge it into boxes of size $2^{i+1}$; if in binary representation of $n$ the $i$-th bit is equal to $1$ and we have at most one box of size $2^i$, then we have to put it box in the bag and then merge the remaining boxes of size $2^i$ into boxes of size $2^{i+1}$; if in binary representation of $n$ the $i$-th bit is equal to $1$ and we have not boxes of size $2^i$, then we have to divide the large box into box of size $2^i$ (let's presume that it's box of size $2^x$). After that we just continue this algorithm with box of size $2^x$.
[ "bitmasks", "greedy" ]
1,900
from math import log2 for t in range(int(input())): n, m = map(int, input().split()) c = [0] * 61 s = 0 for x in map(int, input().split()): c[int(log2(x))] += 1 s += x if s < n: print(-1) continue i, res = 0, 0 while i < 60: if (1<<i)&n != 0: if c[i] > 0: c[i] -= 1 else: while i < 60 and c[i] == 0: i += 1 res += 1 c[i] -= 1 continue c[i + 1] += c[i] // 2 i += 1 print(res)
1303
E
Erase Subsequences
You are given a string $s$. You can build new string $p$ from $s$ using the following operation \textbf{no more than two times}: - choose any subsequence $s_{i_1}, s_{i_2}, \dots, s_{i_k}$ where $1 \le i_1 < i_2 < \dots < i_k \le |s|$; - erase the chosen subsequence from $s$ ($s$ can become empty); - concatenate chosen subsequence to the right of the string $p$ (in other words, $p = p + s_{i_1}s_{i_2}\dots s_{i_k}$). Of course, initially the string $p$ is empty. For example, let $s = \text{ababcd}$. At first, let's choose subsequence $s_1 s_4 s_5 = \text{abc}$ — we will get $s = \text{bad}$ and $p = \text{abc}$. At second, let's choose $s_1 s_2 = \text{ba}$ — we will get $s = \text{d}$ and $p = \text{abcba}$. So we can build $\text{abcba}$ from $\text{ababcd}$. Can you build a given string $t$ using the algorithm above?
Let's look at string $t$. Since we should get it using no more than two subsequences, then $t = a + b$ where $a$ is the first subsequence and $b$ is the second one. In the general case, $a$ can be empty. Let iterate all possible lengths of $a$ ($0 \le |a| < |s|$), so we can check the existence of solution for each pair $a$ and $b$. If we'd fix $a$ and $b$ we need to check the following: is it true that $s$ contains $a$ and $b$ as subsequences and these subsequences don't intersect. Initially, we can invent the following dp: let $dp[len_s][len_a][len_b]$ be $1$ if the prefix of $s$ of length $len_s$ contains prefixes of $a$ and $b$ of length $len_a$ and $len_b$ as non-intersecting subsequences. The transitions are straingforward: if $dp[len_s][len_a][len_b] = 1$ we can either skip $s[len_s]$ ($0$-indexed) and update $dp[len_s + 1][len_a][len_b]$. If $s[len_s] = a[len_a]$ ($0$-indexed) then we can update $dp[len_s + 1][len_a + 1][len_b]$ and if $s[len_s] = b[len_b]$ then we can update $dp[len_s + 1][len_a][len_b + 1]$. But this dp has complexity $O(|s|^3)$ in general case. But we can transform it in the next way: instead of the boolean value, we will make $len_s$ as a value of dp. In other words, we will maintain $dp[len_a][len_b]$ as minimal appropriate prefix $len_s$. But the problem now is to define transitions. Let's note the next fact: suppose we have $len_s = dp[len_a][len_b]$ and we'd like to add next character to $a$ which is equal to $a[len_a]$. The idea is next: it's always optimal to choose the first occurrence of $a[len_a]$ in $s[len_s \dots |s|)$. It can be proved by contradiction: if the first occurrence is free then it's better to take it, or if the first occurrence will be occupied by $b$ then this will be handled by the other state $dp[len_a][len_b']$ with $len_b' > len_b$. The logic for increasing $len_b$ is analogical. In result, we need to precalculate array $nxt[pos][c]$ with the next occurrence of character $c$ in suffix $pos$ of $s$ one time before choosing $a$ and $b$ and use it each time to acquire $O(|s|^2)$ complexity. The total complexity if $O(|s|^3)$ for each test case.
[ "dp", "strings" ]
2,200
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); string s, t; inline bool read() { if(!(cin >> s >> t)) return false; for(auto &c : s) c -= 'a'; for(auto &c : t) c -= 'a'; return true; } vector< vector<int> > nxt; bool calc(const string &a, const string &b) { vector< vector<int> > dp(sz(a) + 1, vector<int>(sz(b) + 1, INF)); dp[0][0] = 0; fore(i, 0, sz(a) + 1) fore(j, 0, sz(b) + 1) { if(dp[i][j] > sz(s)) continue; int len = dp[i][j]; if(i < sz(a) && nxt[len][a[i]] < INF) { dp[i + 1][j] = min(dp[i + 1][j], nxt[len][a[i]] + 1); } if(j < sz(b) && nxt[len][b[j]] < INF) { dp[i][j + 1] = min(dp[i][j + 1], nxt[len][b[j]] + 1); } } return dp[sz(a)][sz(b)] < INF; } inline void solve() { nxt.assign(sz(s) + 1, vector<int>(26, INF)); for(int i = sz(s) - 1; i >= 0; i--) { nxt[i] = nxt[i + 1]; nxt[i][s[i]] = i; } for(int i = 0; i < sz(t); i++) { if(calc(t.substr(0, i), t.substr(i, sz(t)))) { cout << "YES" << endl; return; } } cout << "NO" << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int tc; cin >> tc; while(tc--) { read(); solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1303
F
Number of Components
You are given a matrix $n \times m$, initially filled with zeroes. We define $a_{i, j}$ as the element in the $i$-th row and the $j$-th column of the matrix. Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1$ is the first cell, $s_k$ is the second cell, and for every $i \in [1, k - 1]$, $s_i$ and $s_{i + 1}$ are connected. You are given $q$ queries of the form $x_i$ $y_i$ $c_i$ ($i \in [1, q]$). For every such query, you have to do the following: - replace the element $a_{x, y}$ with $c$; - count the number of connected components in the matrix. There is one additional constraint: for every $i \in [1, q - 1]$, $c_i \le c_{i + 1}$.
Note that because of the low constraints on the number of colors, the problem can be solved independently for each color. Now you can divide the queries into two types: add a cell to the field and delete it. You have to maintain the number of components formed by added cells. Cell deletions will occur after all additions because of the condition $c_i \le c_{i+1}$. The first part of the solution will be to calculate the number of components while adding new cells. This is a standard problem that can be solved using the DSU. After that, we should note that if we consider the process of removing cells from the end, this process is similar to the process of adding. Therefore, we have to process delete requests from the end in the same way as add requests, only their contribution to the number of components will be opposite in sign.
[ "dsu", "implementation" ]
2,800
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define pb push_back #define mp make_pair #define sqr(a) ((a) * (a)) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i < int(n); ++i) #define fore(i, l, r) for (int i = int(l); i < int(r); ++i) #define forr(i, r, l) for (int i = int(r) - 1; i >= int(l); --i) typedef pair<int, int> pt; const int M = 310; const int N = 2000 * 1000 + 13; int n, m, q; int a[M][M]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, -1, 0, 1}; bool in(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; } int p[M * M], rk[M * M]; int getp(int v) { return p[v] == v ? v : p[v] = getp(p[v]); } bool unite(int a, int b) { a = getp(a); b = getp(b); if (a == b) return false; if (rk[a] < rk[b]) swap(a, b); p[b] = a; rk[a] += rk[b]; return true; } int dif[N]; vector<pt> add[N], del[N]; void recalc(const vector<pt>& ev, int coeff) { forn(i, n) forn(j, m) a[i][j] = 0; forn(i, n * m) p[i] = i, rk[i] = 1; for (auto it : ev) { int cur = 1; int x = it.x / m, y = it.x % m; a[x][y] = 1; forn(k, 4) { int nx = x + dx[k]; int ny = y + dy[k]; if (in(nx, ny) && a[nx][ny] == 1) cur -= unite(nx * m + ny, x * m + y); } dif[it.y] += cur * coeff; } } int main() { scanf("%d%d%d", &n, &m, &q); int clrs = 1; forn(i, q) { int x, y, c; scanf("%d%d%d", &x, &y, &c); --x; --y; if (a[x][y] == c) continue; clrs = c + 1; add[c].pb(mp(x * m + y, i)); del[a[x][y]].pb(mp(x * m + y, i)); a[x][y] = c; } forn(x, n) forn(y, m) del[a[x][y]].pb(mp(x * m + y, q)); forn(i, clrs) reverse(all(del[i])); forn(i, clrs) recalc(add[i], +1); forn(i, clrs) recalc(del[i], -1); int cur = 1; forn(i, q) { cur += dif[i]; printf("%d\n", cur); } }
1303
G
Sum of Prefix Sums
We define the sum of prefix sums of an array $[s_1, s_2, \dots, s_k]$ as $s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + \dots + (s_1 + s_2 + \dots + s_k)$. You are given a tree consisting of $n$ vertices. Each vertex $i$ has an integer $a_i$ written on it. We define the value of the simple path from vertex $u$ to vertex $v$ as follows: consider all vertices appearing on the path from $u$ to $v$, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence. Your task is to calculate the maximum value over all paths in the tree.
Let's use centroid decomposition to solve the problem. We need to process all the paths going through each centroid somehow. Consider a path from vertex $u$ to vertex $v$ going through vertex $c$, which is an ancestor of both $u$ and $v$ in the centroid decomposition tree. Suppose the sequence of numbers on path from $u$ to $c$ (including both these vertices) is $[a_1, a_2, \dots, a_k]$, and the sequence of numbers on path from $c$ to $v$ (including $v$, but excluding $c$) is $[b_1, b_2, \dots, b_m]$. Let $sum_a = \sum\limits_{i = 1}^{k} a_i$, $psum_a = \sum\limits_{i = 1}^{k} (k - i + 1) a_i$, and $psum_b = \sum\limits_{i = 1}^{m} (m - i + 1) b_i$. We can show that the sum of prefix sums of $[a_1, a_2, \dots, a_k, b_1, b_2, \dots, b_m]$ is equal to $psum_a + psum_b + sum_a \cdot m$. Now, suppose we fix the second part of the path ($psum_b$ and $m$ are fixed), and we want to find the best first part for this second part. Each possible first part is represented by a linear function, and our goal is to find the maximum over all these linear functions in the point $m$, and add $psum_b$ to this maximum. This can be done with the help of convex hull or Li Chao tree. The most difficult part of implementation is how to process each centroid's subtree. It's easy to obtain all "first parts" and "second parts" of paths going through the centroid, but pairing them up can be complicated - for each second part, we have to build a convex hull or Li Chao tree on all first parts going to this centroid, excluding those which go through the same child of the centroid as the "second part" we are considering. One of the best ways to implement this is the following. Suppose our centroid has $m$ children, $fp_i$ is the set of "first parts" going from the $i$-th child of the centroid, and $sp_i$ is the set of "second parts" going to the $i$-th child. We will create a new data structure (initially empty), process all second parts from $sp_1$, add all first parts from $fp_1$, process all second parts from $sp_2$, add all first parts from $fp_2$, and so on. After that, we will clear our data structure, process all second parts from $sp_m$, add all first parts from $fp_m$, process all second parts from $sp_{m - 1}$, add all first parts from $fp_{m - 1}$, and so on, until we add all first parts from $fp_1$. That way we will consider all possible first parts for each second part we are trying to use.
[ "data structures", "divide and conquer", "geometry", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; const int N = 150043; typedef pair<long long, long long> func; func T[4 * N]; bool usedT[4 * N]; void clear(int v, int l, int r) { if(!usedT[v]) return; usedT[v] = false; T[v] = make_pair(0ll, 0ll); if(l < r - 1) { int m = (l + r) / 2; clear(v * 2 + 1, l, m); clear(v * 2 + 2, m, r); } } long long eval(func f, int x) { return f.first * x + f.second; } long long get(int v, int l, int r, int x) { long long ans = eval(T[v], x); if(l < r - 1) { int m = (l + r) / 2; if(m > x) ans = max(ans, get(v * 2 + 1, l, m, x)); else ans = max(ans, get(v * 2 + 2, m, r, x)); } return ans; } void upd(int v, int l, int r, func f) { usedT[v] = true; int m = (l + r) / 2; bool need_swap = eval(f, m) > eval(T[v], m); if(need_swap) swap(T[v], f); if(l == r - 1) return; if(eval(f, l) > eval(T[v], l)) upd(v * 2 + 1, l, m, f); else upd(v * 2 + 2, m, r, f); } long long ans = 0; void update_ans(vector<vector<func> > heads, vector<vector<func> > tails) { int n = heads.size(); for(int i = 0; i < n; i++) { for(auto x : heads[i]) ans = max(ans, get(0, 0, N, x.first) + x.second); for(auto x : tails[i]) upd(0, 0, N, x); } clear(0, 0, N); } int a[N]; vector<int> g[N]; int n; bool used[N]; int siz[N]; void dfs1(int x, int p = -1) { if(used[x]) return; siz[x] = 1; for(auto to : g[x]) { if(!used[to] && to != p) { dfs1(to, x); siz[x] += siz[to]; } } } pair<int, int> c; int S = 0; void find_centroid(int x, int p = -1) { if(used[x]) return; int mx = 0; for(auto to : g[x]) { if(!used[to] && to != p) { find_centroid(to, x); mx = max(mx, siz[to]); } } if(p != -1) mx = max(mx, S - siz[x]); c = min(c, make_pair(mx, x)); } void dfs_heads(int v, int p, int cnt, long long cursum, long long curadd, vector<func>& sink) { if(used[v]) return; cnt++; curadd += a[v]; cursum += curadd; sink.push_back(make_pair(cnt, cursum)); for(auto to : g[v]) if(to != p) dfs_heads(to, v, cnt, cursum, curadd, sink); } void dfs_tails(int v, int p, int cnt, long long cursum, long long curadd, vector<func>& sink) { if(used[v]) return; cnt++; curadd += a[v]; cursum += a[v] * 1ll * cnt; sink.push_back(make_pair(curadd, cursum)); for(auto to : g[v]) if(to != p) dfs_tails(to, v, cnt, cursum, curadd, sink); } void centroid(int v) { if(used[v]) return; dfs1(v); S = siz[v]; c = make_pair(int(1e9), -1); find_centroid(v); int C = c.second; used[C] = 1; vector<vector<func> > heads, tails; for(auto to : g[C]) if(!used[to]) { heads.push_back(vector<func>()); dfs_heads(to, C, 1, a[C], a[C], heads.back()); tails.push_back(vector<func>()); dfs_tails(to, C, 0, 0, 0, tails.back()); } heads.push_back(vector<func>({{1, a[C]}})); tails.push_back(vector<func>({{0, 0}})); update_ans(heads, tails); reverse(heads.begin(), heads.end()); reverse(tails.begin(), tails.end()); update_ans(heads, tails); for(auto to : g[C]) centroid(to); } int main() { scanf("%d", &n); for(int i = 0; i < n - 1; i++) { int x, y; scanf("%d %d", &x, &y); --x; --y; g[x].push_back(y); g[y].push_back(x); } for(int i = 0; i < n; i++) scanf("%d", &a[i]); centroid(0); printf("%lld\n", ans); }
1304
A
Two Rabbits
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $x$, and the shorter rabbit is currently on position $y$ ($x \lt y$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $a$, and the shorter rabbit hops to the negative direction by $b$. For example, let's say $x=0$, $y=10$, $a=2$, and $b=3$. At the $1$-st second, each rabbit will be at position $2$ and $7$. At the $2$-nd second, both rabbits will be at position $4$. Gildong is now wondering: {Will the two rabbits be at the same position \textbf{at the same moment}? If so, how long will it take?} Let's find a moment in time (in seconds) after which the rabbits will be at the same point.
We can see that the taller rabbit will be at position $x + Ta$ and the shorter rabbit will be at position $y - Tb$ at the $T$-th second. We want to know when these two values are equal. Simplifying the equation, we get $\cfrac{y - x}{a + b} = T$. Since we only consider positive integers for $T$, the answer is $\cfrac{y - x}{a + b}$ only if $y - x$ is divisible by $a + b$. Otherwise, the answer is $-1$. Another intuitive approach is to think of it as relative speed. In the perspective of the taller rabbit, the shorter rabbit will move (or more like, teleport) to the negative direction at speed of $a + b$ per second. Therefore the initial distance $y - x$ must be divisible by $a + b$ in order to make the two rabbits meet at time $\cfrac{y - x}{a + b}$. Time complexity: $O(1)$ for each test case.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while (tc--) { int x, y, a, b; cin >> x >> y >> a >> b; cout << ((y - x) % (a + b) == 0 ? (y - x) / (a + b) : -1) << endl; } }
1304
B
Longest Palindrome
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. \textbf{An empty string is also a palindrome.} Gildong loves this concept so much, so he wants to play with it. He has $n$ distinct strings of equal length $m$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Let's define $rev(S)$ as the reversed string of a string $S$. There are two cases when we choose $K$ strings to make a palindrome string $S_1 + S_2 + \cdots + S_K$: If $K$ is even, for every integer $X$ ($1 \le X \le \cfrac{K}{2}$), $S_X = rev(S_{K-X+1})$. if $K$ is odd, $S_{\frac{K+1}{2}}$ must be palindrome. Also for every integer $X$ ($1 \le X \le \cfrac{K-1}{2}$), $S_X = rev(S_{K-X+1})$. In either case we want to find as many pairs of strings as possible such that one is the reverse of the other. It is also clear that if $T$ is a palindrome string then $rev(T) = T$. We cannot make a pair of T and rev(T) because all strings in the input are distinct. Therefore, for each string we need to find if there is another string that is its reverse. If there exists one, put them on the left / right end respectively. If there are one or more strings that are palindrome themselves, pick any one of them and put it in the middle. Time complexity: $O(n^2m)$ if we implement it naively. $O(nmlogn)$ is possible if we use a data structure that provides $O(logn)$ search such as std::set in C++.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100; string s[MAX_N]; int main() { set<string> dict; int n, m, i; cin >> n >> m; for (i = 0; i < n; i++) { cin >> s[i]; dict.insert(s[i]); } vector<string> left, right; string mid; for (i = 0; i < n; i++) { string t = s[i]; reverse(t.begin(), t.end()); if (t == s[i]) mid = t; else if (dict.find(t) != dict.end()) { left.push_back(s[i]); right.push_back(t); dict.erase(s[i]); dict.erase(t); } } cout << left.size() * m * 2 + mid.size() << endl; for (string x : left) cout << x; cout << mid; reverse(right.begin(), right.end()); for (string x : right) cout << x; cout << endl; }
1304
C
Air Conditioner
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it. Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant. The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially. Each customer is characterized by three values: $t_i$ — the time (in minutes) when the $i$-th customer visits the restaurant, $l_i$ — the lower bound of their preferred temperature range, and $h_i$ — the upper bound of their preferred temperature range. A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $i$-th customer is satisfied if and only if the temperature is between $l_i$ and $h_i$ (inclusive) in the $t_i$-th minute. Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
Since the range of temperatures can be large, it is impossible to consider all possible cases. However, we only need to find any case that can satisfy all customers, so let's try to maximize the possible range for each customer in the order of their visit time. Let's define two variables $mn$ and $mx$, each representing the minimum and maximum possible temperature that can be set now. Initially they are both $m$ and the current time is $0$. After $K$ minutes, we can see that the possible range is $[mn-K, mx+K]$. This means if a customer that visits after $K$ minutes has preferred temperature range $[L, R]$ that intersects with this range (inclusive), Gildong can satisfy that customer. In other words, $mn-K \le R$ and $L \le mx+K$ must be satisfied. Then we can reset $mn$ and $mx$ to fit this intersected range: $mn = max(mn-K, L)$ and $mx = min(mx+K, R)$. If this can be continued until the last customer, the answer is "YES". Otherwise, the answer is "NO". Time complexity: $O(n)$ for each test case.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100; int t[MAX_N], lo[MAX_N], hi[MAX_N]; int main() { int tc; cin >> tc; while (tc--) { int n, m, i; cin >> n >> m; for (i = 0; i < n; i++) cin >> t[i] >> lo[i] >> hi[i]; int prev = 0; int mn = m, mx = m; bool flag = true; for (i = 0; i < n; i++) { mx += t[i] - prev; mn -= t[i] - prev; if (mx < lo[i] || mn > hi[i]) { flag = false; break; } mx = min(mx, hi[i]); mn = max(mn, lo[i]); prev = t[i]; } if (flag) cout << "YES\n"; else cout << "NO\n"; } }
1304
D
Shortest and Longest LIS
Gildong recently learned how to find the longest increasing subsequence (LIS) in $O(n\log{n})$ time for a sequence of length $n$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of $n$ distinct integers between $1$ and $n$, inclusive, to test his code with your output. The quiz is as follows. Gildong provides a string of length $n-1$, consisting of characters '<' and '>' only. The $i$-th (1-indexed) character is the comparison result between the $i$-th element and the $i+1$-st element of the sequence. If the $i$-th character of the string is '<', then the $i$-th element of the sequence is less than the $i+1$-st element. If the $i$-th character of the string is '>', then the $i$-th element of the sequence is greater than the $i+1$-st element. He wants you to find two possible sequences (not necessarily distinct) consisting of $n$ distinct integers between $1$ and $n$, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.
There are various strategies to solve each part. I'll explain one of them for each. It would be fun to come up with your own strategy as well :) Shortest LIS Let's group each contiguously increasing part. We can easily see that we cannot make the LIS shorter than the maximum size among these groups. It can be shown that we can make the length of the LIS not longer than that as well. One strategy is to fill the largest unused numbers in increasing order for each group from left to right. There will be no indices $i$ and $j$ ($i \lt j$) such that $perm[i]$ < $perm[j]$ where $i$ and $j$ are in different groups. Therefore the maximum size among the groups will be the length of the LIS. Longest LIS Let's group each contiguously decreasing part. We can easily see that there can be at most one element from each group that is included in any possible LIS. It can be shown that we can make a sequence that takes one element from every groups to form the LIS. One strategy is to fill the smallest unused numbers in decreasing order for each group from left to right. Then for every indices $i$ and $j$ ($i \lt j$) where $i$ and $j$ are in different groups, $perm[j]$ will be always greater than $perm[i]$. Thus, we can take any one element from each and every groups to form the LIS. Time complexity: $O(n)$ for each test case. Here's a little challenge for people who want harder things: Can you make a sequence that has the length of its LIS exactly $k$?
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; const int MAX_N = 200000; int ans[MAX_N + 5]; int main() { int tc; cin >> tc; while (tc--) { int n, i, j; string s; cin >> n >> s; int num = n, last = 0; for (i = 0; i < n; i++) { if (i == n - 1 || s[i] == '>') { for (j = i; j >= last; j--) ans[j] = num--; last = i + 1; } } for (i = 0; i < n; i++) cout << ans[i] << (i == n - 1 ? '\n' : ' '); num = 1, last = 0; for (i = 0; i < n; i++) { if (i == n - 1 || s[i] == '<') { for (j = i; j >= last; j--) ans[j] = num++; last = i + 1; } } for (i = 0; i < n; i++) cout << ans[i] << (i == n - 1 ? '\n' : ' '); } }
1304
E
1-Trees and Queries
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree? Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees. First, he'll provide you a tree (not 1-tree) with $n$ vertices, then he will ask you $q$ queries. Each query contains $5$ integers: $x$, $y$, $a$, $b$, and $k$. This means you're asked to determine if there exists a path from vertex $a$ to $b$ that contains exactly $k$ edges after adding a bidirectional edge between vertices $x$ and $y$. \textbf{A path can contain the same vertices and same edges multiple times}. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Assume that the length of a path from $a$ to $b$ is $L$. It is obvious that for every non-negative integer $Z$, there exists a path from $a$ to $b$ of length $L + 2Z$ since we can go back and forth any edge along the path any number of times. So, we want to find the shortest path from $a$ to $b$ where the parity (odd or even) of its length is same as the parity of $k$. Since it is a tree, the parity of the length of every paths from $a$ to $b$ is unique. However, if we add another edge, we can possibly find a path of length with different parity. The parity is changed only if you use the added edge odd number of times and the length of the simple path from $x$ to $y$ is even. Since there is no reason to take the path multiple times to find the shortest path of same parity, let's assume we use it only once. If it doesn't change the parity, we can think of it as trying to find a shorter path with same parity of length. Then there are three paths we need to check: The simple path from $a$ to $b$ without using the added edge. The simple path from $a$ to $x$ without using the added edge, plus the added edge, plus the simple path from $y$ to $b$ without using the added edge. The simple path from $a$ to $y$ without using the added edge, plus the added edge, plus the simple path from $x$ to $b$ without using the added edge. Finding the length of each simple path can be done in $O(\log{n})$ time using the well-known LCA (Lowest Common Ancestor) algorithm with $O(n\log{n})$ pre-processing. Now for the ones that have the same parity of length as $k$, we need to determine if the minimum of them is less than or equal to $k$. If there are no such paths, the answer is "NO". Otherwise the answer is "YES". Time complexity: $O((n+q)\log{n})$.
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100000; const int LIM = 17; const int INF = (int)1e9 + 7; vector<int> adj[MAX_N + 5]; int depth[MAX_N + 5]; int par[MAX_N + 5][LIM + 1]; void build(int cur, int p) { int i; depth[cur] = depth[p] + 1; par[cur][0] = p; for (i = 1; i <= LIM; i++) par[cur][i] = par[par[cur][i - 1]][i - 1]; for (int x : adj[cur]) if (x != p) build(x, cur); } int lca_len(int a, int b) { int i, len = 0; if (depth[a] > depth[b]) swap(a, b); for (i = LIM; i >= 0; i--) { if (depth[par[b][i]] >= depth[a]) { b = par[b][i]; len += (1 << i); } } if (a == b) return len; for (i = LIM; i >= 0; i--) { if (par[a][i] != par[b][i]) { a = par[a][i]; b = par[b][i]; len += (1 << (i + 1)); } } return len + 2; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, q, i; cin >> n; for (i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } build(1, 0); cin >> q; while (q--) { int x, y, a, b, k; cin >> x >> y >> a >> b >> k; int without = lca_len(a, b); int with = min(lca_len(a, x) + lca_len(y, b), lca_len(a, y) + lca_len(x, b)) + 1; int ans = INF; if (without % 2 == k % 2) ans = without; if (with % 2 == k % 2) ans = min(ans, with); cout << (ans <= k ? "YES" : "NO") << '\n'; } }
1304
F1
Animal Observation (easy version)
\textbf{The only difference between easy and hard versions is the constraint on} $k$. Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue. Gildong is going to take videos for $n$ days, starting from day $1$ to day $n$. The forest can be divided into $m$ areas, numbered from $1$ to $m$. He'll use the cameras in the following way: - On every odd day ($1$-st, $3$-rd, $5$-th, ...), bring the red camera to the forest and record a video for $2$ days. - On every even day ($2$-nd, $4$-th, $6$-th, ...), bring the blue camera to the forest and record a video for $2$ days. - If he starts recording on the $n$-th day with one of the cameras, the camera records for only one day. Each camera can observe $k$ consecutive areas of the forest. For example, if $m=5$ and $k=3$, he can put a camera to observe one of these three ranges of areas for two days: $[1,3]$, $[2,4]$, and $[3,5]$. Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for $n$ days. \textbf{Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.}
For simplicity, we'll assume that there is the $n+1$-st day when no animals appear at all. Let's say $animal[i][j]$ is the number of animals appearing in the $j$-th area on the $i$-th day. Let's define $DP[i][j]$ ($1 \le i \le n, 1 \le j \le m - k + 1$) as the maximum number of animals that can be observed in total since day $1$, if Gildong puts a camera on the $i$-th day to observe area $[j, j+k-1]$ in day $i$ and $i+1$. Obviously, $DP[1][j]$ is the sum of the number of animals in area $[j, j+k-1]$ in day $1$ and day $2$. Now, for each day since day $2$, let's find three values to determine $DP[i][j]$, which is the maximum among them. For all $x$ ($1 \le x \le j-k$), maximum of $DP[i-1][x]$ plus $sum(animal[i \ldots i+1][j \ldots j+k-1])$. For all $y$ ($j+k \le y \le m-k+1$), maximum of $DP[i-1][y]$ plus $sum(animal[i \ldots i+1][j \ldots j+k-1])$. For all $z$ ($j-k+1 \le z \le j+k-1$), maximum of $DP[i-1][z]$ plus $sum(animal[i \ldots i+1][j \ldots j+k-1])$ minus the sum of animals in the intersected area on the $i$-th day. The summation parts can be calculated in $O(1)$ time by prefix sum technique after $O(nm)$ pre-processing. For the ones that have no intersection, we can pre-calculate the prefix max and suffix max for the values in $DP[i-1]$ in $O(m)$ time for each day, therefore finding it in $O(1)$ as well. Since $k$ is small in this problem, we can naively check all cases when there are one or more intersected areas. For each area we need to check $O(k)$ cases each in $O(1)$ time, so the problem can be solved in $O(nmk)$ time in total.
[ "data structures", "dp" ]
2,300
#include <bits/stdc++.h> using namespace std; const int MAX_N = 50; const int MAX_M = 20000; const int MAX_K = 20; int animal[MAX_N + 5][MAX_M + 5]; int psum[MAX_N + 5][MAX_M + 5]; int lmax[MAX_N + 5][MAX_M + 5]; int rmax[MAX_N + 5][MAX_M + 5]; int dp[MAX_N + 5][MAX_M + 5]; inline int ps(int i, int j, int k) { return psum[i][k] - psum[i][j - 1]; } int main() { ios::sync_with_stdio(false); cin.tie(0); int i, j; int n, m, k; cin >> n >> m >> k; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cin >> animal[i][j]; psum[i][j] = psum[i][j - 1] + animal[i][j]; } } for (i = 1; i <= n; i++) { for (j = 1; j <= m - k + 1; j++) { int p = ps(i, j, j + k - 1) + ps(i + 1, j, j + k - 1); if (i == 1) { dp[i][j] = p; continue; } int mx = 0; for (int x = max(1, j - k + 1); x <= min(m - k + 1, j + k - 1); x++) mx = max(mx, dp[i - 1][x] + p - ps(i, max(x, j), min(x + k - 1, j + k - 1))); dp[i][j] = mx; if (j > k) dp[i][j] = max(dp[i][j], lmax[i - 1][j - k] + p); if (j + k - 1 <= m - k) dp[i][j] = max(dp[i][j], rmax[i - 1][j + k] + p); } for (j = 1; j <= m - k + 1; j++) lmax[i][j] = max(lmax[i][j - 1], dp[i][j]); for (j = m - k + 1; j >= 1; j--) rmax[i][j] = max(rmax[i][j + 1], dp[i][j]); } cout << *max_element(dp[n] + 1, dp[n] + m + 1) << '\n'; }
1304
F2
Animal Observation (hard version)
\textbf{The only difference between easy and hard versions is the constraint on} $k$. Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue. Gildong is going to take videos for $n$ days, starting from day $1$ to day $n$. The forest can be divided into $m$ areas, numbered from $1$ to $m$. He'll use the cameras in the following way: - On every odd day ($1$-st, $3$-rd, $5$-th, ...), bring the red camera to the forest and record a video for $2$ days. - On every even day ($2$-nd, $4$-th, $6$-th, ...), bring the blue camera to the forest and record a video for $2$ days. - If he starts recording on the $n$-th day with one of the cameras, the camera records for only one day. Each camera can observe $k$ consecutive areas of the forest. For example, if $m=5$ and $k=3$, he can put a camera to observe one of these three ranges of areas for two days: $[1,3]$, $[2,4]$, and $[3,5]$. Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for $n$ days. \textbf{Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.}
We can further advance the idea we used in F1 to reduce the time complexity. Solution: $O(nm\log{m})$ Let's generalize all three cases we discussed in F1. Let's make a lazy segment tree supporting range addition update and range maximum query. Each node represents the maximum value of ($DP[i-1]$ minus the sum of the animals appearing on the $i$-th day in the intersected area) in the corresponding interval. Then we can add $sum(animal[i \ldots i+1][j \ldots j+k-1])$ to the maximum value of the segment tree to determine $DP[i][j]$. For the $i$-th day, we insert $DP[i-1][j]$ in the respective index of the segment tree for all $j$ ($1 \le j \le m-k+1$) initially. Now, to determine $DP[i][j]$ for each $j$, we want to subtract $sum(animal[i][max(j, x) \ldots min(j, x)+k-1])$ from the segment tree for all $x$ ($1 \le x \le m-k+1$). But it is infeasible to do this and add them back for every single $x$-s that has intersected areas. Here, we can use sliding window technique to improve it. To determine $DP[i][1]$, we can manually subtract the first $k$ elements of $animal[i]$ from the segment tree like above. Let's assume that we're done with determining $DP[i][j-1]$. When we move on to determining $DP[i][j]$, we can see that $animal[i][j-1]$ is no longer in the range and thus should be added back to the segment tree. Precisely, all $DP[i-1][x]$-s where $x$ is within range $[max(1, j-k), j-1]$ are affected by this and must be added with $animal[i][j-1]$. Similarly, $animal[i][j+k-1]$ is now in the range and thus should be subtracted from all $DP[i-1][y]$-s where $y$ is within range $[j, j+k-1]$. Each range update takes $O(\log{m})$ time, and this happens only two times for determining each $DP[i][j]$. The 'initial' work takes $O(k)$ time but it happens only once for each day. Therefore, it takes $O(m\log{m})$ time for each day and $O(nm\log{m})$ time in total. Solution: $O(nm)$ It turns out that it's even possible without the segment tree. Of course, $O(nm\log{m})$ is intended to pass so you don't really need to implement this to solve the problem. Instead of segment tree, we'll use monotonic queue structure (the core idea for convex hull trick) to have the values in decreasing order from front to back. If you don't know what monotonic queue is, make sure you understand it first. You can read about it here. We'll do basically the same thing we did for $O(nm\log{m})$ solution, but there are two major differences. First, we'll slide the window two times, one from left to right and the other one from right to left. Second, we'll only consider the values where the range of their indices intersects with the window, but only a part of them. We'll see how it works when sliding the window from left to right, then we can also do it in reverse direction. We'll only consider all $DP[i-1][x]$ where $x$ is within range $[max(1, j-k+1), j]$. In other words, we only consider it when the intersected area is a prefix of the window. This means when we're about to determine $DP[i][j]$, $DP[i-1][j]$ (in fact, the actual value will be $DP[i-1][j] - sum(animal[i][j \ldots j+k-1])$) is inserted into the queue and $DP[i-1][j-k]$ is removed from the queue. Now let's see how the 'real' values in the queue are changed while sliding the window. Since we'll only add the same value to all elements in the queue every time we slide the window, the order of the elements won't be changed, thus maintaining the monotone queue structure. However, we don't actually need to perform the 'add' action, simply because we can always calculate it in $O(1)$ time by calculating the sum of the animals between the index of that element (inclusive) and the window (exclusive). So to the 'real' value at the front of the queue, we can add $sum(animal[i \ldots i+1][j \ldots j+k-1])$ to determine $DP[i][j]$. The exact same thing can be done in the reversed way, too. Now let's take back the prefix and suffix max we discussed in F1, so that we can check the cases when they do not intersect. We can see that each of these operations can be done in $O(m)$ for each day. Therefore, the whole process is performed in $O(nm)$ time.
[ "data structures", "dp", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; using vi = vector<int>; using vvi = vector<vi>; const int MAX_N = 50; const int MAX_M = 20000; const int MAX_K = 20; int n, m, k; inline int ps(vvi &p, int i, int s, int e) { if (s < 1) return p[i][e]; return p[i][e] - p[i][s - 1]; } void calc_overlapped(vvi &ar, vvi &p, vvi &dp, int i) { int j; deque<pii> dq; for (j = 1; j <= m - k + 1; j++) { int num = dp[i - 1][j] - ps(p, i, j, j + k - 1); if (dq.size() && dq.front().second <= j - k) dq.pop_front(); while (dq.size() && dq.back().first + ps(p, i, dq.back().second, j - 1) <= num) dq.pop_back(); dq.push_back({ num, j }); dp[i][j] = dq.front().first + ps(p, i, dq.front().second, j - 1) + ps(p, i, j, j + k - 1) + ps(p, i + 1, j, j + k - 1); } } int main() { ios::sync_with_stdio(false); cin.tie(0); int i, j; cin >> n >> m >> k; vvi init(n + 5, vi(m + 5, 0)); vvi animal, animal_rev, psum, psum_rev, lmax, rmax, dp, dpl, dpr; animal = animal_rev = psum = psum_rev = lmax = rmax = dp = dpl = dpr = init; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cin >> animal[i][j]; psum[i][j] = psum[i][j - 1] + animal[i][j]; animal_rev[i][m - j + 1] = animal[i][j]; } for (j = 1; j <= m; j++) psum_rev[i][j] = psum_rev[i][j - 1] + animal_rev[i][j]; } deque<pii> dq; for (i = 1; i <= n; i++) { for (j = 1; j <= m - k + 1; j++) { if (j > k) dp[i][j] = lmax[i - 1][j - k]; if (j <= m - k * 2 + 1) dp[i][j] = max(dp[i][j], rmax[i - 1][j + k]); dp[i][j] += ps(psum, i, j, j + k - 1) + ps(psum, i + 1, j, j + k - 1); } calc_overlapped(animal, psum, dpl, i); calc_overlapped(animal_rev, psum_rev, dpr, i); for (j = 1; j <= m - k + 1; j++) { dp[i][j] = max({ dp[i][j], dpl[i][j], dpr[i][m - j - k + 2] }); dpl[i][j] = dpr[i][m - j - k + 2] = dp[i][j]; } for (j = 1; j <= m - k + 1; j++) lmax[i][j] = max(lmax[i][j - 1], dp[i][j]); for (j = m - k + 1; j >= 1; j--) rmax[i][j] = max(rmax[i][j + 1], dp[i][j]); } cout << *max_element(dp[n].begin(), dp[n].end()) << endl; }
1305
A
Kuroni and the Gifts
Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets: - the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are \textbf{pairwise distinct} (i.e. all $a_i$ are different), - the $i$-th bracelet has a brightness $b_i$, where all the $b_i$ are \textbf{pairwise distinct} (i.e. all $b_i$ are different). Kuroni wants to give \textbf{exactly one} necklace and \textbf{exactly one} bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be \textbf{pairwise distinct}. Formally, if the $i$-th daughter receives a necklace with brightness $x_i$ and a bracelet with brightness $y_i$, then the sums $x_i + y_i$ should be pairwise distinct. Help Kuroni to distribute the gifts. For example, if the brightnesses are $a = [1, 7, 5]$ and $b = [6, 1, 2]$, then we may distribute the gifts as follows: - Give the third necklace and the first bracelet to the first daughter, for a total brightness of $a_3 + b_1 = 11$. - Give the first necklace and the third bracelet to the second daughter, for a total brightness of $a_1 + b_3 = 3$. - Give the second necklace and the second bracelet to the third daughter, for a total brightness of $a_2 + b_2 = 8$. Here is an example of an \textbf{invalid} distribution: - Give the first necklace and the first bracelet to the first daughter, for a total brightness of $a_1 + b_1 = 7$. - Give the second necklace and the second bracelet to the second daughter, for a total brightness of $a_2 + b_2 = 8$. - Give the third necklace and the third bracelet to the third daughter, for a total brightness of $a_3 + b_3 = 7$. This distribution is \textbf{invalid}, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!
We claim that if we sort the arrays $a$ and $b$, then giving the $i$-th daughter the $i$-th necklace and the $i$-th bracelet is a valid distribution. Notice that since all elements in each array are distinct, we have $a_1 < a_2 < \dots < a_n$ $b_1 < b_2 < \dots < b_n$ Then $a_i + b_i < a_{i + 1} + b_i < a_{i + 1} + b_{i + 1}$ for $1 \le i \le n$, so $a_1 + b_1 < a_2 + b_2 < \dots < a_n + b_n$ And all these sums are distinct.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
800
T = int(input()) for _ in range(T): n = int(input()) A = sorted(list(map(int, input().split()))) B = sorted(list(map(int, input().split()))) print(*A) print(*B)
1305
B
Kuroni and Simple Strings
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence! We say that a string formed by $n$ characters '(' or ')' is \textbf{simple} if its length $n$ is even and positive, its first $\frac{n}{2}$ characters are '(', and its last $\frac{n}{2}$ characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple. Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. \textbf{Note that this subsequence doesn't have to be continuous}. For example, he can apply the operation to the string {')\textbf{(})\textbf{(}()\textbf{))}'}, to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string \textbf{does not} have to be empty. Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead? A sequence of characters $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.
We claim that the answer is always $0$ or $1$. First, note we can't apply any operations if and only if each '(' symbol is left from each ')' symbol, so that the string looks as ')))(((((('. Let $a_1, a_2, \dots, a_p$ be the indexes of symbols '(' in the string, and $b_1, b_2, \dots, b_q$ be the indexes of symbols ')' in the string. Let $i$ be the largest index for which $a_i < b_{q-i+1}$. We claim that we can delete subsequence $\{a_1, a_2, \dots, a_i, b_{q-i+1}, \dots, b_{q-1}, b_q\}$, and won't be able to apply any operation to the resulting string. Indeed, suppose that in the resulting string some '(' symbol will be to the left from some ')' symbol, say they were $a_k$ and $b_l$ in out sequences. Then we must have $k>i$ and $l<q-i+1$, as they weren't deleted yet. So, we get that $b_{i+1} \le b_k < b_l \le b_{q-i}$, so $i$ wasn't maximal. In other words, just pick brackets greedily from ends, forming as large simple string as you can. Asymptotics $O(|s|)$.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
1,200
string = input() oList, cList = [], [] for i in range(len(string)): if string[i] == '(': oList.append(i) if string[i] == ')': cList.append(i) oPtr, cPtr = 0, len(cList)-1 removal = [] while oPtr < len(oList) and cPtr >= 0: if oList[oPtr] > cList[cPtr]: break removal.append(oList[oPtr]) removal.append(cList[cPtr]) oPtr += 1 cPtr -= 1 removal.sort() if len(removal) == 0: print(0) else: print('1\n{}\n{}'.format(len(removal), ' '.join([str(x+1) for x in removal])))
1305
C
Kuroni and Impossible Calculation
To become the king of Codeforces, Kuroni has to solve the following problem. He is given $n$ numbers $a_1, a_2, \dots, a_n$. Help Kuroni to calculate $\prod_{1\le i<j\le n} |a_i - a_j|$. As result can be very big, output it modulo $m$. If you are not familiar with short notation, $\prod_{1\le i<j\le n} |a_i - a_j|$ is equal to $|a_1 - a_2|\cdot|a_1 - a_3|\cdot$ $\dots$ $\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$ $\dots$ $\cdot|a_2 - a_n| \cdot$ $\dots$ $\cdot |a_{n-1} - a_n|$. In other words, this is the product of $|a_i - a_j|$ for all $1\le i < j \le n$.
Let's consider $2$ cases. $n\le m$. Then we can calculate this product directly in $O(n^2)$. $n\le m$. Then we can calculate this product directly in $O(n^2)$. $n > m$. Note that there are only $m$ possible remainders under division by $m$, so some $2$ numbers of $n$ have the same remainder. Then their difference is divisible by $m$, so the entire product is $0 \bmod m$. $n > m$. Note that there are only $m$ possible remainders under division by $m$, so some $2$ numbers of $n$ have the same remainder. Then their difference is divisible by $m$, so the entire product is $0 \bmod m$. Asymptotic $O(m^2)$.
[ "brute force", "combinatorics", "math", "number theory" ]
1,600
n, m = map(int, input().split()) a = list(map(int, input().split())) if n > m: exit(print(0)) ans = 1 for i in range(n): for j in range(i+1, n): ans *= abs(a[i] - a[j]) ans %= m print(ans)
1305
D
Kuroni and the Celebration
\textbf{This is an interactive problem.} After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost! The United States of America can be modeled as a tree (why though) with $n$ vertices. The tree is rooted at vertex $r$, wherein lies Kuroni's hotel. Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $u$ and $v$, and it'll return a vertex $w$, which is the lowest common ancestor of those two vertices. However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $\lfloor \frac{n}{2} \rfloor$ times. After that, the phone would die and there will be nothing left to help our dear friend! :( As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?
For each question, pick any two leaves $u$ and $v$ and ask for the lowest common ancestor of them. The answer is either $u$ or $v$: The root of the tree must be the answer we received. The answer is neither $u$ nor $v$: Since $u$ and $v$ are leaves, there are no other vertices that lie within the subtree of either of these vertices. We remove $u$ and $v$ from the tree and repeat the process. We repeat the process until we find the root in one of the question, or there is one vertex remaining in tree which will be our root. Complexity: $O(n)$.
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
1,900
from sys import stdout def ask(u, v): print('? {} {}'.format(u+1, v+1)) stdout.flush() return (int(input()) - 1) def answer(r): print('! {}'.format(r+1)) stdout.flush() exit() n = int(input()) adj = [{} for _ in range(n)] isLeaf = {} def purge(z, last, blockpoint): if z in isLeaf: isLeaf.pop(z) for t in adj[z].keys(): if t == last: continue if t == blockpoint: adj[t].pop(z) elif len(adj[t]) > 0: purge(t, z, blockpoint) adj[z].clear() for _ in range(n-1): x, y = map(lambda s: int(s)-1, input().split()) adj[x][y] = True adj[y][x] = True for i in range(n): if len(adj[i]) == 1: isLeaf[i] = True while len(isLeaf) > 1: taken = [] for key in isLeaf.keys(): taken.append(key) if len(taken) == 2: break for key in taken: isLeaf.pop(key) w = ask(taken[0], taken[1]) if w in taken: answer(w) for key in taken: purge(key, -1, w) if len(adj[w]) <= 1: isLeaf[w] = True for key in isLeaf.keys(): answer(key)
1305
E
Kuroni and the Score Distribution
Kuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round. The round consists of $n$ problems, numbered from $1$ to $n$. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array $a_1, a_2, \dots, a_n$, where $a_i$ is the score of $i$-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: - The score of each problem should be a positive integer not exceeding $10^9$. - A harder problem should grant a strictly higher score than an easier problem. In other words, $1 \leq a_1 < a_2 < \dots < a_n \leq 10^9$. - The \textbf{balance} of the score distribution, defined as the number of triples $(i, j, k)$ such that $1 \leq i < j < k \leq n$ and $a_i + a_j = a_k$, should be exactly $m$. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output $-1$.
Firstly, note that for each $i$, there can't be more than $\lfloor \frac{i-1}{2} \rfloor$ triples of form $(x, y, i)$ with $a_x + a_y = a_i$. This is true as every index $j$ can meet at most once among all $x, y$ (as the third index is uniquely determined by $i$, $j$). Therefore, the answer can't exceed $\lfloor \frac{0}{2} \rfloor + \lfloor \frac{1}{2} \rfloor + \dots + \lfloor \frac{n-1}{2} \rfloor = N$. So, if $m>N$, answer is $-1$. Note that the sequence $a_i = i$ has balance exactly $N$. Now we show how to construct the answer for any given $m\le N$. If $m = N$, we just output sequence $a_i = i$. Now suppose that $\sum_{i = 1}^k \lfloor \frac{i-1}{2} \rfloor \le m < \sum_{i = 1}^{k+1} \lfloor \frac{i-1}{2} \rfloor$ for some $k$. Then let's choose $a_i = i$ for $i = 1, 2, \dots, k$, and choose $a_{k+1} = 2k + 1 - 2(m - \sum_{i = 1}^k \lfloor \frac{i-1}{2})$. We get balance of $\sum_{i = 1}^k \lfloor \frac{i-1}{2} \rfloor$ from first $k$ numbers, and $m - \sum_{i = 1}^k \lfloor \frac{i-1}{2} \rfloor$ triples of form $(x, y, k+1)$ (precisely $(k + 1 - 2(m - \sum_{i = 1}^k \lfloor \frac{i-1}{2} \rfloor), k, k+1), (k + 2 - 2(m - \sum_{i = 1}^k \lfloor \frac{i-1}{2} \rfloor), k-1, k+1), \dots$). We have achieved the desired balance now, and just have to choose $a_i$ for $i>k+1$ such that they don't form any other good triples. For this, we can take $a_i = 10^8 + 1 + 10^4i$ for $i>k+1$, for example (sum of two odd numbers can't be odd, no $a_i$ with $i>k+1$ can be equal to $a_x + a_y$ with $x, y\le k+1$ as $a_i$ is much larger, and $a_x + a_y = a_i$ for $i, y>k+1, x\le k+1$ is impossible as $a_x<10^4$).
[ "constructive algorithms", "greedy", "implementation", "math" ]
2,200
n, m = map(int, input().split()) numList = [x+1 for x in range(n)] backdoor = [] count = sum([(i-1) // 2 for i in range(1, n+1)]) if count < m: exit(print(-1)) while count > m: lastpop = numList.pop() count -= (lastpop - 1) // 2 if count >= m: if len(backdoor) == 0: backdoor.append(10 ** 9) else: backdoor.append(backdoor[-1] - 2 ** 16) else: gap = m - count backdoor.append(2 * (lastpop - gap) - 1) count += gap while len(backdoor) > 0: numList.append(backdoor.pop()) print(' '.join([str(x) for x in numList]))
1305
F
Kuroni and the Punishment
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem: You have an array $a$ consisting of $n$ positive integers. An operation consists of choosing an element and either adding $1$ to it or subtracting $1$ from it, such that the element remains positive. We say the array is \textbf{good} if the greatest common divisor of all its elements is not $1$. Find the minimum number of operations needed to make the array good. Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!
First, let's assume we have a fixed positive integer $d \ge 2$, and we want to find the minimum number of operations needed to make all elements divisible by $d$. Then a simple greedy algorithm gives us the answer: For each element $x$ just apply operations to transform it into the closest multiple of $d$, which is either $x - x \bmod{d}$ or $x + d - x \bmod{d}$. This gives us a linear algorithm. Now we will reduce the integers that we have to check to a small set, and use this greedy algorithm to check each. First look at what happens if we choose $d = 2$. Every number is at distance at most $1$ from a multiple of $2$, so we apply at most one operation on each number. Therefore the answer to the problem is at most $n$. Now, notice that since the answer to the problem is at most $n$, when we apply the optimal sequence of operations there are at least $\frac{n}{2}$ elements which are affected by at most one operation. Therefore, if we choose an element $x$ of the array at random, with probability at least $\frac{1}{2}$ an optimal solution will be given by a prime divisor of $x$, $x - 1$ or $x + 1$. Then, to solve the problem we can repeatedly choose a random element $x$ of the array, find the prime factors of $x$, $x - 1$ and $x + 1$, and run our greedy algorithm with these prime factors. If we run this for enough operations we find the optimal answer with a very high probability. Final complexity is $O(it(\sqrt{MAX} + n \log MAX))$ where $it$ denotes the number of elements we choose. This is because we can factor in $O(\sqrt{MAX})$ and each number has $O(\log MAX)$ prime divisors. For $it = 20$ the probability of failure for each test case is at most $2^{-20}$, which is small enough to be sure that it is correct.
[ "math", "number theory", "probabilities" ]
2,500
import random n = int(input()) a = list(map(int, input().split())) limit = min(8, n) iterations = [x for x in range(n)] random.shuffle(iterations) iterations = iterations[:limit] def factorization(x): primes = [] i = 2 while i * i <= x: if x % i == 0: primes.append(i) while x % i == 0: x //= i i = i + 1 if x > 1: primes.append(x) return primes def solve_with_fixed_gcd(arr, gcd): result = 0 for x in arr: if x < gcd: result += (gcd - x) else: remainder = x % gcd result += min(remainder, gcd - remainder) return result answer = float("inf") prime_list = set() for index in iterations: for x in range(-1, 2): tmp = factorization(a[index]-x) for z in tmp: prime_list.add(z) for prime in prime_list: answer = min(answer, solve_with_fixed_gcd(a, prime)) if answer == 0: break print(answer)
1305
G
Kuroni and Antihype
Kuroni isn't good at economics. So he decided to found a new financial pyramid called \textbf{Antihype}. It has the following rules: - You can join the pyramid for free and get $0$ coins. - If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). $n$ people have heard about Antihype recently, the $i$-th person's age is $a_i$. Some of them are friends, but friendship is a weird thing now: the $i$-th person is a friend of the $j$-th person \textbf{if and only if} $a_i \text{ AND } a_j = 0$, where $\text{AND}$ denotes the bitwise AND operation. Nobody among the $n$ people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them?
Let's forget about the structure of our graph of friendship first and let's solve a more general problem: what are the highest possible total gainings of all people given some edges. Firstly, let's suppose there is a $n+1$-th person with age $a_{n+1} = 0$ in Antihype already, who is friend with everybody. We can suppose that instead of someone joining Antihype for free, he is invited by this person. Now, let's color the edge between $i$ and $j$ in red if $a_i$ invited $a_j$ or $a_j$ invited $a_i$. Note that red edges form a tree. Let's write on an edge between $i$ and $j$ $a_i + a_j$. Surprising fact: For a given tree $G$ of invitations, the total gainings are equal to the sum of numbers on the edges of the tree - sum of all $a_i$! Proof: Suppose that the degree of person $i$ in $G$ is $v_i$. Then this person was invited once and invited $v_i - 1$ times, giving $a_i(v_i - 1)$ coins in total. $\sum_{i = 1}^{n+1} a_i(v_i - 1) = \sum_{i = 1}^{n+1} a_i\cdot v_i - \sum_{i = 1}^{n+1} a_i = \sum_{(i, j)\in G} (a_i + a_j) - \sum_{i = 1}^{n+1} a_i$. Now the solution is easy: on each edge $(i, j)$, write $a_i + a_j$ on it, find Maximum Spanning Tree, and subtract sum of $a_i$. The $n+1$-th person works out well in out version of the problem: he is friend of everybody as $a_{n+1}\text{ AND }a_i = 0\text{ AND }a_i = 0$. However, we can't find MST directly, as there can be $\Omega(n^2)$ edges. There are two approaches now: Approach 1: Find MST with Borůvka's algorithm. Let's do $\log{n}$ iterations of the following: For each mask, find two largest present weights (from different components) which are submasks of this mask in $O(2^{18} \cdot 18)$ with SOS DP. Then, for each component we can find the edge from this component to some other component with the largest weight, and do one iteration of Boruvka. Complexity $O(2^{18} \cdot 18 \cdot log(n)$). Approach 2: Make a list of people with each age first. Now, for $i$ from $2^{18} - 1$ to $0$, iterate through submasks of $i$, let it be $j$, and make edges between people with ages $j$ and $i\text{ XOR }j$, this edge will have weight of $i$. This works in $O(3^{18}\cdot\alpha(n))$, which is fast enough to pass.
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
3,500
import sys range = xrange input = raw_input n = int(input()) A = [int(x) for x in input().split()] m = 2**18 count = [0]*m for a in A: count[a] += 1 count[0] += 1 # Using dsu with O(1) lookup and O(log(n)) merge owner = list(range(m)) sets = [[i] for i in range(m)] total = 0 for profit in reversed(range(m)): a = profit b = a ^ profit while a > b: if count[a] and count[b] and owner[a] != owner[b]: total += (count[a] + count[b] - 1) * profit count[a] = 1 count[b] = 1 small = owner[a] big = owner[b] if len(sets[small]) > len(sets[big]): small, big = big, small for c in sets[small]: owner[c] = big sets[big] += sets[small] a = (a - 1) & profit b = a ^ profit print total - sum(A)
1305
H
Kuroni the Private Tutor
As a professional private tutor, Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him. The exam consists of $n$ questions, and $m$ students have taken the exam. Each question was worth $1$ point. Question $i$ was solved by at least $l_i$ and at most $r_i$ students. Additionally, you know that the total score of all students is $t$. Furthermore, you took a glance at the final ranklist of the quiz. The students were ranked from $1$ to $m$, where rank $1$ has the highest score and rank $m$ has the lowest score. Ties were broken arbitrarily. You know that the student at rank $p_i$ had a score of $s_i$ for $1 \le i \le q$. You wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank $1$, and the maximum possible score for rank $1$ achieving this maximum number of students.
Suppose we fix the scores of the students $b_0 \le b_1 \le \dots \le b_{m-1}$. We model our problem as a flow graph. Consider a flow graph where the left side contains the source and $n$ nodes denoting the problems, and the right side contains the sink and $m$ nodes denoting the students. Each problem node is connected to each student node with capacity $1$. The source is connected to the node for problem $i$ with minimum capacity $L_{i}$ and maximum capacity $R_{i}$. The node for student $i$ is connected to the sink with capacity $b_i$. Our assignment is valid iff there is a valid saturating flow. We can build a flow graph with demands (minimum capacity for some edges) as a normal flow graph. You can find more information on how to build it here: https://cp-algorithms.com/graph/flow_with_demands.html. We want to ensure that our minimum cut is at least $T$. Let $B[i] = \displaystyle\sum_{i=0}^{i}b_i$ (with $B[-1]=0$), $L[i]$ and $R[i]$ denote the sum of the $i$ smallest $L$ and $R$ values respectively. Let $s_L$ denote the sum of all $L$ values. Analyzing the possibilities for minimum cut, we can show that our minimum cut is at least $T$ iff the following two conditions hold for all $0 \le i \le m$ and $0 \le j \le n$: $R[j] + B[i-1] + (n-j)(m-i) \ge T$ $L[j] + B[i-1] + (n-j)(m-i) \ge s_L$ If we fix the values of $b_i$, we can check whether these conditions hold using Convex Hull Trick in $O(n+m)$ (by fixing $i$ and varying $j$). How to determine which $b_i$ values to use. From our formulas, it is clear that if there are no additional restrictions, if two sequences $a_i$, $b_i$ are such that $b_i$ majorizes $a_i$, then $b_i$ is a better choice than $a_i$. We can binary search the maximum number of students with a tie for first place. We try to assign the minimum possible score for each student satisfying all the constraints given. We still have some additional "score" left before our sum of scores reach $T$. We want to determine the maximum score our highest-scoring student can obtain. It can be proven that the set of valid maximum scores forms a range starting from the smallest $x$ such that there exists a valid $b_i$ arrangement satisfying all the problem conditions except the conditions for flow. Thus, we can binary search to find $x$ and also binary search to find the maximum possible score. The solution works in $O((n+m)\log^{2}n)$ time.
[ "binary search", "greedy" ]
3,500
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<int,int> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds; const int N = 150000; //number of problems const int M = 150000; //number of students int L[N+10]; int R[N+10]; int a[N+10]; //array of fixed score ll T; int n,m; void read() { cin>>n>>m; for(int i=0;i<n;i++) //problem score { cin>>L[i]>>R[i]; } for(int i=0;i<m;i++) a[i]=-1; int q; cin>>q; for(int i=0;i<q;i++) { int rk, sc; cin>>rk>>sc; a[m-rk] = sc; } cin>>T; //total score } vector<ll> sortedL,sortedR; struct ConvexHull { struct Line { ll m, c; Line (ll _m, ll _c) : m(_m), c(_c) {} ll pass(ll x) { return m * x + c; } }; deque<Line> d; bool irrelevant(Line Z) { if (int(d.size()) < 2) return false; Line X = d[int(d.size())-2], Y = d[int(d.size())-1]; return (X.c - Z.c) * (Y.m - X.m) <= (X.c - Y.c) * (Z.m - X.m); } void push_line(ll m, ll c) { Line l = Line(m,c); while (irrelevant(l)) d.pop_back(); d.push_back(l); } ll query(ll x) { while (int(d.size()) > 1 && (d[0].c - d[1].c <= x * (d[1].m - d[0].m))) d.pop_front(); return d.front().pass(x); } }; bool check_naive(vector<int> b) //check if your assignment is valid { ll sumB = 0; ll sumL = 0; sort(b.begin(),b.end()); for(int i=0;i<b.size();i++) { sumB+=b[i]; if(a[i]!=-1) assert(a[i]==b[i]); if(i>0) assert(b[i]>=b[i-1]); } for(int i=0;i<n;i++) sumL+=L[i]; assert(int(b.size())==m&&sumB==T); ll cursum=0; for(int i=0;i<=m;i++) { for(int j=0;j<=n;j++) { ll s1 = sortedR[j]+cursum+(n-j)*1LL*(m-i); ll s2 = sortedL[j]+cursum+(n-j)*1LL*(m-i); if(s1<sumB||s2<sumL) return false; } if(i<m) cursum+=b[i]; } return true; } bool check(vector<int> b) //check if your assignment is valid { ll sumB = 0; ll sumL = 0; sort(b.begin(),b.end()); for(int i=0;i<b.size();i++) { sumB+=b[i]; if(a[i]!=-1) assert(a[i]==b[i]); if(i>0) assert(b[i]>=b[i-1]); } for(int i=0;i<n;i++) sumL+=L[i]; assert(int(b.size())==m&&sumB==T); ll cursum=0; ConvexHull ch1,ch2; for(int j=n;j>=0;j--) { ch1.push_line(n-j,-sortedR[j]+j*1LL*m); ch2.push_line(n-j,-sortedL[j]+j*1LL*m); } for(int i=0;i<=m;i++) { ll v1 = -ch1.query(i); ll v2 = -ch2.query(i); if(v1<sumB-(cursum+n*1LL*m)||v2<sumL-(cursum+n*1LL*m)) return false; if(i<m) cursum+=b[i]; } return true; } void greedyrange(vector<int> &v, int l, int r, int ub, ll &S) { if(S<=0) return ; ll ext = 0; for(int i=l;i<=r;i++) { ext+=ub-v[i]; } if(ext<=S) { S-=ext; for(int i=l;i<=r;i++) { v[i]=ub; } return ; } deque<ii> dq; for(int i=l;i<=r;i++) { if(!dq.empty()&&dq.back().fi==v[i]) { dq.back().se++; } else { dq.pb({v[i],1}); } } while(S>0&&dq.size()>1) { int L = dq[0].fi; int cnt = dq[0].se; int R = dq[1].fi; //I have (R-L)*cnt before absolute merge if((R-L)*1LL*cnt<=S) { S-=(R-L)*1LL*cnt; dq[1].se+=cnt; dq.pop_front(); continue; } //not enough space liao ll q = S/cnt; ll rem = S%cnt; dq[0].fi+=q; if(rem>0) { ii tmp = dq.front(); dq.pop_front(); dq.push_front({rem,tmp.fi+1}); dq.push_front({cnt-rem,tmp.fi}); } S=0; break; } //S>0 if(S>0) { assert(int(dq.size())==1); ll q = S/(r-l+1); ll rem = S%(r-l+1); for(int i=l;i<=r;i++) { v[i]=dq[0].fi+q; } int ptr=r; for(int i=0;i<rem;i++) { v[ptr--]++; } S=0; } else { int ptr=l; for(ii x:dq) { for(int j=0;j<x.se;j++) v[ptr++]=x.fi; } } } void greedy(vector<int> &v, ll &S) { if(S<=0) return ; vi ans; vector<ii> ranges; int l=0; for(int i=0;i<m;i++) { if(a[i]==-1) continue; if(l<=i-1) { ranges.pb({l,i-1}); } l=i+1; } if(l<m) ranges.pb({l,m-1}); for(ii x:ranges) { int r=x.se; int ub = n; if(r+1<m&&a[r+1]!=-1) ub=a[r+1]; greedyrange(v,x.fi,x.se,ub,S); } } ii solve_full() { sortedL.clear(); sortedR.clear(); sortedL.pb(0); sortedR.pb(0); for(int i=0;i<n;i++) { sortedL.pb(L[i]); sortedR.pb(R[i]); } sort(sortedL.begin(),sortedL.end()); sort(sortedR.begin(),sortedR.end()); for(int i=1;i<=n;i++) { sortedL[i]+=sortedL[i-1]; sortedR[i]+=sortedR[i-1]; } //at least k people tie for first? int lo = 1; int hi = m; int anstie = -1; int ansm = 0; vector<int> testb; vi ori(m,-1); while(lo<=hi) { int mid=(lo+hi)>>1; vector<int> b; int curmin=0; ll cursum=0; for(int i=0;i<m;i++) { if(a[i]!=-1) curmin=a[i]; b.pb(curmin); cursum+=b[i]; } //left T - cursum stuff to add :( //fix the maximum M bool pos=0; int forcedM=-1; for(int j=m-mid;j<m;j++) { if(a[j]>=0) { if(forcedM>=0&&forcedM!=a[j]) forcedM=-2; forcedM = a[j]; } } if(forcedM>=-1) { int L2 = curmin; int R2 = n; if(forcedM>=0) L2=R2=forcedM; //otherwise L2 is the smallest d+curmin such that there EXIST a good covering if(forcedM<0) { int lo2 = curmin; int hi2 = max(0LL,min(ll(n),(T-cursum)/mid+curmin)); //add to everyone i guess L2=int(1e9); while(lo2<=hi2) { int mid2=(lo2+hi2)>>1; vector<int> nwb = b; ll rem = T - cursum; int M = mid2; for(int j=m-mid;j<m;j++) { rem+=b[j]; rem-=M; nwb[j]=M; if(a[j]>=0&&nwb[j]!=a[j]) {rem=-ll(1e18);} ori[j]=a[j]; a[j]=M; } greedy(nwb, rem); for(int j=m-mid;j<m;j++) { a[j]=ori[j]; } if(rem==0) { hi2=mid2-1; L2=mid2; } else { lo2=mid2+1; } } } //how to figure out L2 otherwise!? while(L2<=R2) { int M = (L2+R2)>>1; vector<int> nwb = b; ll rem = T - cursum; for(int j=m-mid;j<m;j++) { rem+=b[j]; rem-=M; nwb[j]=M; if(a[j]>=0&&nwb[j]!=a[j]) {rem=-ll(1e18);} ori[j]=a[j]; a[j]=M; } greedy(nwb, rem); if(rem==0&&check(nwb)) { testb=nwb; ansm=M; pos=1; L2=M+1; } else { R2=M-1; } for(int j=m-mid;j<m;j++) { a[j]=ori[j]; } } } if(pos) { anstie=mid; lo=mid+1; } else hi=mid-1; } if(anstie==-1) { return {-1,-1}; } return {anstie,ansm}; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); //freopen("student-scores.in","r",stdin); read(); ii sol2 = solve_full(); cout<<sol2.fi<<' '<<sol2.se<<'\n'; }
1307
A
Cow and Haybales
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $n$ haybale piles on the farm. The $i$-th pile contains $a_i$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $i$ and $j$ ($1 \le i, j \le n$) such that $|i-j|=1$ and $a_i>0$ and apply $a_i = a_i - 1$, $a_j = a_j + 1$. She may also decide to not do anything on some days because she is lazy. Bessie wants to maximize the number of haybales in pile $1$ (i.e. to maximize $a_1$), and she only has $d$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $1$ if she acts optimally!
At any point, it is optimal to move a haybale in the closest pile from pile $1$ to the left. So, for every day, we can loop through the piles from left to right and move the first haybale we see closer. If all the haybales are in pile $1$ at some point, we can stop early. Time Complexity: $O(n \cdot d)$
[ "greedy", "implementation" ]
800
#include <iostream> using namespace std; int N,D,a[105],ans; int main(){ int T; cin>>T; while (T--){ cin>>N>>D; for (int i=1;i<=N;i++) cin>>a[i]; for (int i=2;i<=N;i++){ int move=min(a[i],D/(i-1)); //number of haybales we can move from pile i to pile 1 a[1]+=move; //update pile 1 D-=move*(i-1); //update remaining days } cout<<a[1]<<endl; } }
1307
B
Cow and Friend
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $(0,0)$ to $(x,0)$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $n$ favorite numbers: $a_1, a_2, \ldots, a_n$. What is the minimum number of hops Rabbit needs to get from $(0,0)$ to $(x,0)$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination. Recall that the Euclidean distance between points $(x_i, y_i)$ and $(x_j, y_j)$ is $\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$. For example, if Rabbit has favorite numbers $1$ and $3$ he could hop from $(0,0)$ to $(4,0)$ in two hops as shown below. Note that there also exists other valid ways to hop to $(4,0)$ in $2$ hops (e.g. $(0,0)$ $\rightarrow$ $(2,-\sqrt{5})$ $\rightarrow$ $(4,0)$). \begin{center} {\small Here is a graphic for the first example. Both hops have distance $3$, one of Rabbit's favorite numbers.} \end{center} In other words, each time Rabbit chooses some number $a_i$ and hops with distance equal to $a_i$ in any direction he wants. The same number can be used multiple times.
If the distance $d$ is in the set, the answer is $1$. Otherwise, let $y$ denote Rabbit's largest favorite number. The answer is $max(2,\lceil \frac{d}{y}\rceil)$. This is true because clearly the answer is at least $\lceil\frac{d}{y}\rceil$: if it were less Rabbit can't even reach distance $d$ away from the origin. If $\lceil\frac{d}{y}\rceil$ is at least $2$, we can reach $(d,0)$ in exactly that number of hops by hopping to the right $\lceil\frac{d}{y}\rceil-2$ times using $y$ then using the last $2$ hops for up to $2y$ additional distance. Time Complexity: $O(n)$
[ "geometry", "greedy", "math" ]
1,300
#include <iostream> #include <set> #include <algorithm> using namespace std; set<int>a; //you don't have to use set, it was just easier for us int main(){ int T; cin>>T; while (T--){ int N,X; cin>>N>>X; int far=0; //largest favorite number for (int i=0;i<N;i++){ int A; cin>>A; a.insert(A); far=max(far,A); } if (a.count(X)) //X is favorite number cout<<1<<endl; else cout<<max(2,(X+far-1)/far)<<endl; //expression as explained in tutorial a.clear(); } }
1307
C
Cow and Message
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string $s$ of lowercase Latin letters. She considers a string $t$ as hidden in string $s$ if $t$ exists as a subsequence of $s$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $1$, $3$, and $5$, which form an arithmetic progression with a common difference of $2$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $S$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden $3$ times, b is hidden $2$ times, ab is hidden $6$ times, aa is hidden $3$ times, bb is hidden $1$ time, aab is hidden $2$ times, aaa is hidden $1$ time, abb is hidden $1$ time, aaab is hidden $1$ time, aabb is hidden $1$ time, and aaabb is hidden $1$ time. The number of occurrences of the secret message is $6$.
We observe that if the hidden string that occurs the most times has length longer than $2$, then there must exist one that occurs just as many times of length exactly $2$. This is true because we can always just take the first $2$ letters; there can't be any collisions. Therefore, we only need to check strings of lengths $1$ and $2$. Checking strings of length $1$ is easy. To check strings of length $2$, we can iterate across $S$ from left to right and update the number of times we have seen each string of length $1$ and $2$ using DP. Time Complexity: $O(|s|c)$ (c is length of alphabet)
[ "brute force", "dp", "math", "strings" ]
1,500
#include <iostream> using namespace std; typedef long long ll; ll arr1[26],arr2[26][26]; int main(){ string S; cin>>S; for (int i=0;i<S.length();i++){ int c=S[i]-'a'; for (int j=0;j<26;j++) arr2[j][c]+=arr1[j]; arr1[c]++; } ll ans=0; for (int i=0;i<26;i++) ans=max(ans,arr1[i]); for (int i=0;i<26;i++) for (int j=0;j<26;j++) ans=max(ans,arr2[i][j]); cout<<ans<<endl; }
1307
D
Cow and Fields
Bessie is out grazing on the farm, which consists of $n$ fields connected by $m$ bidirectional roads. She is currently at field $1$, and will return to her home at field $n$ at the end of the day. The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has $k$ special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them. After the road is added, Bessie will return home on the shortest path from field $1$ to field $n$. Since Bessie needs more exercise, Farmer John must \textbf{maximize} the length of this shortest path. Help him!
There are a few solutions that involve breadth first search (BFS) and sorting, this is just one of them. First, let's use BFS to find the distance from fields $1$ and $n$ to each special field. For a special field $i$, let $x_i$ denote the distance to node $1$, and $y_i$ denote the distance to $n$. We want to choose two fields $a$ and $b$ to maximize $min(x_a+y_b,y_a+x_b)$. Without loss of generality, suppose $x_a+y_b \le y_a+x_b$. Now we want to maximize $x_a+y_b$ subject to $x_a-y_a \le x_b-y_b$. This can be done by sorting by $x_i-y_i$ and iterating $a$ over $x$ while keeping a suffix maximum array of $y$ to compute $\max_{b>a}{y_b}$. Remember that an upper bound of the answer is the distance between field $1$ and $n$. Time Complexity: $O(n\log{n}+m)$
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
1,900
#include <cstdio> #include <vector> #include <algorithm> const int INF=1e9+7; int N; int as[200005]; std::vector<int> edges[200005]; int dist[2][200005]; int q[200005]; void bfs(int* dist,int s){ std::fill(dist,dist+N,INF); int qh=0,qt=0; q[qh++]=s; dist[s]=0; while(qt<qh){ int x=q[qt++]; for(int y:edges[x]){ if(dist[y]==INF){ dist[y]=dist[x]+1; q[qh++]=y; } } } } int main(){ int M,K; scanf("%d %d %d",&N,&M,&K); for(int i=0;i<K;i++){ scanf("%d",&as[i]); as[i]--; } std::sort(as,as+K); for(int i=0;i<M;i++){ int X,Y; scanf("%d %d",&X,&Y); X--,Y--; edges[X].push_back(Y); edges[Y].push_back(X); } bfs(dist[0],0); bfs(dist[1],N-1); std::vector<std::pair<int,int> > data; for(int i=0;i<K;i++){ data.emplace_back(dist[0][as[i]]-dist[1][as[i]],as[i]); } std::sort(data.begin(),data.end()); int best=0; int max=-INF; for(auto it:data){ int a=it.second; best=std::max(best,max+dist[1][a]); max=std::max(max,dist[0][a]); } printf("%d\n",std::min(dist[0][N-1],best+1)); }
1307
E
Cow and Treats
After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass! On the field, there is a row of $n$ units of grass, each with a sweetness $s_i$. Farmer John has $m$ cows, each with a favorite sweetness $f_i$ and a hunger value $h_i$. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: - The cows from the left and right side will take turns feeding in an order decided by Farmer John. - When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats $h_i$ units. - The moment a cow eats $h_i$ units, it will fall asleep there, preventing further cows from passing it from both directions. - If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo $10^9+7$)? The order in which FJ sends the cows does not matter as long as no cows get upset.
First, we observe that it is impossible to send more than one cow with the same favorite sweetness on the same side without upsetting any of them. This means we can send at most two cows of each favorite sweetness, one on each side. Now, let's assume we know the index of the rightmost cow that came from the left side. For each sweetness $i$, we denote the number of units of grass to the left of the index as $l_i$ and to the right as $r_i$. There are three cases we have to consider. If there does not exist a cow of this favorite sweetness or the one of this favorite sweetness with minimum hunger cannot be satisfied from either direction, then $0$ cows of the type will be asleep. Otherwise, $1$ or $2$ cows will be asleep, and we can derive a simple formula based on $l_i$, $r_i$, and the cows of this type. Remember that we always maximize the number of sleeping cows first. We maintain how much each sweetness contributed to the answer. When we shift this index of the rightmost cow to the right, we can undo and recompute our answer. You can speed up the solution using binary search, but we chose not to require it. We also chose to allow other $O(n^2)$ and $O(n^2\log{n})$ solutions to pass. Time Complexity: $O(n\log{n})$
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
2,500
#include <cstdio> #include <vector> #include <algorithm> #include <cassert> const int MOD=1e9+7; int modexp(int base,int exp){ int ac=1; for(;exp;exp>>=1){ if(exp&1) ac=1LL*ac*base%MOD; base=1LL*base*base%MOD; } return ac; } int inverse(int x){ return modexp(x,MOD-2); } int fs[100005]; int left[100005],right[100005]; std::vector<int> cows[100005];//cows[f]: hunger of cows that like flavor f int asleep[100005]; int ways[100005]; int total_asleep=0,total_ways=1; void calc_ways(int f){ int a=std::upper_bound(cows[f].begin(),cows[f].end(),left[f])-cows[f].begin(); int b=std::upper_bound(cows[f].begin(),cows[f].end(),right[f])-cows[f].begin(); if(a>b) std::swap(a,b); long long cnt2=1LL*a*b-a; int cnt1=a+b; cnt2%=MOD; if(cnt2>0){ asleep[f]=2; ways[f]=cnt2; }else if(cnt1>0){ asleep[f]=1; ways[f]=cnt1; }else{ asleep[f]=0; ways[f]=1; } } //fixed left cow, with hunger left[i] //precondition: such cow exists void calc_ways_stuck(int f){ int b=std::upper_bound(cows[f].begin(),cows[f].end(),right[f])-cows[f].begin(); if(right[f]>=left[f]) b--; int cnt2=b; if(cnt2>0){ asleep[f]=2; ways[f]=cnt2; }else{ asleep[f]=1; ways[f]=1; } } int ans_asleep=0,ans_ways=0; void add_to_ans(int asleep,int ways){ if(asleep>ans_asleep){ ans_asleep=asleep; ans_ways=0; } if(asleep==ans_asleep) ans_ways=(ans_ways+ways)%MOD; } int main(){ int N,M; scanf("%d %d",&N,&M); for(int i=1;i<=N;i++){ scanf("%d",&fs[i]); right[fs[i]]++; } for(int i=0;i<M;i++){ int F,H; scanf("%d %d",&F,&H); cows[F].push_back(H); } for(int f=1;f<=N;f++) std::sort(cows[f].begin(),cows[f].end()); for(int f=1;f<=N;f++){ calc_ways(f); total_asleep+=asleep[f]; total_ways=1LL*total_ways*ways[f]%MOD; } add_to_ans(total_asleep,total_ways); for(int i=1;i<=N;i++){ total_asleep-=asleep[fs[i]]; total_ways=1LL*total_ways*inverse(ways[fs[i]])%MOD; right[fs[i]]--; left[fs[i]]++; if(std::binary_search(cows[fs[i]].begin(),cows[fs[i]].end(),left[fs[i]])){ calc_ways_stuck(fs[i]); int here_asleep=total_asleep+asleep[fs[i]]; int here_ways=1LL*total_ways*ways[fs[i]]%MOD; add_to_ans(here_asleep,here_ways); } calc_ways(fs[i]); total_asleep+=asleep[fs[i]]; total_ways=1LL*total_ways*ways[fs[i]]%MOD; } printf("%d %d\n",ans_asleep,ans_ways); }
1307
F
Cow and Vacation
Bessie is planning a vacation! In Cow-lifornia, there are $n$ cities, with $n-1$ bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering $v$ possible vacation plans, with the $i$-th one consisting of a start city $a_i$ and destination city $b_i$. It is known that only $r$ of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than $k$ consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so. For each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?
We will run a BFS from all the rest stops in parallel and use union-find to determine which rest stops can reach each other directly. We will split each edge into two to simplify this process. Note that this means Bessie can now travel at most $2k$ roads before needing a rest. While we perform the BFS, we also color all nodes that are within distance $k$ from a rest stop and store the rest stop that can reach each colored node in an array. When two frontiers collide, merge them. Let's consider each query individually. First of all, if $a$ can reach $b$ directly, the answer is YES. Otherwise, let's walk $a$ towards $b$ for $k$ edges, and $b$ towards $a$ for $k$ edges. Note that they may cross over $lca(a,b)$ in the process. The walks will not meet because if they did, the condition that $a$ can reach $b$ directly would have been satisfied. Then, the answer is YES if the new $a$ is a colored node, the new $b$ is a colored node, and they both belong to the same component of rest stops which we can check from our union find. Otherwise, the answer is NO. Time Complexity: $O((n+v)\log{n})$
[ "dfs and similar", "dsu", "trees" ]
3,300
#include <cstdio> #include <vector> #include <cassert> #include <queue> #include <algorithm> const int INF=1e9+7; std::vector<int> edges[400005]; int anc[19][400005]; int depth[400005]; void dfs(int node){ for(int child:edges[node]){ edges[child].erase(std::find(edges[child].begin(),edges[child].end(),node)); anc[0][child]=node; for(int k=1;k<19;k++){ anc[k][child]=anc[k-1][anc[k-1][child]]; } depth[child]=depth[node]+1; dfs(child); } } int la(int node,int len){ for(int k=19-1;k>=0;k--){ if(len&(1<<k)){ node=anc[k][node]; } } return node; } int lca(int a,int b){ if(depth[a]<depth[b]) std::swap(a,b); a=la(a,depth[a]-depth[b]); if(a==b) return a; for(int k=19-1;k>=0;k--){ if(anc[k][a]!=anc[k][b]){ a=anc[k][a]; b=anc[k][b]; } } return anc[0][a]; } //move x steps from a to b //assumes x<=dist(a,b) int walk(int a,int b,int x){ int c=lca(a,b); if(x<=depth[a]-depth[c]){ return la(a,x); } int excess=x-(depth[a]-depth[c]); assert(excess<=(depth[b]-depth[c])); return la(b,depth[b]-depth[c]-excess); } int uf[400005]; int dist[400005];//dist[x]=0 iff x is rest stop int find(int a){ while(a!=uf[a]){ a=uf[a]=uf[uf[a]]; } return a; } bool query(int K){ int A,B; scanf("%d %d",&A,&B); A--,B--; int C=lca(A,B); if(depth[A]+depth[B]-2*depth[C]<=2*K){ return true; }else{ return find(walk(A,B,K))==find(walk(B,A,K)); } } int main(){ int N,K,R; scanf("%d %d %d",&N,&K,&R); int oldN=N; for(int i=0;i<oldN-1;i++){ int X,Y; scanf("%d %d",&X,&Y); X--,Y--; edges[X].push_back(N); edges[N].push_back(X); edges[Y].push_back(N); edges[N].push_back(Y); N++; } for(int i=0;i<N;i++){ uf[i]=i; } std::fill(dist,dist+N,INF); std::queue<int> frontier; for(int i=0;i<R;i++){ int X; scanf("%d",&X); X--; dist[X]=0; frontier.push(X); } while(!frontier.empty()){ int x=frontier.front(); if(dist[x]>K-1) break; frontier.pop(); for(int y:edges[x]){ uf[find(y)]=find(x); if(dist[y]==INF){ dist[y]=dist[x]+1; frontier.push(y); } } } dfs(0); int V; scanf("%d",&V); while(V--){ if(query(K)){ printf("YES\n"); }else{ printf("NO\n"); } } }
1307
G
Cow and Exercise
Farmer John is obsessed with making Bessie exercise more! Bessie is out grazing on the farm, which consists of $n$ fields connected by $m$ directed roads. Each road takes some time $w_i$ to cross. She is currently at field $1$ and will return to her home at field $n$ at the end of the day. Farmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed $x_i$ for the $i$-th plan. Determine the maximum he can make the shortest path from $1$ to $n$ for each of the $q$ independent plans.
This problem can be formulated as a linear program, and looks like the LP dual of min-cost flow. LP formulation of min-cost flow (see for example here: https://imada.sdu.dk/%7Ejbj/DM85/mincostnew.pdf): $x_{vw}$ is flow on edge $(v,w)$ $c_{vw}$ is cost on edge $(v,w)$ $u_{vw}$ is capacity on edge $(v,w)$ $b_v$ is demand at vertex $v$ (flow in minus flow out) Find $\min{\Sigma_{vw}c_{vw}x_{vw}}$ subject to $\Sigma_{(v,w)\in E}(x_{wv}-x_{vw})=b_v$ (Hopefully the signs are right.) $0\le x_{vw} \le u_{vw}$ The LP Dual is $\max{\Sigma{b_vy_v}-\Sigma{u_{vw}z_{vw}}}$ $y_w\le y_v+c_{vw}+z_{vw}$ $z_{vw}\ge 0$ This is exactly what we need, except the objective function is a bit messy. Letting $b_{src}=-F$, $b_{snk}=F$, $b_v=0$ for other $v$, $D=y_{snk}-y_{src}$, $C=\Sigma{vw}{u_{vw}z_{vw}}$, the objective becomes $\max{FD-C}$ We have the unweighted case, so assign capacities (cost in original problem) $u_{vw}=1$ for all edges. We can interpret $y_v$ as distance from $src$ and $z_{vw}$ as the amount added to edge edge to it. The set of all valid assignments to the variables form a convex polytope. If we project it onto the 2D space of $D$ and $C$, it will still be convex. By varying $F$, we can get a piecewise linear function describing all Pareto optimal solutions. From this function, we can find the minimum $C$ required to get some fixed $D$ or maximum $D$ achieve by some fixed $C$. Since a feasible solution to a min-cost flow problem is optimal iff it has no negative cost cycles, and both successive shortest path and primal-dual never create negative cycles, they maintain optimal solutions to their current min-cost flow problems, which only differs in $F$. Thus, they effectively trace out the function as $F$ varies from $0$ to maximum. By binary searching and lerping, we can answer queries in $O(\log{N})$. (Since the cost is integral and bounded by $N$, there are at most $N$ linear pieces.) Time Complexity: $O(n^2m+q\log{n})$
[ "flows", "graphs", "shortest paths" ]
3,100
#include <cstdio> #include <queue> #include <vector> #include <stdint.h> #include <algorithm> const long long INF=1e9+7; const long long MAXV=50; const long long MAXE=MAXV*(MAXV-1); long long SRC,SNK; long long elist[MAXE*2]; long long next[MAXE*2]; long long head[MAXV]; long long cap[MAXE*2]; long long cost[MAXE*2]; long long tot=0; void add(long long x,long long c,long long w){ elist[tot]=x; cap[tot]=c; cost[tot]=w; next[tot]=head[x]; head[x]=tot++; } long long dist[MAXV]; long long prev[MAXV]; std::queue<long long> q; long long total_cost=0; long long total_flow=0; int main(){ long long N,M; scanf("%lld %lld",&N,&M); SRC=0,SNK=N-1; std::fill(head,head+N,-1); for(long long i=0;i<M;i++){ long long A,B,C; scanf("%lld %lld %lld",&A,&B,&C); A--,B--; add(A,1,C); add(B,0,-C); } std::vector<std::pair<long long,long long> > crit; crit.push_back({0,0}); while(true){ std::fill(dist,dist+N,INF); dist[SRC]=0; prev[SRC]=-1; q.push(SRC); while(!q.empty()){ long long node=q.front(); q.pop(); for(long long e=head[node];e!=-1;e=next[e]){ long long i=elist[e^1]; if(cap[e]){ if(dist[i]>dist[node]+cost[e]){ dist[i]=dist[node]+cost[e]; prev[i]=e; q.push(i); } } } } crit.push_back({1LL*total_flow*dist[SNK]-total_cost,dist[SNK]}); if(dist[SNK]==INF) break; long long aug=INF; for(long long x=SNK;x!=SRC;x=elist[prev[x]]){ aug=std::min(aug,cap[prev[x]]); } for(long long x=SNK;x!=SRC;x=elist[prev[x]]){ cap[prev[x]]-=aug; cap[prev[x]^1]+=aug; } total_flow+=aug; total_cost+=1LL*dist[SNK]*aug; } long long Q; scanf("%lld",&Q); while(Q--){ long long X; scanf("%lld",&X); auto it=std::lower_bound(crit.begin(),crit.end(),std::pair<long long,long long>{X+1,0}); double D=(long double)((X-(it-1)->first)*it->second+(it->first-X)*((it-1)->second))/(it->first-(it-1)->first); printf("%.10lf\n",D); } return 0; }
1310
A
Recommendations
VK news recommendation system daily selects interesting publications of one of $n$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $i$ batch algorithm selects $a_i$ publications. The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $i$-th category within $t_i$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
In this problem we have an array $a_1, \ldots, a_n$, we can increase each $a_i$ by one with cost $t_i$, and we want to make all $a_i$ different with minimal total cost. Let's sort $a_i$ in a non-decreasing way (and permute the $t$ in a corresponding way). Let's see at the minimal number, $a_1$. If it is unique, e.g. $a_1 \ne a_2$, then we don't need to change $a_1$ - it is already unique, and it can't get equal to something else if we don't increase it. In this case, we can just skip $a_1$ and solve the smaller problem without $a_1$. Otherwise, suppose there is some $j>1$ such that $a_1 = a_2 = \ldots = a_j$. Obviously, we should leave at most one of them with the current value, and increase other $j-1$ numbers by one. Which one should be not increased? We shouldn't increase the $a_l$ ($1 \le l \le j$) with the maximal $t_l$ because it minimizes the total cost. So, we should remove the maximal value $t_l$ among all elements with minimal $a_l$, and increase all other by one. This effectively reduces our problem to the smaller one, decreasing $n$ by one. This gives us a $\mathcal{O}(n^2)$ solution - $n$ times we discard one minimum from the array and increase all other minimums by one. We can further optimize it by using a multiset of values $t_l$ for all minimal $a_l$ and its sum. At each iteration, we should (probably) add some values to a multiset, if the number of minimums in array increases, discard one maximum from multiset and add the current sum to the answer. Continue the process until the array becomes empty. This is an $\mathcal{O}(n \log n)$ solution.
[ "data structures", "greedy", "sortings" ]
1,700
null
1310
B
Double Elimination
The biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. $2^n$ teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from $1$ to $2^n$ and will play games one-on-one. All teams start in the upper bracket. All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket. Lower bracket starts with $2^{n-1}$ teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round $2^k$ teams play a game with each other (teams are split into games by team numbers). $2^{k-1}$ loosing teams are eliminated from the championship, $2^{k-1}$ winning teams are playing $2^{k-1}$ teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have $2^{k-1}$ teams remaining. See example notes for better understanding. Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner. You are a fan of teams with numbers $a_1, a_2, ..., a_k$. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?
The main observation in this problem is that for each set of players that lie in the subtree of any vertex of a binary tree of the upper bracket, exactly one player will win all matches in the upper bracket, and exactly one player will win all matches in the lower bracket. We can define this set of players (in 0-indexation instead of 1-indexation from statement) as $[a \cdot 2^t; (a+1) \cdot 2^t)$ for some $1 \le t \le n$, $0 \le a < {{2^n} \over {2^t}}$. For each fixed $t$ the players with different values of ${id \over {2^t}}$ don't play with each other, and their upper and lower brackets are independent. For each of these sets of players, we are interested only in a number of interesting matches between them, and if the winner of their upper and lower brackets are the teams that are we're fans of. This leads us to the dynamic programming solution: $dp[l \ldots r][f_{up}][f_{lower}]$ - the maximal number of matches between teams with indices in $[l; r)$, if $f_{up} \in \{ 0, 1 \}$ is 1 if the we're fans of winner of upper bracket, and $f_{lower} \in \{ 0, 1 \}$ is 1 if the we're fans of winner of lower bracket. Again, $l \ldots r$ is the special segment: $l = a \cdot 2^t, r =(a+1) \cdot 2^t - 1$ for some $1 \le t \le n$, $0 \le a < {{2^n} \over {2^t}}$. $dp[l \ldots r][f_{up}][f_{lower}]$ can be recalculated from $dp[l \ldots {{l+r} \over 2}][f_{up}^l][f_{lower}^l]$ and $dp[{{l+r} \over 2} \ldots r][f_{up}^r][f_{lower}^r]$ - we just iterate over all possible $f_{up}^l, f_{lower}^l, f_{up}^r, f_{lower}^r$, and the results of all three matches (one in the upper bracket and two in the lower bracket). In the end, we use $dp[0 \ldots 2^n][f_{up}][f_{lower}]$ to count the result with the last, grand-finals match. This solution works in something like $\mathcal{O}(2^n \cdot 2^7)$ because there are $2^n$ interesting segments.
[ "dp", "implementation" ]
2,500
null
1310
C
Au Pont Rouge
VK just opened its second HQ in St. Petersburg! Side of its office building has a huge string $s$ written on its side. This part of the office is supposed to be split into $m$ meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of $s$ written on its side. For each possible arrangement of $m$ meeting rooms we ordered a test meeting room label for the meeting room with lexicographically \textbf{minimal} name. When delivered, those labels got sorted \textbf{backward} lexicographically. What is printed on $k$th label of the delivery?
Let's list all distinct substrings, sort them and make a binary search. Now, we need to count number of ways to make minimal string no more then given one. Let's count inverse value - number of wat to make minimal string greater. It could be done by quadratic dynamic programming $dp_{pos, count}$ - number of ways to split suffix starting at pos to count string all of which are greater then given value. Let's find first position where suffix differs which given string. If next character in suffix is smaller, no part can start here and answer is zero. Otherwise, any longer part is acceptable, so we need to find $\sum\limits_{i > lcp(S, s[pos:])}{dp_{i, count-1}}$, which can be done in O(1) time by suffix sums and precalculating lcp for all pairs of suffixes. Later can by done by another quadratic dynamic programming. lcp of two suffix is equal to 0 if first letter differs, and equal to lcp of two smaller suffixes +1 otherwise.
[ "binary search", "dp", "strings" ]
2,800
null
1310
D
Tourism
Masha lives in a country with $n$ cities numbered from $1$ to $n$. She lives in the city number $1$. There is a direct train route between each pair of distinct cities $i$ and $j$, where $i \neq j$. In total there are $n(n-1)$ distinct routes. Every route has a cost, cost for route from $i$ to $j$ may be different from the cost of route from $j$ to $i$. Masha wants to start her journey in city $1$, take \textbf{exactly} $k$ routes from one city to another and as a result return to the city $1$. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times. Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city $v$, take \textbf{odd} number of routes used by Masha in her journey and return to the city $v$, such journey is considered unsuccessful. Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.
There are two different solutions possible. First, one is to fix all even vertices in the path. It can be done in $O(n^{k/2 - 1})$ time. If it's done, we need to join them by the minimal path of length 2, not going through these vertices. It can be done by precalculating 6 minimal paths of length 2 between each pair of vertices and ignoring no more than 5 best ones until good one found. Another solution is a randomized one. Let's color all vertices in 2 colors in a random way. We can find the best path which is consistent with given coloring in $O(k \cdot E)$ time using dynamic programming. With probability $\frac{1}{512}$ best path overall is consistent with coloring. So, if one repeats this operation $512 \cdot 20$ time, probability of fail would be about $\left(\frac{511}{512}\right)^{512 \cdot 20} \approx e^{-20} \approx 2\cdot 10^{-9}$.
[ "dp", "graphs", "probabilities" ]
2,300
null
1310
E
Strange Function
Let's define the function $f$ of multiset $a$ as the multiset of number of occurences of every number, that is present in $a$. E.g., $f(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 1, 2, 2, 4\}$. Let's define $f^k(a)$, as applying $f$ to array $a$ $k$ times: $f^k(a) = f(f^{k-1}(a)), f^0(a) = a$. E.g., $f^2(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 2, 2\}$. You are given integers $n, k$ and you are asked how many different values the function $f^k(a)$ can have, where $a$ is arbitrary non-empty array with numbers of size no more than $n$. Print the answer modulo $998\,244\,353$.
The solution of the task consists of three cases: $k = 1$. For fixed $n$ $f(a)$ can be equal to any partition of $n$. We need to count the number of arrays $b_1, b_2, \ldots, b_m$, such that $b_1 \ge b_2 \ge \ldots \ge b_m$ and $\sum \limits_{i=1}^m b_i \le n$. This can be done by simple dp in $\mathcal{O}(n^2)$ (or even faster, much faster). $k = 2$. When the array $b_1 \ge b_2 \ge \ldots \ge b_m$ can be equal to value of $f^2(a)$ for some $|a| \le n$? When there exists some array $c_1, \ldots, c_l$ such that $\sum \limits_{i=1}^l c_i \le n$, and $f(c) = b$. The values of $b$ are the numbers of occurences of numbers in $c$, so we need to minimize $\sum \limits_{i=1}^m b_i v_i$, where $v_i$ - the unique numbers in $c$. To minimize this sum we should take $v_1=1, \ldots, v_m=m$, so we need $\sum \limits_{i=1}^m b_i i \le n$. This can be done by simple dp: $dp[val][j][sum]$ - the number of prefixes of $b$ such that we already took $j$ elements to $b$, all elements on prefix are greater than or equal to $val$, and the $\sum \limits_{i=1}^j b_i i = sum$. This dp can look like it is $\mathcal{O}(n^3)$, but it is actually $\mathcal{O}(n^2 \log n)$, because there is a limitation $val \cdot j \le n$, and there are $\mathcal{O}(n \log n)$ such pairs. There is also a subquadratic solution. To minimize this sum we should take $v_1=1, \ldots, v_m=m$, so we need $\sum \limits_{i=1}^m b_i i \le n$. This can be done by simple dp: $dp[val][j][sum]$ - the number of prefixes of $b$ such that we already took $j$ elements to $b$, all elements on prefix are greater than or equal to $val$, and the $\sum \limits_{i=1}^j b_i i = sum$. This dp can look like it is $\mathcal{O}(n^3)$, but it is actually $\mathcal{O}(n^2 \log n)$, because there is a limitation $val \cdot j \le n$, and there are $\mathcal{O}(n \log n)$ such pairs. There is also a subquadratic solution. $k \ge 3$. We can notice that in the array $f^2(a)$ there are at most $\mathcal{O}(\sqrt{2n})$ elements. We can use this fact to bruteforce all possible answers - candidates for the answer are the partitions of numbers not exceeding $\sqrt{2n}=64$, there are few millions of them. How to check if the array $b_1 \ge b_2 \ge \ldots \ge b_m$ can be the falue of $f^k(a)$? It happens that we can make $k-2$ iterations of the unfolding algorithm from case $k=2$ and get the <<minimal>> possible array $a$, and check, if it contains no more than $n$ elements. This part works in $\mathcal{O}(\mathcal{P}(\sqrt{2n}))$. How to check if the array $b_1 \ge b_2 \ge \ldots \ge b_m$ can be the falue of $f^k(a)$? It happens that we can make $k-2$ iterations of the unfolding algorithm from case $k=2$ and get the <<minimal>> possible array $a$, and check, if it contains no more than $n$ elements. This part works in $\mathcal{O}(\mathcal{P}(\sqrt{2n}))$.
[ "dp" ]
2,900
null
1310
F
Bad Cryptography
In modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: \begin{center} Let's fix a finite field and two it's elements $a$ and $b$. One need to fun such $x$ that $a^x = b$ or detect there is no such x. \end{center} It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to $2^{2^k} - 1$ for some positive integer $k$ . Bitwise exclusive or ($\oplus$) operation is used as addition. One of ways to define multiplication operation ($\odot$) is following properties: - $0 \odot a = a \odot 0 = 0$ - $1 \odot a = a \odot 1 = a$ - $a \odot b = b \odot a$ - $a \odot (b \odot c)= (a \odot b) \odot c$ - $a \odot (b \oplus c) = (a \odot b) \oplus (a \odot c)$ - If $a = 2^{2^n}$ for some integer $n > 0$, and $b < a$, then $a \odot b = a \cdot b$. - If $a = 2^{2^n}$ for some integer $n > 0$, then $a \odot a = \frac{3}{2}\cdot a$. For example: - $ 4 \odot 4 = 6$ - $ 8 \odot 8 = 4 \odot 2 \odot 4 \odot 2 = 4 \odot 4 \odot 2 \odot 2 = 6 \odot 3 = (4 \oplus 2) \odot 3 = (4 \odot 3) \oplus (2 \odot (2 \oplus 1)) = (4 \odot 3) \oplus (2 \odot 2) \oplus (2 \odot 1) = 12 \oplus 3 \oplus 2 = 13.$ - $32 \odot 64 = (16 \odot 2) \odot (16 \odot 4) = (16 \odot 16) \odot (2 \odot 4) = 24 \odot 8 = (16 \oplus 8) \odot 8 = (16 \odot 8) \oplus (8 \odot 8) = 128 \oplus 13 = 141$ - $5 \odot 6 = (4 \oplus 1) \odot (4 \oplus 2) = (4\odot 4) \oplus (4 \odot 2) \oplus (4 \odot 1) \oplus (1 \odot 2) = 6 \oplus 8 \oplus 4 \oplus 2 = 8$ Formally, this algorithm can be described by following pseudo-code. \begin{verbatim} multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans; } multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power } } \end{verbatim} It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally $a^{\odot k} = \underbrace{a \odot a \odot \cdots \odot a}_{k~times}$. You need to analyze the proposed scheme strength. For pairs of numbers $a$ and $b$ you need to find such $x$, that $a^{\odot x} = b$, or determine that it doesn't exist.
One of the well-known algorithms for the discrete logarithm problem is baby step giant step algorithm based on the meet in the middle idea. It can solve the problem in $O(\sqrt{|F|})$ time, which is definitely too much for the field of size $2^64$. Multiplicative group of field has size $F = 2^64 - 1 = 3 \cdot 5 \cdot 17 \cdot 257 \cdot 641 \cdot 65537 \cdot 6700417$. We can see, that all numbers in this factoring are not too big. Let's try to find an answer modulo each of these primes. If we do that, we can restore the answer by the Chinese remainder theorem, and we are done. Let $p$ be one of divisors. So, if $x = k * p + y$ is answer, than $a^{kp + y} = b$, than $a^{kF + y\frac{F}{p}} = b^{\frac{F}{p}}$. $a^F$ is equal to 1, so problem is equivalent to searching such an $y$, that $(a^{\frac{F}{p}})^y = b^{\frac{F}{p}}$, which is discrete logarithm problem on multiplicative subgroup of size $p$. So it can be solved using $O(\sqrt{p})$ multiplications, which is about 6000 multiplications total for all values of $p$. If one of the discrete logarithms not exists, the total answer obviously not exists. Another corner case, that both values in subproblem can be equal to $1$. That means, that any value for this module is good. Also, this means, that $a$ and $b$ both have a smaller period, so any of these values would lead us to the correct answer. Another part of problem is making multiplication fast enough. The first idea is to cache multiplications for powers of 2. This solution works for about 5 seconds in my implementation, and probably can be squeezed in time limit with some hacks. But multiplication can be done asymptotically faster. Let's $a = a_1 \cdot P + a_2$, $b = b_1 \cdot P + b_2$ is decomposition to first and second half of bits (in fact P is equal to power in multiply_powers_of_2 function). Then $a \odot b = (a_1 \cdot P + a_2) \cdot (b_1 \cdot P + b_2) = (a_1 \odot P \oplus a_2) \odot (b_1 \odot P \oplus b_2) = (a_1 \odot b_1) \odot (P \odot P) \oplus (a_2 \odot b_2) \oplus ((a_1 \odot b_2)\oplus(a_2\odot b_1))\odot P$. As in Karatsuba algroithm, this 4 products can be reduce for 3, if one notice, that $(a_1 \odot b_2)\oplus(a_2\odot b_1) = (a_1 \oplus a_2) \odot(b_1\oplus b_2) \oplus (a_1\odot b_1)\oplus(a_2\odot b_2)$. The only diffrenece is instead of shift for multiplying on $P\cdot P$ we need to do one more multiplication. But $P\odot P = P \oplus \frac{P}{2}$. We can multiply by them separately. Multiplying on $P$ is easy. The other one is multiplying on the power of 2, which can be done by the naive algorithm in linear time. On the other hand, we can just call multiply for the second one recursively, and it will work fast enough because most of the branches will lead to multiplying on zero. Also, to make things fast, one can precompute all multiplications for numbers smaller than 256. This makes multiplication about 5 times faster than naive approach.
[ "math", "number theory" ]
3,400
null
1311
A
Add Odd or Subtract Even
You are given two positive integers $a$ and $b$. In one move, you can \textbf{change} $a$ in the following way: - Choose any positive \textbf{odd} integer $x$ ($x > 0$) and replace $a$ with $a+x$; - choose any positive \textbf{even} integer $y$ ($y > 0$) and replace $a$ with $a-y$. You can perform as many such operations as you want. You can choose the same numbers $x$ and $y$ in different moves. Your task is to find the minimum number of moves required to obtain $b$ from $a$. It is guaranteed that you can always obtain $b$ from $a$. You have to answer $t$ independent test cases.
If $a=b$ then the answer is $0$. Otherwise, if $a > b$ and $a - b$ is even or $a < b$ and $b - a$ is odd then the answer is $1$. Otherwise the answer is $2$ (you can always make $1$-case in one move).
[ "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if (a == b) cout << 0 << endl; else cout << 1 + int((a < b) ^ ((b - a) & 1)) << endl; } return 0; }
1311
B
WeirdSort
You are given an array $a$ of length $n$. You are also given a set of \textbf{distinct} positions $p_1, p_2, \dots, p_m$, where $1 \le p_i < n$. The position $p_i$ means that you can swap elements $a[p_i]$ and $a[p_i + 1]$. You can apply this operation any number of times for each of the given \textbf{positions}. Your task is to determine if it is possible to sort the initial array in non-decreasing order ($a_1 \le a_2 \le \dots \le a_n$) using only allowed swaps. For example, if $a = [3, 2, 1]$ and $p = [1, 2]$, then we can first swap elements $a[2]$ and $a[3]$ (because position $2$ is contained in the given set $p$). We get the array $a = [3, 1, 2]$. Then we swap $a[1]$ and $a[2]$ (position $1$ is also contained in $p$). We get the array $a = [1, 3, 2]$. Finally, we swap $a[2]$ and $a[3]$ again and get the array $a = [1, 2, 3]$, sorted in non-decreasing order. You can see that if $a = [4, 1, 2, 3]$ and $p = [3, 2]$ then you cannot sort the array. You have to answer $t$ independent test cases.
The simple simulation works here: while there is at least one inversion (such a pair of indices $i$ and $i+1$ that $a[i] > a[i + 1]$) we can fix, let's fix it (we can fix this inversion if $i \in p$). If there are inversions but we cannot fix any of them, the answer is "NO". Otherwise, the answer is "YES". There is also a $O(n \log n)$ solution: it is obvious that we have some segments in which we can change the order of elements as we want. And it is also obvious that we cannot move elements between these "allowed" segments. So, each of them is independent of each other. We can just find all these segments of indices using two pointers and sort them independently. Then we just need to check if the array becomes sorted. Time complexity is $O(n^2)$ or $O(n \log n)$.
[ "dfs and similar", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<int> p(n); for (int i = 0; i < m; ++i) { int pos; cin >> pos; p[pos - 1] = 1; } for (int i = 0; i < n; ++i) { if (p[i] == 0) continue; int j = i; while (j < n && p[j]) ++j; sort(a.begin() + i, a.begin() + j + 1); i = j; } bool ok = true; for (int i = 0; i < n - 1; ++i) { ok &= a[i] <= a[i + 1]; } if (ok) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
1311
C
Perform the Combo
You want to perform the combo on your opponent in one popular fighting game. The combo is the string $s$ consisting of $n$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $s$. I.e. if $s=$"abca" then you have to press 'a', then 'b', 'c' and 'a' again. You know that you will spend $m$ wrong tries to perform the combo and during the $i$-th try you will make a mistake right after $p_i$-th button ($1 \le p_i < n$) (i.e. you will press first $p_i$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $m+1$-th try you press all buttons right and finally perform the combo. I.e. if $s=$"abca", $m=2$ and $p = [1, 3]$ then the sequence of pressed buttons will be 'a' (\textbf{here} you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (\textbf{here} you're making a mistake and start performing the combo from the beginning), 'a' (\textbf{note that at this point you will not perform the combo because of the mistake}), 'b', 'c', 'a'. Your task is to calculate for each button (letter) the number of times you'll press it. You have to answer $t$ independent test cases.
We can consider all tries independently. During the $i$-th try we press first $p_i$ buttons, so it makes $+1$ on the prefix of length $p_i$. So the $i$-th character of the string will be pressed (the number of $p_i \ge i$ plus $1$) times. We can use sorting and some kind of binary search to find this number for each character but we also can build suffix sums to find all required numbers. We can build suffix sums using the following code: So as you can see, the $i$-th element of $p$ will add $1$ in each position from $1$ to $p_i$. So we got what we need. After that we can calculate the answer for each character in the following way: Time complexity: $O(n \log n)$ or $O(n)$.
[ "brute force" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, m; string s; cin >> n >> m >> s; vector<int> pref(n); for (int i = 0; i < m; ++i) { int p; cin >> p; ++pref[p - 1]; } for (int i = n - 1; i > 0; --i) { pref[i - 1] += pref[i]; } vector<int> ans(26); for (int i = 0; i < n; ++i) { ans[s[i] - 'a'] += pref[i]; ++ans[s[i] - 'a']; } for (int i = 0; i < 26; ++i) { cout << ans[i] << " "; } cout << endl; } return 0; }
1311
D
Three Integers
You are given three integers $a \le b \le c$. In one move, you can add $+1$ or $-1$ to \textbf{any} of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. \textbf{Note that you cannot make non-positive numbers using such operations}. You have to perform the minimum number of such operations in order to obtain three integers $A \le B \le C$ such that $B$ is divisible by $A$ and $C$ is divisible by $B$. You have to answer $t$ independent test cases.
Let's iterate over all possible values of $A$ from $1$ to $2a$. It is obvious that $A$ cannot be bigger than $2a$, else we can just move $a$ to $1$. Then let's iterate over all possible multiples of $A$ from $1$ to $2b$. Let this number be $B$. Then we can find $C$ as the nearest number to $c$ that is divisible by $B$ (we can check two nearest numbers to be sure). These numbers are $C = \lfloor\frac{c}{B}\rfloor \cdot B$ and $C = \lfloor\frac{c}{B}\rfloor \cdot B + B$. Then we can update the answer with the found triple. Note that the only condition you need to check is that $B \le C$. Time complexity: $O(n \log n)$ because of the sum of the harmonic series.
[ "brute force", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int a, b, c; cin >> a >> b >> c; int ans = 1e9; int A = -1, B = -1, C = -1; for (int cA = 1; cA <= 2 * a; ++cA) { for (int cB = cA; cB <= 2 * b; cB += cA) { for (int i = 0; i < 2; ++i) { int cC = cB * (c / cB) + i * cB; int res = abs(cA - a) + abs(cB - b) + abs(cC - c); if (ans > res) { ans = res; A = cA; B = cB; C = cC; } } } } cout << ans << endl << A << " " << B << " " << C << endl; } return 0; }
1311
E
Construct the Binary Tree
You are given two integers $n$ and $d$. You need to construct a rooted binary tree consisting of $n$ vertices with a root at the vertex $1$ and the sum of depths of all vertices equals to $d$. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. The depth of the vertex $v$ is the length of the path from the root to the vertex $v$. Children of vertex $v$ are all vertices for which $v$ is the parent. The binary tree is such a tree that no vertex has more than $2$ children. You have to answer $t$ independent test cases.
This problem has an easy constructive solution. We can find lower and upper bounds on the value of $d$ for the given $n$. If the given $d$ does not belong to this segment, then the answer is "NO". Otherwise, the answer is "YES" for any $d$ in this segment. How to construct it? Let's start from the chain. The answer for the chain is the upper bound of $d$ and it is $\frac{n(n-1)}{2}$. Then let's try to decrease the answer by $1$ in one move. Let's take some leaf $v$ (the vertex without children) with the smallest depth that is not bad and try to move it up. The definition of badness will be below. To do this, let's find such vertex $p$ that its depth is less than the depth of $v$ by $2$ and it has less than $2$ children. If we found such vertex $p$ then let's make $v$ the child of $p$ and decrease the answer by one. If we didn't find such vertex $p$, I claim that the vertex $v$ has the minimum possible depth it can have and we should not consider it in the future. Let's mark this vertex as bad and continue our algorithm. If at some moment we cannot find any not bad leaf $v$, then the answer is "NO". Otherwise, the answer is "YES". Time complexity: $O(nd)$.
[ "brute force", "constructive algorithms", "trees" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, d; cin >> n >> d; int ld = 0, rd = n * (n - 1) / 2; for (int i = 1, cd = 0; i <= n; ++i) { if (!(i & (i - 1))) ++cd; ld += cd - 1; } if (!(ld <= d && d <= rd)) { cout << "NO" << endl; continue; } vector<int> par(n); iota(par.begin(), par.end(), -1); vector<int> cnt(n, 1); cnt[n - 1] = 0; vector<int> bad(n); vector<int> dep(n); iota(dep.begin(), dep.end(), 0); int cur = n * (n - 1) / 2; while (cur > d) { int v = -1; for (int i = 0; i < n; ++i) { if (!bad[i] && cnt[i] == 0 && (v == -1 || dep[v] > dep[i])) { v = i; } } assert(v != -1); int p = -1; for (int i = 0; i < n; ++i) { if (cnt[i] < 2 && dep[i] < dep[v] - 1 && (p == -1 || dep[p] < dep[i])) { p = i; } } if (p == -1) { bad[v] = 1; continue; } assert(dep[v] - dep[p] == 2); --cnt[par[v]]; --dep[v]; ++cnt[p]; par[v] = p; --cur; } cout << "YES" << endl; for (int i = 1; i < n; ++i) cout << par[i] + 1 << " "; cout << endl; } return 0; }
1311
F
Moving Points
There are $n$ points on a coordinate axis $OX$. The $i$-th point is located at the integer point $x_i$ and has a speed $v_i$. It is guaranteed that no two points occupy the same coordinate. All $n$ points move with the constant speed, the coordinate of the $i$-th point at the moment $t$ ($t$ \textbf{can be non-integer}) is calculated as $x_i + t \cdot v_i$. Consider two points $i$ and $j$. Let $d(i, j)$ be the minimum possible distance between these two points over any possible moments of time (even \textbf{non-integer}). It means that if two points $i$ and $j$ coincide at some moment, the value $d(i, j)$ will be $0$. Your task is to calculate the value $\sum\limits_{1 \le i < j \le n}$ $d(i, j)$ (the sum of minimum distances over all pairs of points).
Let's understand when two points $i$ and $j$ coincide. Let $x_i < x_j$. Then they are coincide when $v_i > v_j$. Otherwise, these two points will never coincide and the distance between them will only increase. So, we need to consider only the initial positions of points. Let's sort all points by $x_i$ and consider them one by one from left to right. Let the $i$-th point be the rightmost in the pair of points that we want to add to the answer. We need to find the number of points $j$ such that $x_j < x_i$ and $v_j \le v_i$ and the sum of $x_j$ for such points as well. We can do this using two BITs (Fenwick trees) if we compress coordinates (all values $v$) and do some kind of "scanline" by values $x$. Let the number of such points be $cnt$ and the sum of coordinates of such points be $sum$. Then we can increase the answer by $x_i \cdot cnt - sum$ and add our current point to the Fenwick trees (add $1$ to the position $v_i$ in the first tree and $x_i$ to the position $v_i$ in the second tree). When we want to find the number of required points and the sum of its coordinates, we just need to find the sum on the prefix two times in Fenwick trees. Note that you can use any "online" logarithmic data structure you like in this solution (such as treap and segment tree). There is also another solution that uses pbds. Let's do the same thing, but there is one problem. Such data structure does not have "sum on prefix" function, so we have to replace it somehow. To do this, let's calculate only $x_i \cdot cnt$ part when we go from left to right. Then let's clear our structure, go among all points again but from right to left and calculate the same thing, but with the opposite sign (find the number of points $j$ such that $x_j > x_i$ and $v_j \ge v_i$). When we go from right to left, we need to decrease the answer by $x_i \cdot cnt$. It is some kind of "contribution to the sum" technique. Time complexity: $O(n \log n)$.
[ "data structures", "divide and conquer", "implementation", "sortings" ]
1,900
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; typedef tree< pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<pair<int, int>> p(n); for (auto &pnt : p) cin >> pnt.first; for (auto &pnt : p) cin >> pnt.second; sort(p.begin(), p.end()); ordered_set s; long long ans = 0; for (int i = 0; i < n; ++i) { int cnt = s.order_of_key(make_pair(p[i].second + 1, -1)); ans += cnt * 1ll * p[i].first; s.insert(make_pair(p[i].second, i)); } s.clear(); for (int i = n - 1; i >= 0; --i) { int cnt = int(s.size()) - s.order_of_key(make_pair(p[i].second - 1, n)); ans -= cnt * 1ll * p[i].first; s.insert(make_pair(p[i].second, i)); } cout << ans << endl; return 0; }
1312
A
Two Regular Polygons
You are given two integers $n$ and $m$ ($m < n$). Consider a \textbf{convex} regular polygon of $n$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). \begin{center} Examples of convex regular polygons \end{center} Your task is to say if it is possible to build another \textbf{convex} regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon. You have to answer $t$ independent test cases.
The answer is "YES" if and only if $n$ is divisible by $m$ because if you number all vertices of the initial polygon from $0$ to $n-1$ clockwise then you need to take every vertex divisible by $\frac{n}{m}$ (and this number obviously should be integer) and there is no other way to construct the other polygon.
[ "geometry", "greedy", "math", "number theory" ]
800
for i in range(int(input())): n, m = map(int, input().split()) print('YES' if n % m == 0 else 'NO')
1312
B
Bogosort
You are given an array $a_1, a_2, \dots , a_n$. Array is good if for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if $a = [1, 1, 3, 5]$, then shuffled arrays $[1, 3, 5, 1]$, $[3, 5, 1, 1]$ and $[5, 3, 1, 1]$ are good, but shuffled arrays $[3, 1, 5, 1]$, $[1, 1, 3, 5]$ and $[1, 1, 5, 3]$ aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition.
Let's sort array $a$ in non-ascending order ($a_1 \ge a_2 \ge \dots \ge a_n$). In this case for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds.
[ "constructive algorithms", "sortings" ]
1,000
for t in range(int(input())): n = input() print(*sorted(map(int, input().split()))[::-1])
1312
C
Adding Powers
Suppose you are performing the following algorithm. There is an array $v_1, v_2, \dots, v_n$ filled with zeroes at start. The following operation is applied to the array several times — at $i$-th step ($0$-indexed) you can: - either choose position $pos$ ($1 \le pos \le n$) and increase $v_{pos}$ by $k^i$; - or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array $v$ equal to the given array $a$ ($v_j = a_j$ for each $j$) after some step?
This is the solution that doesn't involve masks. Let's reverse the process and try to get all zeroes from the array $a$: since all $a_i \le 10^{16}$ we can start from maximum $k^s \le 10^{16}$. The key idea: since $k^s > \sum_{x=0}^{s-1}{k^x}$ then there should be no more than one position $pos$ such that $a_{pos} \ge k^s$ and we should decrease it by $k^s$. Now we can decrease $s$ by $1$ and repeat the same process. If at any step there are at least two $a_{pos} \ge k^s$ or as result, we won't get array filled with $0$ then there is no way to build the array $a$.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
1,400
fun getMask(a: Long, k: Long): Long? { var (tmp, res) = listOf(a, 0L) var cnt = 0 while (tmp > 0) { if (tmp % k > 1) return null res = res or ((tmp % k) shl cnt) tmp /= k cnt++ } return res } fun main() { val T = readLine()!!.toInt() for (tc in 1..T) { val (n, k) = readLine()!!.split(' ').map { it.toLong() } val a = readLine()!!.split(' ').map { getMask(it.toLong(), k) } val b = a.filterNotNull() if (b.size < n) { println("NO") continue } else { val res = b.reduce { acc, l -> if (acc < 0 || (acc and l) > 0) -1 else acc or l } println(if (res < 0) "NO" else "YES") } } }
1312
D
Count the Arrays
Your task is to calculate the number of arrays such that: - each array contains $n$ elements; - each element is an integer from $1$ to $m$; - for each array, there is \textbf{exactly} one pair of equal elements; - for each array $a$, there exists an index $i$ such that the array is \textbf{strictly ascending} before the $i$-th element and \textbf{strictly descending} after it (formally, it means that $a_j < a_{j + 1}$, if $j < i$, and $a_j > a_{j + 1}$, if $j \ge i$).
First of all, there will be exactly $n - 1$ distinct elements in our array. Let's choose them, there are ${m}\choose{n-1}$ ways to do that. After that, there should be exactly one element that appears twice. There are $n - 1$ elements to choose from, but are all of them eligible? If we duplicate the maximum element, there will be no way to meet the fourth condition. So we should multiply the current answer by $n - 2$, not $n - 1$. And finally, some elements will appear earlier than the maximum in our array, and some - later. The duplicated element will appear on both sides, but all other elements should appear either to the left or to the right, so there are $2^{n - 3}$ ways to choose their positions. Thus the answer is ${{m}\choose{n - 1}} (n - 2)2^{n - 3}$. Note that you have to precompute all factorials and use their inverse elements to calculate ${m}\choose{n-1}$. Note that there is a tricky case when $n = 2$: some binpow implementations go into infinite loop trying to compute $2^{-1}$, so you may have to handle it specifically.
[ "combinatorics", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = 200043; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y) { if(y & 1) z = mul(z, x); x = mul(x, x); y >>= 1; } return z; } int inv(int x) { return binpow(x, MOD - 2); } int divide(int x, int y) { return mul(x, inv(y)); } int fact[N]; void precalc() { fact[0] = 1; for(int i = 1; i < N; i++) fact[i] = mul(fact[i - 1], i); } int C(int n, int k) { return divide(fact[n], mul(fact[k], fact[n - k])); } int main() { precalc(); int n, m; cin >> n >> m; int ans = 0; if(n > 2) ans = mul(C(m, n - 1), mul(n - 2, binpow(2, n - 3))); cout << ans << endl; }
1312
E
Array Shrinking
You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: - Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). - Replace them by one element with value $a_i + 1$. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
Let's look at the answer: by construction, each element in the final answer was the result of replace series of elements on the corresponding segment. So all we need to find is the minimal (by size) partition of the array $a$ on segments where each segment can be transformed in one element by series of replaces. We can calculate it using standard prefix dynamic programming, or $dp2[len]$ is the size of such minimal partition of a prefix of length $len$. The transitions are standard: let's check all segments $[len, nxt)$ and if it can be replaced by one element let's relax $dp2[nxt]$. Now we need to check for all segments of $a$ - can it be replaced by one element. Let's calculate another $dp[l][r]$ using the following fact: if there is a way to replace all segment as one element so the segment either has the length $1$ or it can be divided into two parts where the prefix can be replaced by one element, the suffix also can be replaced by one element and these elements are equal. It's exactly the transitions we need to check to calculate $dp[l][r]$. The resulting complexity is $O(n^3)$.
[ "dp", "greedy" ]
2,100
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << ", " << p.y << ")"; } template<class A> ostream& operator <<(ostream& out, const vector<A> &v) { out << "["; fore(i, 0, sz(v)) { if(i) out << ", "; out << v[i]; } return out << "]"; } const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; const int N = 555; int n, a[N]; inline bool read() { if(!(cin >> n)) return false; fore(i, 0, n) cin >> a[i]; return true; } int dp[N][N]; int calcDP(int l, int r) { assert(l < r); if(l + 1 == r) return dp[l][r] = a[l]; if(dp[l][r] != 0) return dp[l][r]; dp[l][r] = -1; fore(mid, l + 1, r) { int lf = calcDP(l, mid); int rg = calcDP(mid, r); if(lf > 0 && lf == rg) return dp[l][r] = lf + 1; } return dp[l][r]; } int dp2[N]; inline void solve() { fore(i, 0, N) dp2[i] = INF; dp2[0] = 0; fore(i, 0, n) { fore(j, i + 1, n + 1) { if(calcDP(i, j) > 0) dp2[j] = min(dp2[j], dp2[i] + 1); } } cout << dp2[n] << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1312
F
Attack on Red Kingdom
The Red Kingdom is attacked by the White King and the Black King! The Kingdom is guarded by $n$ castles, the $i$-th castle is defended by $a_i$ soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King. Each attack must target a castle with \textbf{at least one} alive defender in it. There are three types of attacks: - a mixed attack decreases the number of defenders in the targeted castle by $x$ (or sets it to $0$ if there are already less than $x$ defenders); - an infantry attack decreases the number of defenders in the targeted castle by $y$ (or sets it to $0$ if there are already less than $y$ defenders); - a cavalry attack decreases the number of defenders in the targeted castle by $z$ (or sets it to $0$ if there are already less than $z$ defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the \textbf{previous attack on the targeted castle} had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack. The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
This problem seems like a version of Nim with some forbidden moves, so let's try to apply Sprague-Grundy theory to it. First of all, we may treat each castle as a separate game, compute its Grundy value, and then XOR them to determine who is the winner of the game. When analyzing the state of a castle, we have to know two things: the number of remaining soldiers in it and the type of the last attack performed on it. So, the state of the game can be treated as a pair. We can compute Grundy values for each state in a straightforward way, but the constraints are too large to do it. Instead, we should try to search for a period: five consecutive rows (by row we mean a vector of Grundy values for the same number of remaining soldiers, but different types of last attacks) of Grundy values determine all of the values after them, so as soon as we get the same five rows of Grundy values that we already met, we can determine the period. There are $15$ values stored in these five rows, so the period can be up to $4^{15}$ - but that's a really generous upper bound. Some intuition can help us to prove something like $10^5$ or $10^6$ as an upper bound, but it is better to check all cases with brute force and find out that the period is at most $36$. After we've found the period of Grundy values, it's easy to get them in $O(1)$ for any castle. To count the number of winning moves for the first player, we can compute the XOR-sum of all castles, and for each castle check what happens if we make some type of attack on it: if the XOR-sum becomes $0$, then this move is winning.
[ "games", "two pointers" ]
2,500
#include<bits/stdc++.h> using namespace std; const int N = 300043; const int K = 5; int x, y, z, n; long long a[N]; typedef vector<vector<int> > state; map<state, int> d; int cnt; int p; vector<vector<int> > state_log; int mex(const vector<int>& a) { for(int i = 0; i < a.size(); i++) { bool f = false; for(auto x : a) if(x == i) f = true; if(!f) return i; } return a.size(); } state go(state s) { int f1 = mex({s[0][K - x], s[1][K - y], s[2][K - z]}); int f2 = mex({s[0][K - x], s[2][K - z]}); int f3 = mex({s[0][K - x], s[1][K - y]}); state nw = s; nw[0].push_back(f1); nw[1].push_back(f2); nw[2].push_back(f3); for(int i = 0; i < 3; i++) nw[i].erase(nw[i].begin()); return nw; } void precalc() { d.clear(); state cur(3, vector<int>(K, 0)); cnt = 0; state_log.clear(); while(!d.count(cur)) { d[cur] = cnt; state_log.push_back({cur[0].back(), cur[1].back(), cur[2].back()}); cur = go(cur); cnt++; } p = cnt - d[cur]; } int get_grundy(long long x, int t) { if(x < cnt) return state_log[x][t]; else { int pp = cnt - p; x -= pp; return state_log[pp + (x % p)][t]; } } void read() { scanf("%d %d %d %d", &n, &x, &y, &z); for(int i = 0; i < n; i++) scanf("%lld", &a[i]); } int check(int x, int y) { return x == y ? 1 : 0; } void solve() { precalc(); int ans = 0; for(int i = 0; i < n; i++) ans ^= get_grundy(a[i], 0); int res = 0; for(int i = 0; i < n; i++) { ans ^= get_grundy(a[i], 0); res += check(ans, get_grundy(max(0ll, a[i] - x), 0)); res += check(ans, get_grundy(max(0ll, a[i] - y), 1)); res += check(ans, get_grundy(max(0ll, a[i] - z), 2)); ans ^= get_grundy(a[i], 0); } printf("%d\n", res); } int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { read(); solve(); } }
1312
G
Autocompletion
You are given a set of strings $S$. Each string consists of lowercase Latin letters. For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: - if the current string is $t$, choose some lowercase Latin letter $c$ and append it to the back of $t$, so the current string becomes $t + c$. This action takes $1$ second; - use autocompletion. When you try to autocomplete the current string $t$, a list of all strings $s \in S$ such that $t$ is a prefix of $s$ is shown to you. \textbf{This list includes $t$ itself, if $t$ is a string from $S$}, and the strings are ordered lexicographically. You can transform $t$ into the $i$-th string from this list in $i$ seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from $S$? \textbf{Note that the strings from $S$ are given in an unusual way}.
First of all, the information given in the input is the structure of a trie built on $S$ and some other strings - so we can store this information in the same way as we store a trie. Okay, now let's calculate the number of seconds required to type each string with dynamic programming: let $dp_i$ be the number of seconds required to arrive to the $i$-th vertex of the trie. For regular vertices, $dp_i = dp_{p_i} + 1$, where $p_i$ is the parent of vertex $i$; for vertices corresponding to strings from $S$, $dp$ values should be updated with the time required to autocomplete some of the parents to the current vertex. To do these updates, let's calculate the answers for all strings in lexicographical order. We will run DFS on the trie and maintain a segment tree on the path from the root to the current vertex. In the segment tree, we will store the values of $dp_i + cost_i$, where $cost_i$ is the number of seconds required to autocomplete from $i$ to the current vertex. Obviously, if we are currently in a vertex representing a word from $S$, then we have to find the minimum in this segment tree - and that will be the cost to get to current vertex using autocompletion. How to maintain $dp_i + cost_i$? Recall that we are running DFS on trie in lexicographical order. When we want to compute the answer for the first string, the value of $cost_i$ for all vertices is $1$, since our string will be the first in all autocompletion lists. And here's a trick to maintain these values for other strings: whenever we compute the answer for some string, add $1$ on the whole tree. For vertices that are ancestors of both current string and some next string, this $+1$ will stay and increase the cost to autocomplete the next string accordingly; but for vertices which are not on the path to some next string, the values of $dp_i + cost_i$ will be already deleted from the segment tree and replaced by new values - so this addition does not affect them. Overall, this works in $O(n \log n)$, but it can be written in $O(n)$ with a vector instead of a segment tree (since all additions and minimum queries affect the whole structure).
[ "data structures", "dfs and similar", "dp" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N = 1000043; map<char, int> nxt[N]; bool term[N]; int n, k; char buf[3]; int dp[N]; int dict[N]; int T[4 * N]; int f[4 * N]; void build(int v, int l, int r) { T[v] = int(1e9); if(l != r - 1) { int m = (l + r) / 2; build(v * 2 + 1, l, m); build(v * 2 + 2, m, r); } } int getVal(int v) { return T[v] + f[v]; } void push(int v, int l, int r) { T[v] += f[v]; if(l != r - 1) { f[v * 2 + 1] += f[v]; f[v * 2 + 2] += f[v]; } f[v] = 0; } void upd(int v, int l, int r) { if(l != r - 1) { T[v] = min(getVal(v * 2 + 1), getVal(v * 2 + 2)); } } int get(int v, int l, int r, int L, int R) { if(L >= R) return int(1e9); if(l == L && r == R) return getVal(v); push(v, l, r); int m = (l + r) / 2; int ans = min(get(v * 2 + 1, l, m, L, min(m, R)), get(v * 2 + 2, m, r, max(L, m), R)); upd(v, l, r); return ans; } void add(int v, int l, int r, int L, int R, int val) { if(L >= R) return; if(l == L && r == R) { f[v] += val; return; } push(v, l, r); int m = (l + r) / 2; add(v * 2 + 1, l, m, L, min(m, R), val); add(v * 2 + 2, m, r, max(L, m), R, val); upd(v, l, r); } void setVal(int v, int l, int r, int pos, int val) { if(l == r - 1) { f[v] = 0; T[v] = val; return; } push(v, l, r); int m = (l + r) / 2; if(pos < m) setVal(v * 2 + 1, l, m, pos, val); else setVal(v * 2 + 2, m, r, pos, val); upd(v, l, r); } void dfs(int v, int d, int last) { dp[v] = last + 1; if(term[v]) dp[v] = min(dp[v], get(0, 0, n + 1, 0, d)); setVal(0, 0, n + 1, d, dp[v] + 1); if(term[v]) add(0, 0, n + 1, 0, d + 1, 1); for(auto x : nxt[v]) dfs(x.second, d + 1, dp[v]); setVal(0, 0, n + 1, d, int(1e9)); } int main() { scanf("%d", &n); for(int i = 0; i < n; i++) { int p; scanf("%d %s", &p, buf); char c = buf[0]; nxt[p][c] = i + 1; } scanf("%d", &k); for(int i = 0; i < k; i++) { scanf("%d", &dict[i]); term[dict[i]] = true; } build(0, 0, n + 1); dfs(0, 0, -1); for(int i = 0; i < k; i++) printf("%d ", dp[dict[i]]); puts(""); }
1313
A
Fast Food Restaurant
Tired of boring office work, Denis decided to open a fast food restaurant. On the first day he made $a$ portions of dumplings, $b$ portions of cranberry juice and $c$ pancakes with condensed milk. The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: - every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); - each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; - all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?
Bruteforce solution There are seven possible sets of dishes, so the simplest solution is to iterate over all possible $2^7$ subsets of sets of dishes. You can also go over $7!$ permutations of sets of dishes and gather sets of dishes greedily in the selected order. Greedy solution Note that the solution can be optimal only when it is impossible to add an additional set of dishes to it. Let the solution be such that it is impossible to add a single set of dishes to it and it does not have any set consisting of one dish, but there is a set consisting of two or three dishes containing this one dish. Then you can replace the corresponding set with a set of one dish, without worsening the answer. This means that at the beginning you can greedily add all the sets consisting of one dish. The same can show that any set of three dishes can be replaced with a set of two dishes, so after the sets of one and two dishes are fixed, it is enough to simply check whether you can add a set of three dishes. However, it is wrong to choose sets of two dishes greedily. Suppose that after choosing sets of one dish, there is one dish of the first type, one dish of the second type and two dishes of the third type. Then you can choose two sets of dishes, but if you take at the beginning a set of dishes of the first and second types, you won't get two different sets. In this case, you can simply iterate over the order of choosing sets of two dishes or notice that all such tests have the form $2\, 2\, x$, $2\, x\, 2$, $x\, 2\, 2$, where $x \geq 3$, and solve them separately.
[ "brute force", "greedy", "implementation" ]
900
null
1313
B
Different Rules
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $n$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules. Suppose in the first round participant A took $x$-th place and in the second round — $y$-th place. Then the total score of the participant A is sum $x + y$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $i$ from $1$ to $n$ \textbf{exactly one} participant took $i$-th place in first round and \textbf{exactly one} participant took $i$-th place in second round. Right after the end of the Olympiad, Nikolay was informed that he got $x$-th place in first round and $y$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
Without loss of generality, assume that $x \leq y$. For convenience, we will number the participants from 1 to $n$ in the order of their places in the first round. Thus, the participant we are interested in is the participant $x$. First we can prove the formula: $\operatorname{MIN\_PLACE} = \max(1, \min(n, x + y - n + 1))$ First case: $x + y < n$. It can be shown that participant $x$ can achieve first place in the Olympics. In order to do this, the following example can be built: $i$-th participant ($1 \leq i \leq x-1$) takes $(x+y+1-i)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes $y$-th place in the second round (sum - $x+y$) $j$-th participant ($x+1 \leq j \leq n-y$) takes $(n+x+1-j)$-th place in the second round (sum - $n+x+1$) $(n-y+1)$-th participant takes $(y+1)$-th place in the second round (sum - $n+2$) $t$-th participant ($n-y+2 \leq t \leq n$) takes $(n+1-t)$-th place in the second round (sum - $n+1$) The illustration below explains this example $i$-th participant ($1 \leq i \leq x-1$) takes $(x+y+1-i)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes $y$-th place in the second round (sum - $x+y$) $j$-th participant ($x+1 \leq j \leq n-y$) takes $(n+x+1-j)$-th place in the second round (sum - $n+x+1$) $(n-y+1)$-th participant takes $(y+1)$-th place in the second round (sum - $n+2$) $t$-th participant ($n-y+2 \leq t \leq n$) takes $(n+1-t)$-th place in the second round (sum - $n+1$) Second case: $x + y \geq n+1;\; y \ne n$Consider the participant with the number $k$ ($k \leq x + y - n < x$). They will receive no more than $x+y-n+n = x + y$ in total (because $n$ is the maximum place in the second round they can take), that is guaranteed to overtake the main character. Thus we can't achieve any place better than $x+y-n+1$. For this assessment, an example below is given: $i$-th participant $(1 \leq i \leq x+y-n)$ takes $i$-th place in the second round (sum - $2i < x + y$) $j$-th participant $(x+y-n+1 \leq j \leq x-1)$ takes $(x+y+1-j)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes the y-th place in the second round (sum - $x+y$) $(x+1)$-th participant takes $(y+1)$-th place in the second round (sum - $x+y+2$) $t$-th participant $(x+2 \leq t \leq n)$ takes $(x+y+1-t)$-th place in the second round (sum - $x+y+1$) The illustration below explains this example Consider the participant with the number $k$ ($k \leq x + y - n < x$). They will receive no more than $x+y-n+n = x + y$ in total (because $n$ is the maximum place in the second round they can take), that is guaranteed to overtake the main character. Thus we can't achieve any place better than $x+y-n+1$. For this assessment, an example below is given: $i$-th participant $(1 \leq i \leq x+y-n)$ takes $i$-th place in the second round (sum - $2i < x + y$) $j$-th participant $(x+y-n+1 \leq j \leq x-1)$ takes $(x+y+1-j)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes the y-th place in the second round (sum - $x+y$) $(x+1)$-th participant takes $(y+1)$-th place in the second round (sum - $x+y+2$) $t$-th participant $(x+2 \leq t \leq n)$ takes $(x+y+1-t)$-th place in the second round (sum - $x+y+1$) Third case: $x + y \geq n+1$; $y = n$Then the participant with the number $k$ ($k \leq x + y - n + 1 = x + 1$) will receive no more than $x+y-n+1+n-1 = x + y$ in total, that is guaranteed to overtake the main character. That is, we can't take places better than $x+y-n+1$. For this assessment, we give an example below: Participant $i < x$ takes $x$-th place, overtaking $x+y$ Participant $x + 1$ takes $(n-1)$-th place, overtaking $x+y$ Participant $j$ ($x + 2 \leq j \leq n$) takes $(x+y+1-j)$-th place A separate case: $x = y = n$, then the outcome is obvious Then the participant with the number $k$ ($k \leq x + y - n + 1 = x + 1$) will receive no more than $x+y-n+1+n-1 = x + y$ in total, that is guaranteed to overtake the main character. That is, we can't take places better than $x+y-n+1$. For this assessment, we give an example below: Participant $i < x$ takes $x$-th place, overtaking $x+y$ Participant $x + 1$ takes $(n-1)$-th place, overtaking $x+y$ Participant $j$ ($x + 2 \leq j \leq n$) takes $(x+y+1-j)$-th place A separate case: $x = y = n$, then the outcome is obvious The formula for the minimum place is proved. The formula for the maximum place will be proven in the same way: We prove the formula: $\operatorname{MAX\_PLACE} = \min(n, x + y-1)$ First case: $x + y \geq n+1$. Then we can give an example in which we will take the last place: $i$-th participant ($1 \leq i \leq x+y-n-1$) takes $(y+x-n-i)$-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-n-1 \leq j \leq n$) takes $(x+y-j)$-th place in the second round (sum - $y + x$) $i$-th participant ($1 \leq i \leq x+y-n-1$) takes $(y+x-n-i)$-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-n-1 \leq j \leq n$) takes $(x+y-j)$-th place in the second round (sum - $y + x$) Second case: $x + y \leq n$ Consider a participant with the number $k$ ($x+y \leq k$). They are guaranteed to be overtaken by $x+y$ (main character) So the main character can not take any place worse than $x+y-1$: $i$-th participant ($1 \leq i \leq x+y-1$) takes ($y+x-i$)-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-1 \leq j \leq n$) takes ($x+y+n-j$)-th place in the second round (sum - $y + x$) $i$-th participant ($1 \leq i \leq x+y-1$) takes ($y+x-i$)-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-1 \leq j \leq n$) takes ($x+y+n-j$)-th place in the second round (sum - $y + x$) Thus, the problem was reduced to the problem of output of two numbers - $\left< \max(1, \min(n, x + y - n + 1)),\;\;\min(n, x + y-1)\right>$
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,700
null
1313
C2
Skyscrapers (hard version)
This is a harder version of the problem. In this version $n \le 500\,000$ The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $n$ plots along the highway and is preparing to build $n$ skyscrapers, one skyscraper per plot. Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it. Formally, let's number the plots from $1$ to $n$. Then if the skyscraper on the $i$-th plot has $a_i$ floors, it must hold that $a_i$ is at most $m_i$ ($1 \le a_i \le m_i$). Also there mustn't be integers $j$ and $k$ such that $j < i < k$ and $a_j > a_i < a_k$. Plots $j$ and $k$ are \textbf{not} required to be adjacent to $i$. The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.
Let's solve the task on an array $m$ of length $n$. Let's find a minimal element in this array. Let it be on the $i$-th ($1 \leq i \leq n$) position. We can build the skyscraper at the $i$-th position as high as possible, that is $a_i = m_i$. Now we should make a choice - we need to equate to $a_i$ either the left part of the array ($a_1 = a_i, a_2 = a_i, \ldots, a_{i-1} = a_i$), or the right part ($a_{i+1} = a_i, a_{i+2} = a_i, \ldots, a_{n} = a_i$), and solve the task recursively on the remaining part of the array, until we get an array of length 1. The described recursive task has $n$ different states. Depending on the approach of finding a minimal element on a segment, we can get solutions of complexity $O(n^2)$, $O(n \sqrt{n})$ or $O(n \log n)$. There is another solution. It can be proved that the answer looks like this: from the start of the array the heights are non-decreasing, and starting from the certain skyscraper the heights are non-increasing. Let's call a skyscraper "peak" if there is the change of direction on this skyscraper. We are to find the optimal "peak". We can build arrays $l$ and $r$ of length $n$. Let's iterate positions from left to right. Let we are on the $i$-th position. If $m_i$ is the smallest element among $m_1, \ldots, m_i$, then $l_i = i \times m_i$. Otherwise, let's look at $m_1, m_2, \ldots, m_{i-1}$ and take the rightest number smaller than $m_i$, let it be $m_j$ on the $j$-th position. Then $l_i = l_j + (i - j) \times m_i$. Similarly, we build $r$ (but changing the direction from right to left). The "peak" is the skyscraper $t$ such that $l_t + r_t - m_t$ is maximal. The complexity of this solution can be $O(n^2)$, $O(n \log n)$, $O(n)$ depending on the approach of finding "nearest" numbers to the right and to the left that are smaller than the current one.
[ "data structures", "dp", "greedy" ]
1,900
null
1313
D
Happy New Year
Being Santa Claus is very difficult. Sometimes you have to deal with difficult situations. Today Santa Claus came to the holiday and there were $m$ children lined up in front of him. Let's number them from $1$ to $m$. Grandfather Frost knows $n$ spells. The $i$-th spell gives a candy to every child whose place is in the $[L_i, R_i]$ range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most $k$ candies. It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy. Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.
We wil use scanline to solve this problem. For all segments, we add event of its beginning and end. Let's maintain $dp_{i, mask}$, where $i$ is number of events that we have already processed. $mask$ is mask of $k$ bits, where $1$ in some bit means that segment corresponding to this bit is taken. How to move from one coordinate to another? For all masks we can count number of $1$ bits and if it is odd, we should add distance between to points to value of this $dp$. How to add new segment? As we know, at one point can be at most $k$ segments, so when we add segment we can find free bit and create match to this segment. After this operation we also should change some values of $dp$. Deleting of the segments is similar to adding. As you may notice, only $(i - 1)$-th lay is needed to calculate $i$-th lay, so we can use only $O(2^k)$ additional memory. Total complexity $O(n \log n + n2^k)$.
[ "bitmasks", "dp", "implementation" ]
2,500
null
1313
E
Concatenation with intersection
Vasya had three strings $a$, $b$ and $s$, which consist of lowercase English letters. The lengths of strings $a$ and $b$ are equal to $n$, the length of the string $s$ is equal to $m$. Vasya decided to choose a substring of the string $a$, then choose a substring of the string $b$ and concatenate them. Formally, he chooses a segment $[l_1, r_1]$ ($1 \leq l_1 \leq r_1 \leq n$) and a segment $[l_2, r_2]$ ($1 \leq l_2 \leq r_2 \leq n$), and after concatenation he obtains a string $a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} \ldots a_{r_1} b_{l_2} b_{l_2 + 1} \ldots b_{r_2}$. Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: - segments $[l_1, r_1]$ and $[l_2, r_2]$ have non-empty intersection, i.e. there exists at least one integer $x$, such that $l_1 \leq x \leq r_1$ and $l_2 \leq x \leq r_2$; - the string $a[l_1, r_1] + b[l_2, r_2]$ is equal to the string $s$.
For all $1 \leq i \leq n$ let's define $fa_i$ as the length of the longest common prefix of strings $a[i, n]$ and $s[1, m - 1]$, $fb_i$ as the length of the longest common suffix of strings $b[1, i]$ and $s[2, m]$. Values of $fa$ can be easily found from $z$-function of the string "$s\#a$", values of $fb$ from $z$-function of the string "$\overline{s}\#\overline{b}$" (here $\overline{s}$ is defined as reversed string $s$). Let's fix $l_1$ and $r_2$. Let's note, that $l_1 \leq r_2$, because segments have non-empty intersection. Also, the sum of lengths of segments is equal to $m$ and they have non-empty intersection, so $r_2 \leq l_1 + m - 2$. It's easy to see, that segments will have non-empty intersection if and only if $l_1 \leq r_2 \leq l_1 + m - 2$. Let's note, that if for fixed $l_1$ and $r_2$ innequalities are true, the number of segments with such $l_1$ and $r_2$ is equal to $\max{(fa_{l_1} + fb_{r_2} - m + 1, 0)}$. So, the answer to the problem is equal to $\sum\limits_{1 \leq l_1 \leq r_2 \leq \min{(l_1 + m - 2, n)}} {\max{(fa_{l_1} + fb_{r_2} - m + 1, 0)}} = \sum\limits_{l_1 = 1}^{n} {\sum\limits_{r_2 = l_1}^{\min{(l_1 + m - 2, n)}} {\max{(fa_{l_1} + fb_{r_2} - m + 1, 0)}}}$. Let's make two Fenwick trees on arrays of size $m$. Let's iterate $l_1$ from $1$ to $n$. For $r_2 \in [l_1, \min{(l_1 + m - 2, n)}]$ let's add in the position $m - 1 - fb_{r_2}$ of the first tree the number $1$, in the position $m - 1 - fb_{r_2}$ of the second tree the number $fb_{r_2}$. After that the sum for fixed $l_1$ can be easily found from sums in Fenwick trees on prefixes $i \leq fa_{l_1}$. The total complexity is $O(n \log{n})$.
[ "data structures", "hashing", "strings", "two pointers" ]
2,700
null
1315
A
Dead Pixel
Screen resolution of Polycarp's monitor is $a \times b$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $(x, y)$ ($0 \le x < a, 0 \le y < b$). You can consider columns of pixels to be numbered from $0$ to $a-1$, and rows — from $0$ to $b-1$. Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen. Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.
You can see that you should place the window in such a way so that the dead pixel is next to one of the borders of the screen: otherwise we can definitely increase the size of the window. There are four possible ways to place the window right next to the dead pixel - you can place it below, above, to the left or to the right of the dead pixel. if you place the window to the left to the pixel, the maximal size of the screen will be $x \cdot b$; if you place the window to the right to the pixel, the maximal size of the screen will be $(a - 1 - x) \cdot b$; if you place the window above the pixel, the maximal size of the screen will be $a \cdot y$; if you place the window above the pixel, the maximal size of the screen will be $a \cdot (b - 1 - y)$. These four cases can be united to one formula like $\max(\max(x, a-1-x) \cdot b, a \cdot \max(y, b-1-y))$.
[ "implementation" ]
800
null
1315
B
Homecoming
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $n$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string $s$ of length $n$, where $s_i = A$, if there is a bus station at $i$-th crossroad, and $s_i = B$, if there is a tram station at $i$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $s_1$) and his goal is to get to the last crossroad (which corresponds to $s_n$). If for two crossroads $i$ and $j$ for all crossroads $i, i+1, \ldots, j-1$ there is a bus station, one can pay $a$ roubles for the bus ticket, and go from $i$-th crossroad to the $j$-th crossroad by the bus (it is not necessary to have a bus station at the $j$-th crossroad). Formally, paying $a$ roubles Petya can go from $i$ to $j$ if $s_t = A$ for all $i \le t < j$. If for two crossroads $i$ and $j$ for all crossroads $i, i+1, \ldots, j-1$ there is a tram station, one can pay $b$ roubles for the tram ticket, and go from $i$-th crossroad to the $j$-th crossroad by the tram (it is not necessary to have a tram station at the $j$-th crossroad). Formally, paying $b$ roubles Petya can go from $i$ to $j$ if $s_t = B$ for all $i \le t < j$. For example, if $s$="AABBBAB", $a=4$ and $b=3$ then Petya needs: - buy one bus ticket to get from $1$ to $3$, - buy one tram ticket to get from $3$ to $6$, - buy one bus ticket to get from $6$ to $7$. Thus, in total he needs to spend $4+3+4=11$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $s_n$) does not affect the final expense. Now Petya is at the first crossroad, and he wants to get to the $n$-th crossroad. After the party he has left with $p$ roubles. He's decided to go to some station on foot, and then go to home using only public transport. Help him to choose the closest crossroad $i$ to go on foot the first, so he has enough money to get from the $i$-th crossroad to the $n$-th, using only tram and bus tickets.
The first thing you should do in this problem - you should understand the problem statement (which could be not very easy), and get the right answers to the sample test cases. Petya needs to find the minimal $i$ such that he has enough money to get from $i$ to $n$ (not $n+1$, he doesn't need to use the transport from the last crossroad. This was a rather common mistake in misunderstanding the statement) using only public transport. We can see that if Petya can get from $i$ to $n$ using only public transport, he can also get from any $j>i$ to $n$, using only public transport (because he will need fewer tickets). Let's iterate the candidates for $i$ from $n$ to $1$ and try to find the minimal possible $i$. Of course, Petya can go from $n$ to $n$ using only public transport (he doesn't need to buy any ticket). Suppose Petya can get from $j$ to $n$ for some $j$, and it would cost him $t_j$ money. How much money he would need to get from $j-1$ to $n$? He definitely should be able to buy a ticket at station $j-1$. So, if it is the same ticket he should buy at station $j$, he will need the same amount of money, because he doesn't need to buy two consecutive equal tickets, it has no sense. Otherwise, he should buy one more ticket. So, a minimal amount of money $t_{j-1}$ to get from $j-1$ to $j$ is $t_j$, if $j<n$ and $s_{j-1}=s_j$, and $t_j+cost(s_{j-1})$ otherwise ($cost(s_{j-1})$ is $a$ if $s_{j-1} = \texttt{A}$, and $b$ otherwise). If this value is greater than $p$, he should go to $j$ by foot, otherwise, we should resume the process because he can go to $j-1$ or even some less-numbered crossroads.
[ "binary search", "dp", "greedy", "strings" ]
1,300
null