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
⌀ |
|---|---|---|---|---|---|---|---|
1315
|
C
|
Restoring Permutation
|
You are given a sequence $b_1, b_2, \ldots, b_n$. Find the lexicographically minimal permutation $a_1, a_2, \ldots, a_{2n}$ such that $b_i = \min(a_{2i-1}, a_{2i})$, or determine that it is impossible.
|
This problem has a greedy solution. As you know the $b_i$, which is equal to $\min(a_{2i-1}, a_{2i})$, then one of $a_{2i-1}, a_{2i}$ should be equal to $b_i$. Which one? Of course, $a_{2i-1}$, because we want to get the lexicographically minimal answer, and we want to place a smaller number before the larger number. So, we know that $a_1 = b_1$, $a_3 = b_2$, $a_5 = b_3$, and so on, so we know all elements of the permutation with odd indices. What number should be placed at $a_2$? We know that $a_2 \ge a_1$ (as $a_1 \ne a_2$, and $b_1 = \min(a_1, a_2)$). So, let's take the $a_2 = x$ for minimal possible $x$ such that $x \ge a_1$ and $x \ne a_1, x \ne a_3, \ldots, x \ne a_{2n-1}$. If there is no such $x$ (if all numbers greater than $a_1$ are already used), there is no appropriate permutation. Otherwise, we should take $a_2=x$ and resume the process. The question is, why do we can place the minimal not used integer each time? Suppose there is another optimal answer $a'_1, a'_2, \ldots, a'_{2n}$, and we get $a_1, a_2, \ldots, a_{2n}$ or we didn't get any permutation by our greedy algorithm. As these two sequences are different, there is the first $k$ such that $a'_{2k} \ne a_{2k}$. As we tried to take the minimal possible $a_{2k}$, there are two options: $a_{2k} > a'_{2k}$. This is impossible as we tried to take the minimal possible $a_{2k}$, contradiction; $a_{2k} < a'_{2k}$. As $a'$ is <<optimal correct>> answer, we didn't finish our sequence $a$. Let's see, where is the number $a_{2k}$ in the sequence $a'$. It should be on some position $2l$, where $l>k$ (as $2k$ is the first difference between the sequences). But we can swap $a'_{2k}$ and $a'_{2l}$ and get smaller, but still correct sequence $a"$, so $a'$ is not optimal. Contradiction.
|
[
"greedy"
] | 1,200
| null |
1316
|
A
|
Grade Allocation
|
$n$ students are taking an exam. The highest possible score at this exam is $m$. Let $a_{i}$ be the score of the $i$-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
- All scores are integers
- $0 \leq a_{i} \leq m$
- The average score of the class doesn't change.
You are student $1$ and you would like to maximize your own score.
Find the highest possible score you can assign to yourself such that all conditions are satisfied.
|
Since the average score of the class must remain same ,this means the sum of the scores of all students in the class must remain same. We want to maximize the score of the first student and since the minimum score of each student can be zero we can add the scores of the rest of students to the first student as long as his score is less than or equal to m. Therefore the answer is $\min {(a_1+\sum_{i=2}^{i = n} a_{i} , m )}$ Time complexity : $O(n)$ per testcase
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll test;
cin>>test;
while(test--)
{
ll n,m;
cin>>n>>m;
ll s=0;
for(ll i=1;i<=n;i++)
{
ll x;
cin>>x;
s=s+x;
}
cout<<min(s,m)<<"\n";
}
return 0;
}
|
1316
|
B
|
String Modification
|
Vasya has a string $s$ of length $n$. He decides to make the following modification to the string:
- Pick an integer $k$, ($1 \leq k \leq n$).
- For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if string $s$ is qwer and $k = 2$, below is the series of transformations the string goes through:
- qwer (original string)
- wqer (after reversing the first substring of length $2$)
- weqr (after reversing the second substring of length $2$)
- werq (after reversing the last substring of length $2$)
Hence, the resulting string after modifying $s$ with $k = 2$ is werq.
Vasya wants to choose a $k$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $k$. Among all such $k$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.
A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:
- $a$ is a prefix of $b$, but $a \ne b$;
- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
|
Let the input string $s$ be $s_{1}s_{2}..s_{n}$. We observe the sequence of modifications that the string goes through for some value of $k$. After reversing the first sub-string of length $k$, the string becomes $s_{k}s_{k-1}..s_{1}s_{k+1}s_{k+2}..s_{n}$. Notice that the first character of this string will not be part of any subsequent modifications. After the next step of modification, the string becomes $s_{k}s_{k+1}s_{1}..s_{k-1}s_{k+2}..s_{n}$. Again, notice that the first two characters of this string will not be part of any subsequent modifications. Keep repeating the steps of modification. Do you see any pattern? It is easy to realise that after $i$ steps of modifications, the prefix of the resulting string will be $s_{k}s_{k+1}..s_{k+i-1}$. Since the number of sub-strings to reverse is $(n - k + 1)$, the prefix of our answer string will be $s_{k}s_{k+1}..s_{k+(n-k+1)-1}$, which is just the suffix string $s_{k}..s_{n}$. What about the suffix of our answer string? It can be observed that the suffix will be $s_{1}..s_{k-1}$ if $n$ and $k$ have the same parity and $s_{k-1}..s_{1}$ otherwise. We can generate and compare the modified string for each possible value of $k$ from $1$ to $n$ and find the lexicographically smallest among them. Additionally, we need to take care that the solution outputs the smallest possible $k$ in case when multiple values give the optimal string. Time complexity: $\mathcal{O}(n^{2})$ per testcase.
|
[
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
string modified(string& s, int n, int k) {
string result_prefix = s.substr(k - 1, n - k + 1);
string result_suffix = s.substr(0, k - 1);
if (n % 2 == k % 2)
reverse(result_suffix.begin(), result_suffix.end());
return result_prefix + result_suffix;
}
int main () {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
string s, best_s, temp;
int t, n, best_k;
cin >> t;
while (t--) {
cin >> n >> s;
best_s = modified(s, n, 1);
best_k = 1;
for (int k = 2; k <= n; ++k) {
temp = modified(s, n, k);
if (temp < best_s) {
best_s = temp;
best_k = k;
}
}
cout << best_s << '\n' << best_k << '\n';
}
return 0;
}
|
1316
|
C
|
Primitive Primes
|
It is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.
You are given two polynomials $f(x) = a_0 + a_1x + \dots + a_{n-1}x^{n-1}$ and $g(x) = b_0 + b_1x + \dots + b_{m-1}x^{m-1}$, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to $1$ for both the given polynomials. In other words, $gcd(a_0, a_1, \dots, a_{n-1}) = gcd(b_0, b_1, \dots, b_{m-1}) = 1$. Let $h(x) = f(x)\cdot g(x)$. Suppose that $h(x) = c_0 + c_1x + \dots + c_{n+m-2}x^{n+m-2}$.
You are also given a prime number $p$. Professor R challenges you to find any $t$ such that $c_t$ isn't divisible by $p$. He guarantees you that under these conditions such $t$ always exists. If there are several such $t$, output any of them.
\textbf{As the input is quite large, please use fast input reading methods.}
|
We will prove a simple result thereby giving one of the power that satisfies the constraint: We know that cumulative gcd of coefficients is one in both cases. Hence no prime divides all the coefficients of the polynomial. We call such polynomials primitive polynomials. This question in a way tells us that the product of two primitive polynomials is also a primitive polynomial. Let $x_i$ be the lowest power of $x$ in $f(x)$ whose coefficient is coprime to given prime $p$, and $x_j$ be the lowest power of $x$ in $g(x)$ whose coefficient is coprime to given prime $p$. Since both such coefficients exist, the answer is proved to exist. When we multiply $f(x)$ and $g(x)$, we get the following as the coefficient for $x^{i + j}$, $(a_0 * b_{i + j} + a_1 * b_{i + j - 1} + ...) + a_i * b_j + (a_{i + 1} * b_{j - 1} + a_{i + 2} * b_{j - 2} +...)$ We see the terms inside parentheses are all divisible by the prime $p$, and only $a_i * b_j$ is not divisible by $p$. So, we can say that the coefficient of $x^{i+j}$ is not divisible by $p$. Time complexity : $O(n+m)$
|
[
"constructive algorithms",
"math",
"ternary search"
] | 1,800
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
ll n,i,m,x,a,p,fir,sec;
cin >> n >> m >> p;
a=0;
for(i=0;i<n;i++)
{
cin >> x;
if(x%p && !a)
{
a=1;
fir=i;
}
}
a=0;
for(i=0;i<m;i++)
{
cin >> x;
if(x%p && !a)
{
a=1;
sec=i;
}
}
cout << fir+sec << endl;
return 0;
}
|
1316
|
D
|
Nash Matrix
|
Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands.
This board game is played on the $n\times n$ board. Rows and columns of this board are numbered from $1$ to $n$. The cell on the intersection of the $r$-th row and $c$-th column is denoted by $(r, c)$.
Some cells on the board are called \textbf{blocked zones}. On each cell of the board, there is written one of the following $5$ characters — $U$, $D$, $L$, $R$ or $X$ — instructions for the player. Suppose that the current cell is $(r, c)$. If the character is $R$, the player should move to the right cell $(r, c+1)$, for $L$ the player should move to the left cell $(r, c-1)$, for $U$ the player should move to the top cell $(r-1, c)$, for $D$ the player should move to the bottom cell $(r+1, c)$. Finally, if the character in the cell is $X$, then this cell is the \textbf{blocked zone}. The player should remain in this cell (the game for him isn't very interesting from now on).
It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.
As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.
For every of the $n^2$ cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell $(r, c)$ she wrote:
- a pair ($x$,$y$), meaning if a player had started at $(r, c)$, he would end up at cell ($x$,$y$).
- or a pair ($-1$,$-1$), meaning if a player had started at $(r, c)$, he would keep moving infinitely long and would never enter the blocked zone.
It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.
|
If there exists a valid board satisfying the input matrix, one can notice two types of clusters in the input matrix, first, a cluster of connected cells having the same stopping point and second, a cluster of connected cells which do not have any stopping point, i.e., all having pair $(-1,-1)$ . Among the cells, having a stopping point, we can start a dfs/bfs from all the cells having stopping point as the cell itself , i.e., cells $(i,j)$ has stopping cell as $(i,j)$. While performing the traversal, we move into any neighbouring cell from current cell if it has the same stopping cell as the current cell. This way, all the cells in clusters of first kind will have an instruction associated - $U$, $D$, $L$, $R$ or $X$ - . For the cells having no stopping cell, we need to put instructions on them such that starting on them, a player keeps moving in a cycle. So these cells are either a part of cycle, or have paths starting from them leading into a cycle. The simplest way to do so is to try to put such cells into disjoint pairs (cycles of length 2 of neighbouring cells), each cell in pair pointing towards the other. Note that after trying to pair up these cells having no stopping point, there are no more two adjacent such cells both unpaired. Now for any such cell which could not be paired up, if it has no adjacent paired up cell, then it is a case of INVALID , else , just put a direction on the cell so that player moves into the adjacent paired up cell. Now if any cell remains without having any instruction alloted, it is a case of INVALID. The complexity of the above solution : $O(n*n)$.
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
const int M = (1<<10)+5;
char mat[M][M];
int x[M][M],y[M][M];
int n;
bool connect(int p,int q,int r,int s,char d1,char d2)
{
if(x[r][s] == -1)
{
mat[p][q] = d1;
if(mat[r][s] == '\0') mat[r][s] = d2;
return 1;
}
else
return 0;
}
void dfs(int p,int q,char d)
{
if(mat[p][q] != '\0') return;
mat[p][q] = d;
if(x[p][q] == x[p+1][q] && y[p][q] == y[p+1][q])
dfs(p+1,q,'U');
if(x[p][q] == x[p-1][q] && y[p][q] == y[p-1][q])
dfs(p-1,q,'D');
if(x[p][q] == x[p][q+1] && y[p][q] == y[p][q+1])
dfs(p,q+1,'L');
if(x[p][q] == x[p][q-1] && y[p][q] == y[p][q-1])
dfs(p,q-1,'R');
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int i,j;
cin >> n;
for(i=1;i<=n;++i)
{
for(j=1;j<=n;++j)
cin >> x[i][j] >> y[i][j];
}
for(i=1;i<=n;++i)
{
for(j=1;j<=n;++j)
{
if(x[i][j] == -1)
{
bool res = (mat[i][j] != '\0');
if(res == 0) res = connect(i,j,i+1,j,'D','U');
if(res == 0) res = connect(i,j,i,j+1,'R','L');
if(res == 0) res = connect(i,j,i-1,j,'U','D');
if(res == 0) res = connect(i,j,i,j-1,'L','R');
if(res == 0)
{
cout << "INVALID" << "\n";
return 0;
}
}
else if(x[i][j] == i && y[i][j] == j)
dfs(i,j,'X');
}
}
for(i=1;i<=n;++i)
{
for(j=1;j<=n;++j)
{
if(mat[i][j] == '\0')
{
cout << "INVALID" << "\n";
return 0;
}
}
}
cout << "VALID" << "\n";
for(i=1;i<=n;++i)
{
for(j=1;j<=n;++j)
{
cout << mat[i][j];
}
cout << "\n";
}
return 0;
}
|
1316
|
E
|
Team Building
|
Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of $p$ players playing in $p$ different positions. She also recognizes the importance of audience support, so she wants to select $k$ people as part of the audience.
There are $n$ people in Byteland. Alice needs to select exactly $p$ players, one for each position, and exactly $k$ members of the audience from this pool of $n$ people. Her ultimate goal is to maximize the total strength of the club.
The $i$-th of the $n$ persons has an integer $a_{i}$ associated with him — the strength he adds to the club if he is selected as a member of the audience.
For each person $i$ and for each position $j$, Alice knows $s_{i, j}$ — the strength added by the $i$-th person to the club if he is selected to play in the $j$-th position.
Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.
Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.
|
Idea is DP(bitmask) First sort the people in non-increasing order of $a_{i}$. let $dp[i][mask]$ = maximum strength of the club if we choose players from $1 \ldots i$, mask tells us about the positions in the team which have been covered. Don't worry about the audience part as of now, we will see how it is handled during transitions. $dp[0][0]=0$ - initial state. Lets try to find $dp[i][mask]$ If the $i$-th person is chosen to play in $j$-th position, $dp[i][mask] = dp[i-1][mask \oplus 2^j] + s_{i,j}$ - $(1)$. If we don't choose $i$ as a player, then we can take him as an audience member or not take him at all. I claim that if the no. of audience members chosen till now < $k$, then we must select $i$ as an audience member , We can prove this. If we don't select $i$ as audience, we will need to select some $j$ ($j>i$), strength in that case will include $a_j$ but not $a_i$ , but as $a_i \geq a_j$, it is always better to select $i$. We now need to know how many audience members have been selected for state $(i-1,mask)$. let $c$ be the no. of persons who have not been selected as players, then $c$ = $i-1$ - no. of set bits in mask.By the above logic, we can say that if $c \geq k$, we have chosen already k audience members. So, the solution becomes: if $c < k$ , then $dp[i][mask] = dp[i-1][mask] + a_i$ - (2), else $dp[i][mask] = dp[i-1][mask]$ - (2), You need to choose maximum of $(1)$ and $(2)$ as $dp[i][mask]$. $dp[n][2^p-1]$ would be the answer to our question. Time Complexity : $O(n \cdot p \cdot 2^p)$.
|
[
"bitmasks",
"dp",
"greedy",
"sortings"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
const ll M=1e5+5;
ll dp[M][(1<<7)+1],skill[M][7];
ll ind[M],a[M];
bool cmp(ll p,ll q)
{
return a[p]>a[q];
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
ll n,p,k;
cin>>n>>p>>k;
memset(dp,-1,sizeof(dp));
for(ll i=1;i<=n;i++)
cin>>a[i];
for(ll i=1;i<=n;i++)
for(ll j=0;j<p;j++)
cin>>skill[i][j];
for(ll i=1;i<=n;i++)
ind[i]=i;
sort(ind+1,ind+n+1,cmp);
dp[0][0]=0;
for(ll i=1;i<=n;i++)
{
ll x=ind[i];
for(ll mask=0;mask<(1<<p);mask++)
{
ll ct=0;
for(ll j=0;j<p;j++)
if((mask&(1<<j)))
ct++;
ll z=(i-1)-ct;
if(z<k)
{
if(dp[i-1][mask]!=-1)
dp[i][mask]=dp[i-1][mask]+a[x];
}
else
{
if(dp[i-1][mask]!=-1)
dp[i][mask]=dp[i-1][mask];
}
for(ll j=0;j<p;j++)
{
if((mask&(1<<j)) && dp[i-1][(mask^(1<<j))]!=-1)
{
ll z=dp[i-1][(mask^(1<<j))]+skill[x][j];
if(z>dp[i][mask])
dp[i][mask]=z;
}
}
}
}
cout<<dp[n][(1<<p)-1]<<"\n";
return 0;
}
|
1316
|
F
|
Battalion Strength
|
There are $n$ officers in the Army of Byteland. Each officer has some power associated with him. The power of the $i$-th officer is denoted by $p_{i}$. As the war is fast approaching, the General would like to know the strength of the army.
The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these $n$ officers and calls this subset a battalion.(All $2^n$ subsets of the $n$ officers can be chosen equally likely, including empty subset and the subset of all officers).
The strength of a battalion is calculated in the following way:
Let the powers of the chosen officers be $a_{1},a_{2},\ldots,a_{k}$, where $a_1 \le a_2 \le \dots \le a_k$. The strength of this battalion is equal to $a_1a_2 + a_2a_3 + \dots + a_{k-1}a_k$. (If the size of Battalion is $\leq 1$, then the strength of this battalion is $0$).
The strength of the army is equal to the expected value of the strength of the battalion.
As the war is really long, the powers of officers may change. Precisely, there will be $q$ changes. Each one of the form $i$ $x$ indicating that $p_{i}$ is changed to $x$.
You need to find the strength of the army initially and after each of these $q$ updates.
Note that the changes are permanent.
The strength should be found by modulo $10^{9}+7$. Formally, let $M=10^{9}+7$. It can be shown that the answer can be expressed as an irreducible fraction $p/q$, where $p$ and $q$ are integers and $q\not\equiv 0 \bmod M$). Output the integer equal to $p\cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \leq x < M$ and $x ⋅ q \equiv p \bmod M$).
|
First lets try to find the initial strength of the army. Let $p_1,p_2,\ldots,p_n$ be the powers of officers in sorted order. . Consider a pair ($i,j$) ($i < j$) and find how much it contributes to the answer, the term $p_i \cdot p_j$ will be present in the strength of the subsets in which both $i$ and $j$ are present and there is no $k$ such that $i < k < j$. Probability of this happening is $\frac {1}{2^{j-i+1}}$. By linearity of expectation we can say that the contribution of ($i,j$) to the strength of the army is $p_i \cdot p_j \cdot \frac {1}{2^{j-i+1}}$. So the strenth of the army can be written as $S = \sum_{i=1}^{n} \sum_{j=i+1}^{n} prob_{i,j} \cdot p_i \cdot p_j$ where $prob_{i,j} = \frac {1}{2^{j-i+1}}$. We can keep a sorted array having $p_1,p_2,\ldots,p_n$, we can maintain a prefix sum of $pref_i$ = $p_i \cdot 2^{i-1}$,so $S = \sum_{j=1}^{n} pref_{j-1} \cdot \frac{p_j}{2^{j}}$. But this will not help in handling the updtes. To support updates, we need to process queries offline and use coordinate compression such that all powers lie in range $(1,10^6)$. We can build a segment tree on the compressed powers. For each node of the segment tree, let its range be $(s,e)$, consider that powers(mapped values by coordinate compression) $p_1,p_2,\ldots,p_k$ line in the range of this node ($s \leq p_1 \leq p_2 \leq \ldots \leq p_k \leq e$). At each node, we need to maintain 4 values. $val: \sum_{i=1}^{k} \sum_{j=i+1}^{k} prob_{i,j} \cdot p_i \cdot p_j$ $Lval: \sum_{i=1}^{k} p_i \cdot 2^{i-1}$ $Rval: \sum_{j=1}^{k} \frac{p_j}{2^{j}}$ $count: k$ If we map each power to a unique value, the computation for this values at leaf node $(s=e)$ is trivial. If some power $p$ in the initial set is mapped to s, then values for this node are as follows $val: 0$ $Lval: p$ $Rval: \frac{p}{2}$ $count: 1$. Lets try to compute these 4 values for non-leaf nodes of the segment tree. (lc and rc denote left and right children of the current node). If we try to write break these values in terms of their counterparts in lc and rc, we can easily write them as: $val : val_{lc}+val_{rc}+\frac{Lval_{lc} \cdot Rval_{rc}}{2^{count_{lc}}}$ $Lval : Lval_{lc} + Lval_{rc} \cdot 2^{count_{lc}}$ $Rval : Rval_{lc} + \frac {Rval_{rc}}{2^{count_{lc}}}$ $count : count_{lc} + count_{rc}$ Whenver we get a query ,we will need to update 2 leaves, reduce count of the power for old $p_i$ and increase the count of the new_power $p_i = x$. Answer to our problem would be $val$ at root node of the segment tree. Time Complexity: $O((n+q)log(n))$
|
[
"data structures",
"divide and conquer",
"probabilities"
] | 2,800
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ff first
#define ss second
#define pb push_back
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
const ll M=6e5+6;
const ll mod=1e9+7;
ll val[4*M],lt[4*M],rt[4*M];
int no[4*M];
ll pw[M],ipw[M];
int P[M],idx[M],qr[M],n,q;
vector<pair<int,int> > v;
ll power(ll a,ll b)
{
ll val=1;
while(b)
{
if(b%2)
val=(val*a)%mod;
b/=2;
a=(a*a)%mod;
}
return val;
}
void build(int i,int s,int e)
{
if(s==e)
{
if(v[s].ss>n)
return;
val[i]=0;
lt[i]=v[s].ff;
rt[i]=(v[s].ff*ipw[1])%mod;
no[i]=1;
return;
}
int m=(s+e)/2;
int lc=2*i,rc=2*i+1;
build(lc,s,m);
build(rc,m+1,e);
ll tp=(ipw[no[lc]]*rt[rc])%mod;
tp=(tp*lt[lc])%mod;
val[i]=(val[lc]+val[rc]+tp)%mod;
lt[i]=(lt[lc]+pw[no[lc]]*lt[rc])%mod;
rt[i]=(rt[lc]+ipw[no[lc]]*rt[rc])%mod;
no[i]=(no[lc]+no[rc]);
}
void update(int i,int s,int e,int x,int y)
{
if(s==e)
{
if(y==-1)
{
val[i]=0;
lt[i]=0;
rt[i]=0;
no[i]=0;
}
else
{
val[i]=0;
lt[i]=v[s].ff;
rt[i]=(v[s].ff*ipw[1])%mod;
no[i]=1;
}
return;
}
int m=(s+e)/2;
int lc=(i<<1),rc=(lc|1);
if(x<=m)
update(lc,s,m,x,y);
else
update(rc,m+1,e,x,y);
ll tp=(ipw[no[lc]]*rt[rc])%mod;
tp=(tp*lt[lc])%mod;
val[i]=(val[lc]+val[rc]+tp)%mod;
lt[i]=(lt[lc]+pw[no[lc]]*lt[rc])%mod;
rt[i]=(rt[lc]+ipw[no[lc]]*rt[rc])%mod;
no[i]=(no[lc]+no[rc]);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
pw[0]=1;
ipw[0]=1;
ll inv=power(2,mod-2);
for(int i=1;i<M;i++)
{
pw[i]=(pw[i-1]*2)%mod;
ipw[i]=(ipw[i-1]*inv)%mod;
}
cin>>n;
v.pb({-1LL,-1});
for(int i=1;i<=n;i++)
{
cin>>P[i];
v.pb({P[i],i});
}
cin>>q;
for(int i=1;i<=q;i++)
{
cin>>idx[i]>>qr[i];
v.pb({qr[i],n+i});
}
sort(all(v));
std::vector<int> pos(n+q+1,0);
for(int i=1;i<sz(v);i++)
pos[v[i].ss]=i;
build(1,1,n+q);
cout<<val[1]<<"\n";
for(int i=1;i<=q;i++)
{
update(1,1,n+q,pos[idx[i]],-1);
pos[idx[i]]=pos[n+i];
update(1,1,n+q,pos[idx[i]],1);
cout<<val[1]<<"\n";
}
return 0;
}
|
1320
|
A
|
Journey Planning
|
Tanya wants to go on a journey across the cities of Berland. There are $n$ cities situated along the main railroad line of Berland, and these cities are numbered from $1$ to $n$.
Tanya plans her journey as follows. First of all, she will choose some city $c_1$ to start her journey. She will visit it, and after that go to some other city $c_2 > c_1$, then to some other city $c_3 > c_2$, and so on, until she chooses to end her journey in some city $c_k > c_{k - 1}$. So, the sequence of visited cities $[c_1, c_2, \dots, c_k]$ should be strictly increasing.
There are some additional constraints on the sequence of cities Tanya visits. Each city $i$ has a beauty value $b_i$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $c_i$ and $c_{i + 1}$, the condition $c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$ must hold.
For example, if $n = 8$ and $b = [3, 4, 4, 6, 6, 7, 8, 9]$, there are several three possible ways to plan a journey:
- $c = [1, 2, 4]$;
- $c = [3, 5, 6, 8]$;
- $c = [7]$ (a journey consisting of one city is also valid).
There are some additional ways to plan a journey that are not listed above.
Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
|
Let's rewrite the equality given in the statement as $c_{i + 1} - b_{c_{i + 1}} = c_i - b_{c_i}$. It means that all cities in our path will have the same value of $i - b_i$; furthermore, all cities with the same such value can always be visited in ascending order. So we may group cities by $i - b_i$, compute the sum in each group and find the maximum over all groups. For example, this can be done by storing the sum for each $i - b_i$ in an array (be careful with negative values of $i - b_i$, though!)
|
[
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | 1,400
| null |
1320
|
B
|
Navigation System
|
The map of Bertown can be represented as a set of $n$ intersections, numbered from $1$ to $n$ and connected by $m$ one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection $v$ to another intersection $u$ is the path that starts in $v$, ends in $u$ and has the minimum length among all such paths.
Polycarp lives near the intersection $s$ and works in a building near the intersection $t$. Every day he gets from $s$ to $t$ by car. Today he has chosen the following path to his workplace: $p_1$, $p_2$, ..., $p_k$, where $p_1 = s$, $p_k = t$, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. \textbf{Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from $s$ to $t$}.
Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection $s$, the system chooses some shortest path from $s$ to $t$ and shows it to Polycarp. Let's denote the next intersection in the chosen path as $v$. If Polycarp chooses to drive along the road from $s$ to $v$, then the navigator shows him the same shortest path (obviously, starting from $v$ as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection $w$ instead, the navigator \textbf{rebuilds} the path: as soon as Polycarp arrives at $w$, the navigation system chooses some shortest path from $w$ to $t$ and shows it to Polycarp. The same process continues until Polycarp arrives at $t$: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system \textbf{rebuilds} the path by the same rules.
Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path $[1, 2, 3, 4]$ ($s = 1$, $t = 4$):
\begin{center}
Check the picture by the link http://tk.codeforces.com/a.png
\end{center}
- When Polycarp starts at $1$, the system chooses some shortest path from $1$ to $4$. There is only one such path, it is $[1, 5, 4]$;
- Polycarp chooses to drive to $2$, which is not along the path chosen by the system. When Polycarp arrives at $2$, the navigator \textbf{rebuilds} the path by choosing some shortest path from $2$ to $4$, for example, $[2, 6, 4]$ (note that it could choose $[2, 3, 4]$);
- Polycarp chooses to drive to $3$, which is not along the path chosen by the system. When Polycarp arrives at $3$, the navigator \textbf{rebuilds} the path by choosing the only shortest path from $3$ to $4$, which is $[3, 4]$;
- Polycarp arrives at $4$ along the road chosen by the navigator, so the system does not have to rebuild anything.
Overall, we get $2$ rebuilds in this scenario. Note that if the system chose $[2, 3, 4]$ instead of $[2, 6, 4]$ during the second step, there would be only $1$ rebuild (since Polycarp goes along the path, so the system maintains the path $[3, 4]$ during the third step).
The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?
|
Let $d_v$ be the length of the shortest path from $v$ to $t$. If we move from vertex $v$ to vertex $u$ on our path, then: the rebuild will definitely occur if $d_u > d_v - 1$; the rebuild may occur if there exists at least one vertex $w \ne u$ such that $d_w = d_v - 1$ (the navigation system could have built a path through $w$). We can calculate all values of $d_v$ using BFS from $t$ on a transposed graph. Now for each vertex, we can easily determine whether it should be added to the set of vertices where the route definitely rebuilds and to the set of vertices where a rebuild is possible.
|
[
"dfs and similar",
"graphs",
"shortest paths"
] | 1,700
| null |
1320
|
C
|
World of Darkraft: Battle for Azathoth
|
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.
Roma has a choice to buy \textbf{exactly one} of $n$ different weapons and \textbf{exactly one} of $m$ different armor sets. Weapon $i$ has attack modifier $a_i$ and is worth $ca_i$ coins, and armor set $j$ has defense modifier $b_j$ and is worth $cb_j$ coins.
After choosing his equipment Roma can proceed to defeat some monsters. There are $p$ monsters he can try to defeat. Monster $k$ has defense $x_k$, attack $y_k$ and possesses $z_k$ coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster $k$ can be defeated with a weapon $i$ and an armor set $j$ if $a_i > x_k$ and $b_j > y_k$. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.
Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma \textbf{must} purchase a weapon and an armor set even if he can not cover their cost with obtained coins.
Help Roma find the maximum profit of the grind.
|
Let $S_a$ be the set of monsters which may be defeated with a weapon having attack $a$. Then the profit we get, if we use weapon $i$ with attack $a$ and armor $j$ with defense $b$, is $-ca_i-cb_j+( \textrm{the sum of $z_k$ over all monsters $k$ from the set $S_a$ having $y_k < b$})$. We will iterate on weapons in non-descending order of their attack values and maintain $S_a$. For each armor option, maintain the value of $D_j = -cb_j+(\textrm{total profit from monsters having attack less than $b_j$})$. If armor sets are sorted by their defense value, adding a new monster into $S_a$ adds some value on the suffix of $D_j$. So we can maintain the values of $D_j$ in a segment tree. So the solution is: Build a segment tree on values of $-cb_j$, where all armors are sorted by $b_j$. Iterate on weapons and monsters in sorted order (sort by $a_i$/$x_k$ in non-descending order). For each new weapon $i$ we should add all monsters $x_k < a_i$ which were not added yet (we can maintain a pointer on the last added monster to find them quickly). Adding a monster means adding $z_k$ on suffix of $D_i$. After that, for the current weapon $i$ we may try $-ca_i + \max D_j$ as the answer.
|
[
"brute force",
"data structures",
"sortings"
] | 2,000
| null |
1320
|
D
|
Reachable Strings
|
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \dots r]$. The characters of each string are numbered from $1$.
We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.
Binary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., \textbf{every string is reachable from itself}.
You are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$.
|
How to determine if two strings can be transformed into each other? Obviously, the number of ones in both strings should be the same. Also the following invariant holds: if all pairs of consecutive ones are deleted, the positions of remaining ones are not affected by any operations. We can prove that these conditions are sufficient: if we move all pairs of ones to the end of the string, the strings are the same if the positions of ones are the same and the number of characters is the same (moving all pairs of ones to the end of the string is almost the same as deleting them). One of the possible solutions is the following - build a segment tree, where each vertex should maintain: the number of deleted pairs of ones; the hash of positions of the remaining ones; the characters at the ends of the corresponding segment (we need these to delete pairs of consecutive ones, if they appear as a result of merging the segments). When merging a pair of vertices, we check if we have to delete a pair of consecutive ones and rebuild the hash for the new vertex. There are lots of other approaches, including a deterministic one (which uses suffix structures).
|
[
"data structures",
"hashing",
"strings"
] | 2,500
| null |
1320
|
E
|
Treeland and Viruses
|
There are $n$ cities in Treeland connected with $n - 1$ bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.
In each scenario, several cities are initially infected with different virus species. Suppose that there are $k_i$ virus species in the $i$-th scenario. Let us denote $v_j$ the initial city for the virus $j$, and $s_j$ the propagation speed of the virus $j$. The spread of the viruses happens in turns: first virus $1$ spreads, followed by virus $2$, and so on. After virus $k_i$ spreads, the process starts again from virus $1$.
A spread turn of virus $j$ proceeds as follows. For each city $x$ not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus $j$ if and only if there is such a city $y$ that:
- city $y$ was infected with virus $j$ at the start of the turn;
- the path between cities $x$ and $y$ contains at most $s_j$ edges;
- all cities on the path between cities $x$ and $y$ (excluding $y$) were uninfected with any virus at the start of the turn.
Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.
You need to process $q$ independent scenarios. Each scenario is described by $k_i$ virus species and $m_i$ important cities. For each important city determine which the virus it will be infected by in the end.
|
When processing a query, the key idea is to build a compressed version of the tree containing only some important vertices. We are not interested in vertices not belonging to any path between some $v_i$ and $u_i$. Furthermore, we can compress all chains in the tree by deleting all vertices with degree $< 2$ not listed in the query. To find all the important vertices in the compressed tree, we may do the following: sort all $v_i$ and $u_i$ by their entry time in DFS traversal of the tree, and then add LCA's of all neighbouring pairs in the sorted list. To restore the edges, we will consider all important vertices in sorted order and maintain the path to the current vertex in a stack. When we process a vertex, we delete vertices from top of the stack until we get an ancestor of current vertex on top of the stack, then this ancestor is the parent of the current vertex in the compressed tree. When we have the compressed tree, there are two approaches to determining the virus affecting each node: Run Dijkstra's algorithm. The distance for each vertex $v$ is the pair (the time when $v$ becomes infected, the index of a virus infecting $v$). For each initially infected vertex $v_i$ the initial distance is $(0,i)$. When processing a vertex with Dijkstra, we can try to infect all of its neighbours with the same virus. Use subtree DP. First of all, for each vertex we determine the virus from its subtree that will infecting it (not taking into account any viruses from above): it's either the virus in this vertex or the virus infecting one of its children. Then we may to the same thing in the other direction: push viruses down the tree and calculate whether they are infecting vertices faster than the viruses from the lower vertices. In any case, each query is processed in $O((k + m) \log n)$.
|
[
"data structures",
"dfs and similar",
"dp",
"shortest paths",
"trees"
] | 3,000
| null |
1320
|
F
|
Blocks and Sensors
|
Polycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size $1 \times 1 \times 1$. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size $1 \times 1 \times 1$; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates $(x, y, z)$ (the cell with these coordinates is a cube with opposite corners in $(x, y, z)$ and $(x + 1, y + 1, z + 1)$) and its contents $a_{x, y, z}$; if the cell is empty, then $a_{x, y, z} = 0$, otherwise $a_{x, y, z}$ is equal to the type of the block placed in it (the types are integers from $1$ to $2 \cdot 10^5$).
Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size $n \times m \times k$, containing all cells $(x, y, z)$ such that $x \in [1, n]$, $y \in [1, m]$, and $z \in [1, k]$. After that, Polycarp has installed $2nm + 2nk + 2mk$ sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into $6$ types:
- there are $mk$ sensors of the first type; each such sensor is installed in $(0, y, z)$, where $y \in [1, m]$ and $z \in [1, k]$, and it sends a ray that is parallel to the $Ox$ axis and has the same direction;
- there are $mk$ sensors of the second type; each such sensor is installed in $(n + 1, y, z)$, where $y \in [1, m]$ and $z \in [1, k]$, and it sends a ray that is parallel to the $Ox$ axis and has the opposite direction;
- there are $nk$ sensors of the third type; each such sensor is installed in $(x, 0, z)$, where $x \in [1, n]$ and $z \in [1, k]$, and it sends a ray that is parallel to the $Oy$ axis and has the same direction;
- there are $nk$ sensors of the fourth type; each such sensor is installed in $(x, m + 1, z)$, where $x \in [1, n]$ and $z \in [1, k]$, and it sends a ray that is parallel to the $Oy$ axis and has the opposite direction;
- there are $nm$ sensors of the fifth type; each such sensor is installed in $(x, y, 0)$, where $x \in [1, n]$ and $y \in [1, m]$, and it sends a ray that is parallel to the $Oz$ axis and has the same direction;
- finally, there are $nm$ sensors of the sixth type; each such sensor is installed in $(x, y, k + 1)$, where $x \in [1, n]$ and $y \in [1, m]$, and it sends a ray that is parallel to the $Oz$ axis and has the opposite direction.
Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.
After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?
|
Initially fill each cell with a colorless block, and then try to paint blocks and delete them if they definitely contradict the sensor data. We have to delete a block if: it is observed by a sensor which should see no blocks; it is observed by at least two sensors that report different block types. In any of these cases, we delete a block. Then we update all sensors which were looking at it: for each of them, find the next block which they are looking at, and maybe delete it (if the information for it is contradictory). If this results in deleting all blocks for a sensor that should see a block, then the answer is $-1$. If this process terminates without any contradictions, we can construct the answer. Now all sensors that should not see any blocks don't see them, and each block observed by sensors can be assigned a type that does not contradict the sensor data. If some block is not observed by sensors at all, we may assign any color to it (or even delete it). To maintain blocks that should be deleted, we may use a BFS-like approach with a queue, or a DFS-like function that deletes a block, updates the sensors looking at it, and maybe calls itself recursively for the blocks that have to be deleted after the updates.
|
[
"brute force"
] | 3,500
| null |
1321
|
A
|
Contest for Robots
|
Polycarp is preparing the first programming contest for robots. There are $n$ problems in it, and a lot of robots are going to participate in it. Each robot solving the problem $i$ gets $p_i$ points, and the score of each robot in the competition is calculated as the sum of $p_i$ over all problems $i$ solved by it. For each problem, $p_i$ is an integer not less than $1$.
Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them.
For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of $p_i$ in such a way that the "Robo-Coder Inc." robot gets \textbf{strictly more} points than the "BionicSolver Industries" robot. However, if the values of $p_i$ will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of $p_i$ over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?
|
Score distribution for problems having $r_i = b_i$ is irrelevant (we can make $p_i = 1$ for all of them). Let's consider the remaining problems. Suppose we have $x$ problems solved by the first robot (and not solved by the second one), and $y$ problems solved by the second robot (and not solved by the first one). If $x = 0$, then the score of the first robot won't exceed the score of the second robot by any means, so the answer is $-1$. Otherwise, we can set the score for problems solved by the first robot to some number $p$, and the score for all remaining problems to $1$. Then, the condition $xp > y$ must hold, or $p > \frac{y}{x}$, so $p = \lceil \frac{y + 1}{x} \rceil$ is the answer. Note that the constraints allow us to iterate on $p$ instead of implementing a formula for it.
|
[
"greedy"
] | 900
| null |
1321
|
C
|
Remove Adjacent
|
You are given a string $s$ consisting of lowercase Latin letters. Let the length of $s$ be $|s|$. You may perform several operations on this string.
In one operation, you can choose some index $i$ and \textbf{remove} the $i$-th character of $s$ ($s_i$) if \textbf{at least one} of its adjacent characters is the previous letter in the Latin alphabet for $s_i$. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index $i$ should satisfy the condition $1 \le i \le |s|$ during each operation.
For the character $s_i$ adjacent characters are $s_{i-1}$ and $s_{i+1}$. The first and the last characters of $s$ both have only one adjacent character (unless $|s| = 1$).
Consider the following example. Let $s=$ bacabcab.
- During the first move, you can remove the first character $s_1=$ b because $s_2=$ a. Then the string becomes $s=$ acabcab.
- During the second move, you can remove the fifth character $s_5=$ c because $s_4=$ b. Then the string becomes $s=$ acabab.
- During the third move, you can remove the sixth character $s_6=$'b' because $s_5=$ a. Then the string becomes $s=$ acaba.
- During the fourth move, the only character you can remove is $s_4=$ b, because $s_3=$ a (or $s_5=$ a). The string becomes $s=$ acaa and you cannot do anything with it.
Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.
|
The optimal answer can be obtained by the following algorithm: choose the maximum possible (alphabetically) letter we can remove and remove it. We can do it naively and it will lead to $O(n^2)$ time complexity. Why is it always true? Suppose we remove the maximum letter $i$ that can be used to remove some other letter $j$ (it is obvious that $s_i + 1 = s_j$ in such case). If there are no other letters between $s_i$ and $s_j$ then $s_i$ is not the maximum letter, so we got contradiction with our algorithm. Now suppose that we can remove all letters between $s_i$ and $s_j$. Then we first choose $s_j$ and only after that $s_i$ by our algorithm. Consider the last case - there is at least one letter $s_k$ between $s_i$ and $s_j$. Because we cannot remove $s_k$ then there are only two cases: $s_k > s_j + 1$ or $s_k + 1 < s_i$. Then we cannot use $s_i$ to remove $s_j$ at all.
|
[
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | 1,600
| null |
1322
|
A
|
Unusual Competitions
|
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can \textbf{the arbitrary number of times} (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $l$ nanoseconds, where $l$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $2$ nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
|
Obviously, if the number of opening brackets is not equal to the number of closing ones, then since the described operation does not change their number, it will be impossible to get the correct sequence. Otherwise, if their numbers are equal, you can take the entire string and rearrange its $n$ characters so that the string becomes a right bracketed sequence, for example, "(((($\dots$))))". Let $p_i$ be a prefix balance on the first $i$ characters, that is, the difference between the number of opening and closing brackets. Consider an index $i$ such that $bal_{i-1} \leq 0$, $bal_{i} < 0$, or $bal_{i-1} < 0$, $bal_i \leq 0$. Then, if the $s_i$ character does not participate in any shuffle oeration, the resulting string will have a $i$th or $i-1$th prefix balance negative, making the resulting sequence incorrect. This means that at least characters with such indexes $i$ must participate in at least one operation. It will be shown below how to use only them in shuffles to make a right bracketed sequence. Let's represent this bracketed sequence as a polyline. It will start at the point with coordinates $(0,0)$, end at the point with coordinates $(2n, 0)$, $i$ - th vector of this polyline will be equal to $(+1, +1)$, if $s_i =$ ( and $(+1, -1)$ otherwise. Then the above-described indexes $i$, which must participate in at least one operation - are exactly all the segments below the line $x=0$. To make the sequence correct, we will turn all consecutive segments of such brackets backwards. It's not hard to see that the sequence will become correct. An example of this conversion is shown below:
|
[
"greedy"
] | 1,300
| null |
1322
|
B
|
Present
|
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute
$$ (a_1 + a_2) \oplus (a_1 + a_3) \oplus \ldots \oplus (a_1 + a_n) \\ \oplus (a_2 + a_3) \oplus \ldots \oplus (a_2 + a_n) \\ \ldots \\ \oplus (a_{n-1} + a_n) \\ $$
Here $x \oplus y$ is a bitwise XOR operation (i.e. $x$ ^ $y$ in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.
|
Let's calculate each bit in the answer separately. Suppose we want to know the value of $k$-th (in 0-indexation) bit in the answer. Then we can notice that we are only interested in bits from $0$-th to $k$-th, which means that we can take all numbers modulo $2^{k+1}$. After that, the sum of the two numbers can't exceed $2^{k+2} - 2$. $k$-th bit is 1 if and only if sum belongs to $[2^k; 2^{k+1})$ or $[2^{k+1} + 2^k; 2^{k+2} - 2]$. So, we have to count the number of pairs of numbers that give a sum that belongs to these segments. Let's sort all numbers (taken by modulo) and make a pass with two pointers or do binary searches for each number. Total complexity: $O(n \log n \log C)$ Bonus: can you do it in $O(n \log C)$?
|
[
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | 2,100
| null |
1322
|
C
|
Instant Noodles
|
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.
You are given a bipartite graph with positive integers in all vertices of the \textbf{right} half. For a subset $S$ of vertices of the \textbf{left} half we define $N(S)$ as the set of all vertices of the right half adjacent to at least one vertex in $S$, and $f(S)$ as the sum of all numbers in vertices of $N(S)$. Find the greatest common divisor of $f(S)$ for all possible non-empty subsets $S$ (assume that GCD of empty set is $0$).
Wu is too tired after his training to solve this problem. Help him!
|
Let's split vertices of right half of graph in groups in such a way that group consists of vertices with same neighboring set. Then answer equals to $gcd$ of sums of numbers in all groups except the group with empty neighboring set. Let's prove it. If there are some vertices with same list of neighbors then they will both in some $N(S)$ or none of them will be in it. It means that we can replace such vertices with one vertex with value equals to sum of values in these vertices. After that numbers in all vertices are divisible by answer and thus sum of every subset is divisible by it. Let's divide all the numbers by answer and prove that after it answer will be 1. Consider some integer $k$ and we'll find some set of vertices $S$ such that $f(S)$ is not divisible by $k$. If sum of all numbers is not divisible by $k$ we can take all the left half and its sum is not divisible by $k$. Otherwise consider a vertex with minimum degree such that its value is not divisible by $k$ (such vertex exists because gcd of numbers in right half is 1 now). Let's take subset of vertices in left part which are not connected to $v$. Which vertices are not neighboring to this set? It is $v$ and all the vertices that their neighboring set it a subset of neighboring set of $v$ (and their sum is divisible by $k$). But value of $v$ is not divisible by $k$ so sum in complement of its neighboring set is not divisible by $k$ too.
|
[
"graphs",
"hashing",
"math",
"number theory"
] | 2,300
| null |
1322
|
D
|
Reality Show
|
A popular reality show is recruiting a new cast for the third season! $n$ candidates numbered from $1$ to $n$ have been interviewed. The candidate $i$ has aggressiveness level $l_i$, and recruiting this candidate will cost the show $s_i$ roubles.
The show host reviewes applications of all candidates from $i=1$ to $i=n$ by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate $i$ is strictly higher than that of any \textbf{already accepted} candidates, then the candidate $i$ will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.
The show makes revenue as follows. For each aggressiveness level $v$ a corresponding profitability value $c_v$ is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant $i$ enters the stage, events proceed as follows:
- The show makes $c_{l_i}$ roubles, where $l_i$ is initial aggressiveness level of the participant $i$.
- If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is:
- the defeated participant is hospitalized and leaves the show.
- aggressiveness level of the victorious participant is increased by one, and the show makes $c_t$ roubles, where $t$ is the new aggressiveness level.
- The fights continue until all participants on stage have distinct aggressiveness levels.
It is allowed to select an empty set of participants (to choose neither of the candidates).
The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total $s_i$). Help the host to make the show as profitable as possible.
|
First of all, we will notice that the order of entering doesn't affect the answer. Let's reverse the sequence. We will add people in the non-decreasing order. Let's use dynamic programming: $dp[i][k][cnt]$ is the answer if we processed first $i$ candidates with the maximum value less or equal $k$ and total number of people who will reach $l_j = k$ is $cnt \leq n$. How we should change values of $dp$ when we go from $k$ to $k + 1$? $dp[i][k + 1][cnt / 2] \leq dp[i][k][cnt] + (cnt / 2) \cdot c_{k + 1}$ But how $dp$ changes when we take $i$-th element? $dp[i + 1][a_i][cnt] \leq dp[i][a_i][cnt - 1] + s_i$ After adding $i$-th element we also should change $dp[i + 1][>a_i ]$. But every next lay will change less: $n + \left \lceil \frac{n}{2} \right \rceil + \left \lceil \frac{n}{4} \right \rceil + \left \lceil \frac{n}{8} \right \rceil + \ldots = O(n + m)$. It clear, that we can remove first parameter of $dp$ and finally get the asymptotics $O(n(n + m))$.
|
[
"bitmasks",
"dp"
] | 2,800
| null |
1322
|
E
|
Median Mountain Range
|
Berland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is $n$ mountain peaks, located on one straight line and numbered in order of $1$ to $n$. The height of the $i$-th mountain top is $a_i$.
"Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from $2$ to $n - 1$ its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal $b_i$, then after the alignment new heights $a_i$ are as follows: $a_1 = b_1$, $a_n = b_n$ and for all $i$ from $2$ to $n - 1$ $a_i = median(b_{i-1}, b_i, b_{i+1})$. The median of three integers is the second largest number among them. For example, $median(5,1,2) = 2$, and $median(4,2,4) = 4$.
Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of $c$ — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after $c$ alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!
|
Let's assume that $1 \le a_i \le 2$. We can notice that if for some $i$ $a_i = a_{i + 1}$, than on $i$-th and $(i+1)$-th positions numbers will stay the same forever. So the only changes will happen to segments of consecutive alternating $1$ and $2$. Now let's look what will happen to such segments after first alignment of mountain peaks. The beginning and end of segment will stay the same, and all intermediate number will change ($1$ will change to $2$ and $2$ will change to $1$). So the second number will be equal to first and pre last number will be equal to last. That means that lengths of all segments of consecutive alternating $1$ and $2$ will decrease by $2$. So the number of alignments equals to length of longest segment divided by $2$, and for each segment its first half will be equal to beginning of segment, and its second half will be equal to the end of segment. Now let's fix some number $x$ and create array $b$, where $b_i = 1$ if $a_i < x$ and $b_i = 2$ if $a_i \ge x$. It can be observed, that if we will make alignment with initial mountain heights and replace them with $1$ and $2$ the same way, we will get array $b$ after first alignment. So if we will get array $b$ after stabilization, we will know that on positions where $b_i = 1$ mountains will have height less than $x$, and on positions where $b_i = 2$ the mountain heights after stabilization will be grater or equal than $x$. So to get the number of alignments we will need to find the longest segment of consecutive alternating $1$ and $2$ for all possible $x$. Now we need to get the final heights. Let's assume that we know all positions where final heights will be grater than $x$. Let's create array $b$ the same way as described above. Using this array we can get positions where the mountain heights will be grater or equal than $x$ after stabilization. As we know positions where the heights will be grater than $x$, we can get positions where heights will be equal to $x$. So if we will decrease $x$ from maximum value to $1$, we can get the final heights of all mountains. To perform it quick enough, we can consider only those $x$, that equal to some of existing initial heights. Then we can decrease $x$ and in some set store all segments of consecutive alternating $1$ and $2$ in array $b$ for such $x$. When the $x$ is decreased, on some positions $1$ can change to $2$. The changes can happen only to the segments that have such positions. (The segments can be splited by this position, or this position can be merged with neighbouring segment(s)) So in total there will be $O(n)$ changes to segments, and we can perform all of them in $O(n \log n)$ time. Also we can store in set all positions, for which we do not know the final heights, we for each new segment we can find positions where $1$ will be in the end (it will be some segment of consecutive positions) and search free positions among them in the set. In total it will take $O(n \log n)$ time. There also exists solution in $O(n)$ time.
|
[
"data structures"
] | 3,300
| null |
1322
|
F
|
Assigning Fares
|
Mayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget, it was decided not to dig new tunnels but to use the existing underground network.
The tunnel system of the city M. consists of $n$ metro stations. The stations are connected with $n - 1$ bidirectional tunnels. Between every two stations $v$ and $u$ there is exactly one simple path. Each metro line the mayor wants to create is a simple path between stations $a_i$ and $b_i$. Metro lines can intersects freely, that is, they can share common stations or even common tunnels. However, it's not yet decided which of two directions each line will go. More precisely, between the stations $a_i$ and $b_i$ the trains will go either from $a_i$ to $b_i$, or from $b_i$ to $a_i$, but not simultaneously.
The city $M$ uses complicated faring rules. Each station is assigned with a positive integer $c_i$ — the fare zone of the station. The cost of travel from $v$ to $u$ is defined as $c_u - c_v$ roubles. Of course, such travel only allowed in case there is a metro line, the trains on which go from $v$ to $u$. Mayor doesn't want to have any travels with a negative cost, so it was decided to assign directions of metro lines and station fare zones in such a way, that fare zones are strictly increasing during any travel on any metro line.
Mayor wants firstly assign each station a fare zone and then choose a lines direction, such that all fare zones are increasing along any line. In connection with the approaching celebration of the day of the city, the mayor wants to assign fare zones so that the maximum $c_i$ will be as low as possible. Please help mayor to design a new assignment or determine if it's impossible to do. Please note that you only need to assign the fare zones optimally, you don't need to print lines' directions. This way, you solution will be considered correct if there will be a way to assign directions of every metro line, so that the fare zones will be strictly increasing along any movement of the trains.
|
Let's assume $c_v$ is the color of vertex v. So, we need to find a coloring of tree, where $c_v$ strictly increases along every path. First of all, if coloring exists, we can renumerate colors so that they will be in range [1, $n$]. Secondly, we can always revert our coloring, make $c_v \rightarrow k + 1 - c_v$. Also, let's do binary search to find $k$. So, now we want to check if it is possible to paint tree using $k$ colors. Every path can be on of two directions. If we determine direction for path #0, then we also automatically determine direction for every path which has common edge with path #0. So, we can get a components of paths - if we choose one path direction, we choose every other paths direction. We can notice, that if a single component is not bipartite, answer is -1. So, for every path, we know it's component and it's orientation inside the component. It can be calculated using subtree sum - for vertexes $a$ and $b$ we make +1 for $a$, +1 for $b$, and -2 for $lca(a,\,b)$. Let's make our tree rooted and then count dp on subtrees. $dp_v$ - minimal color of $v$, if all it's subtree is colored in a correct way and edge $v \rightarrow parent_v$ goes from lower to higher color. How to calculate dp? If we fix $parent_v \rightarrow v$ edge direction, for some edges $v \rightarrow to$ we know the orientation. It happens when they were in same component as $parent_v \rightarrow v$. For other components, we can or use $dp_{to}$ or $k + 1 - dp_{to}$ - depending on which direction of component we use. If we will try both variants and combine all the constraints, we will get two different segments $[l, r]$ and $[k + 1 - r, k + 1 - l]$, and $dp_v$ must be in one of them. It can be solved with scanline in $O(n \log n)$ time. Now we can notice that $r = k + 1 - dp_{to}$. Let's think of segments as about two left constraints: $l_1$ and $l_2$. We have two sets $L$ and $R$. We either put $l_1 \rightarrow L,\ l_2 \rightarrow R$ or $l_2 \rightarrow L,\ l_1 \rightarrow R$. So, we want these conditions to be done: $\begin{cases} \max(L) \le \min(k - R) \\ \max(L) \rightarrow \min \end{cases} \rightarrow \begin{cases} \max(L) + \max(R) \le k \\ \max(L) \rightarrow \min \end{cases}$ If we fix what is more - $\max(R)$ or $\max(L)$, we get fixed distribuition between $L$ and $R$ - max of $l_1$ and $l_2$ goes to max of two sets. Then we just need to check conditions and use best of variants. Solution will have complexity $O(n \log n)$.
|
[
"dp",
"trees"
] | 3,500
| null |
1323
|
A
|
Even Subset Sum Problem
|
You are given an array $a$ consisting of $n$ positive integers. Find a \textbf{non-empty} subset of its elements such that their sum is \textbf{even} (i.e. divisible by $2$) or determine that there is no such subset.
Both the given array and required subset may contain equal values.
|
If there is an even element in array there is an answer consisting of only it. Otherwise if there is at least two odd elements in array there is an answer consisting of this two elements. Otherwise array is only one odd element and there is no answer.
|
[
"brute force",
"dp",
"greedy",
"implementation"
] | 800
| null |
1323
|
B
|
Count Subrectangles
|
You are given an array $a$ of length $n$ and array $b$ of length $m$ both consisting of only integers $0$ and $1$. Consider a matrix $c$ of size $n \times m$ formed by following rule: $c_{i, j} = a_i \cdot b_j$ (i.e. $a_i$ multiplied by $b_j$). It's easy to see that $c$ consists of only zeroes and ones too.
How many subrectangles of size (area) $k$ consisting only of ones are there in $c$?
A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers $x_1, x_2, y_1, y_2$ ($1 \le x_1 \le x_2 \le n$, $1 \le y_1 \le y_2 \le m$) a subrectangle $c[x_1 \dots x_2][y_1 \dots y_2]$ is an intersection of the rows $x_1, x_1+1, x_1+2, \dots, x_2$ and the columns $y_1, y_1+1, y_1+2, \dots, y_2$.
The size (area) of a subrectangle is the total number of cells in it.
|
Rectangle $[x1; x2][y1; y2]$ consists of only ones iff subsegment $[x1; x2]$ consists of only ones in $a$ and subsegment $[y1; y2]$ consists of only ones in $b$. Let's iterate over divisors of $k$. Let the current divisor be $p$ (i.e. $k = p \cdot q$), so we are interested in number of subsegments consisting of ones of length $p$ in $a$ and number of subsegments consisting of ones of length $q$ in $b$. It's possible to precalculate number of segments consisting of ones in $a$ and $b$ of each length. Let's find all maximal subsegments consisting of ones in $a$ and $b$. Consider subsegment of length $l$. It adds $l - s + 1$ for amount of subsegments of length $s$.
|
[
"binary search",
"greedy",
"implementation"
] | 1,500
|
#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using namespace std;
vector<ll> gao(vector<int> a) {
int n = a.size();
vector<ll> res(n + 1);
int i = 0;
while (i < n) {
if (a[i] == 0) {
i++;
continue;
}
int j = i;
while (j < n && a[j] == 1) {
j++;
}
for (int len = 1; len <= j - i; len++) {
res[len] += j - i - len + 1;
}
i = j;
}
return res;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, m;
ll k;
cin >> n >> m >> k;
vector<int> a(n);
vector<int> b(m);
for (int& x : a) {
cin >> x;
}
for (int& x : b) {
cin >> x;
}
ll ans = 0;
auto ga = gao(a);
auto gb = gao(b);
for (int i = 1; i < ga.size(); i++) {
if (k % i == 0 && k / i <= m) {
ans += ga[i] * gb[k / i];
}
}
cout << ans << "\n";
return 0;
}
|
1324
|
A
|
Yet Another Tetris Problem
|
You are given some Tetris field consisting of $n$ columns. The initial height of the $i$-th column of the field is $a_i$ blocks. On top of these columns you can place \textbf{only} figures of size $2 \times 1$ (i.e. the height of this figure is $2$ blocks and the width of this figure is $1$ block). Note that you \textbf{cannot} rotate these figures.
Your task is to say if you can clear the whole field by placing such figures.
More formally, the problem can be described like this:
The following process occurs while \textbf{at least one $a_i$ is greater than $0$}:
- You place one figure $2 \times 1$ (choose some $i$ from $1$ to $n$ and replace $a_i$ with $a_i + 2$);
- then, while all $a_i$ are greater than zero, replace each $a_i$ with $a_i - 1$.
And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.
You have to answer $t$ independent test cases.
|
The answer is "YES" only if all $a_i$ have the same parity (i.e. all $a_i$ are odd or all $a_i$ are even). That's because placing the block doesn't change the parity of the element and the $-1$ operation changes the parity of all elements in the array.
|
[
"implementation",
"number theory"
] | 900
|
for i in range(int(input())):
n = int(input())
cnto = sum(list(map(lambda x: int(x) % 2, input().split())))
print('YES' if cnto == 0 or cnto == n else 'NO')
|
1324
|
B
|
Yet Another Palindrome Problem
|
You are given an array $a$ consisting of $n$ integers.
Your task is to determine if $a$ has some \textbf{subsequence} of length at least $3$ that is a palindrome.
Recall that an array $b$ is called a \textbf{subsequence} of the array $a$ if $b$ can be obtained by removing some (possibly, zero) elements from $a$ (not necessarily consecutive) without changing the order of remaining elements. For example, $[2]$, $[1, 2, 1, 3]$ and $[2, 3]$ are subsequences of $[1, 2, 1, 3]$, but $[1, 1, 2]$ and $[4]$ are not.
Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $a$ of length $n$ is the palindrome if $a_i = a_{n - i - 1}$ for all $i$ from $1$ to $n$. For example, arrays $[1234]$, $[1, 2, 1]$, $[1, 3, 2, 2, 3, 1]$ and $[10, 100, 10]$ are palindromes, but arrays $[1, 2]$ and $[1, 2, 3, 1]$ are not.
You have to answer $t$ independent test cases.
|
The first observation is that we can always try to find the palindrome of length $3$ (otherwise, we can remove some characters from the middle until its length becomes $3$). The second observation is that the palindrome of length $3$ is two equal characters and some other (maybe, the same) character between them. Now there are two ways: find the pair of equal non-adjacent characters in $O(n^2)$ or do it in $O(n)$ (for each character we only need to consider its left and right occurrences).
|
[
"brute force",
"strings"
] | 1,100
|
for i in range(int(input())):
n = int(input())
s = list(map(int, input().split()))
ok = False
for i in range(n):
for j in range(i + 2, n):
if s[i] == s[j]: ok = True
print('YES' if ok else 'NO')
|
1324
|
C
|
Frog Jumps
|
There is a frog staying to the left of the string $s = s_1 s_2 \ldots s_n$ consisting of $n$ characters (to be more precise, the frog initially stays at the cell $0$). Each character of $s$ is either 'L' or 'R'. It means that if the frog is staying at the $i$-th cell and the $i$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $i$-th cell and the $i$-th character is 'R', the frog can jump only to the right. \textbf{The frog can jump only to the right from the cell $0$}.
\textbf{Note that the frog can jump into the same cell twice and can perform as many jumps as it needs}.
The frog wants to reach the $n+1$-th cell. The frog chooses some \textbf{positive integer} value $d$ \textbf{before the first jump} (and cannot change it later) and jumps by no more than $d$ cells at once. I.e. if the $i$-th character is 'L' then the frog can jump to any cell in a range $[max(0, i - d); i - 1]$, and if the $i$-th character is 'R' then the frog can jump to any cell in a range $[i + 1; min(n + 1; i + d)]$.
The frog doesn't want to jump far, so your task is to find the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it can jump by no more than $d$ cells at once. \textbf{It is guaranteed that it is always possible to reach $n+1$ from $0$}.
You have to answer $t$ independent test cases.
|
The only observation we need is that we don't need to jump left at all. This only decreases our position so we have less freedom after the jump to the left. Then, to minimize $d$, we only need to jump between the closest 'R' cells. So, if we build the array $b = [0, r_1, r_2, \dots, r_k, n + 1]$, where $r_i$ is the position of the $i$-th 'R' cell from left to right ($1$-indexed), then the answer is $\max\limits_{i=0}^{k} b_{i + 1} - b_i$. Time complexity: $O(n)$.
|
[
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | 1,100
|
#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--) {
string s;
cin >> s;
vector<int> pos;
pos.push_back(0);
for (int i = 0; i < int(s.size()); ++i) {
if (s[i] == 'R') pos.push_back(i + 1);
}
pos.push_back(s.size() + 1);
int ans = 0;
for (int i = 0; i < int(pos.size()) - 1; ++i) {
ans = max(ans, pos[i + 1] - pos[i]);
}
cout << ans << endl;
}
return 0;
}
|
1324
|
D
|
Pair of Topics
|
The next lecture in a high school requires two topics to be discussed. The $i$-th topic is interesting by $a_i$ units for the teacher and by $b_i$ units for the students.
The pair of topics $i$ and $j$ ($i < j$) is called \textbf{good} if $a_i + a_j > b_i + b_j$ (i.e. it is more interesting for the teacher).
Your task is to find the number of \textbf{good} pairs of topics.
|
Let's rewrite the inequality from $a_i + a_j > b_i + b_j$ to $(a_i - b_i) + (a_j - b_j) > 0$. This looks much simpler. Let's build the array $c$ where $c_i = a_i - b_i$ and sort this array. Now our problem is to find the number of pairs $i < j$ such that $c_i + c_j > 0$. Let's iterate over all elements of $c$ from left to right. For simplicity, we consider only "greater" summands. Because our sum ($c_i + c_j$) must be greater than $0$, then at least one of these summands will be positive. So, if $c_i \le 0$, just skip it. Now $c_i > 0$ and we need to calculate the number of such $j$ that $c_i + c_j > 0$ and $j < i$. It means that each $c_j \ge -c_i + 1$ (for some $j < i$) will be okay. Such leftmost position $j$ can be found with std::lower_bound or binary search. Then add the value $i-j$ to the answer and consider the next element. Time complexity: $O(n \log n)$.
|
[
"binary search",
"data structures",
"sortings",
"two pointers"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n), b(n);
for (auto &it : a) cin >> it;
for (auto &it : b) cin >> it;
vector<int> c(n);
for (int i = 0; i < n; ++i) {
c[i] = a[i] - b[i];
}
sort(c.begin(), c.end());
long long ans = 0;
for (int i = 0; i < n; ++i) {
if (c[i] <= 0) continue;
int pos = lower_bound(c.begin(), c.end(), -c[i] + 1) - c.begin();
ans += i - pos;
}
cout << ans << endl;
return 0;
}
|
1324
|
E
|
Sleeping Schedule
|
Vova had a pretty weird sleeping schedule. There are $h$ hours in a day. Vova will sleep exactly $n$ times. The $i$-th time he will sleep exactly after $a_i$ hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is $0$). Each time Vova sleeps \textbf{exactly one day} (in other words, $h$ hours).
Vova thinks that the $i$-th sleeping time is \textbf{good} if he starts to sleep between hours $l$ and $r$ inclusive.
Vova can control himself and before the $i$-th time can choose between two options: go to sleep after $a_i$ hours or after $a_i - 1$ hours.
Your task is to say the maximum number of \textbf{good} sleeping times Vova can obtain if he acts optimally.
|
This is a very standard dynamic programming problem. Let $dp_{i, j}$ be the maximum number of good sleeping times if Vova had a sleep $i$ times already and the number of times he goes to sleep earlier by one hour is exactly $j$. Then the value $\max\limits_{j=0}^{n} dp_{n, j}$ will be the answer. Initially, all $dp_{i, j} = -\infty$ and $dp_{0, 0} = 0$. What about transitions? Let the current state of the dynamic programming be $dp_{i, j}$ and $s = \sum\limits_{k=0}^{i} a_k$. Then we can don't go to sleep earlier and make the first transition: $dp_{i + 1, j} = max(dp_{i + 1, j}, dp_{i, j} + |(s - j) \% h \in [l; r]|)$. The sign $\%$ is modulo operation and the notation $|f|$ is the boolean result of the expression $f$ ($1$ if $f$ is true and $0$ otherwise). And the second transition if we go to sleep earlier: $dp_{i + 1, j + 1} = max(dp_{i + 1, j + 1}, dp_{i, j} + |(s - j - 1) \% h \in [l; r]|)$. Don't forget to don't make transitions from unreachable states. Time complexity: $O(n^2)$.
|
[
"dp",
"implementation"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
bool in(int x, int l, int r) {
return l <= x && x <= r;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, h, l, r;
cin >> n >> h >> l >> r;
vector<int> a(n);
for (auto &it : a) cin >> it;
vector<vector<int>> dp(n + 1, vector<int>(n + 1, INT_MIN));
dp[0][0] = 0;
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += a[i];
for (int j = 0; j <= n; ++j) {
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + in((sum - j) % h, l, r));
if (j < n) dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + in((sum - j - 1) % h, l, r));
}
}
cout << *max_element(dp[n].begin(), dp[n].end()) << endl;
return 0;
}
|
1324
|
F
|
Maximum White Subtree
|
You are given a tree consisting of $n$ vertices. A tree is a connected undirected graph with $n-1$ edges. Each vertex $v$ of this tree has a color assigned to it ($a_v = 1$ if the vertex $v$ is white and $0$ if the vertex $v$ is black).
You have to solve the following problem for each vertex $v$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that \textbf{contains} the vertex $v$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $cnt_w$ white vertices and $cnt_b$ black vertices, you have to maximize $cnt_w - cnt_b$.
|
This problem is about the "rerooting" technique. Firstly, let's calculate the answer for some fixed root. How can we do this? Let $dp_v$ be the maximum possible difference between the number of white and black vertices in some subtree of $v$ (yes, the subtree of the rooted tree, i.e. $v$ and all its direct and indirect children) that contains the vertex $v$. We can calculate this dynamic programming by simple dfs, for the vertex $v$ it will look like this: $dp_v = a_v + \sum\limits_{to \in children(v)} max(0, dp_{to})$. Okay, we can store the answer for the root somewhere. What's next? Let's try to change the root from the vertex $v$ to some adjacent to it vertex $to$. Which states of dynamic programming will change? Only $dp_v$ and $dp_{to}$. Firstly, we need to "remove" the child $to$ from the subtree of the vertex $v$: $dp_v = dp_v - max(0, dp_{to})$. Then we need to "attach" the vertex $v$ and make it a child of the vertex $to$: $dp_{to} = dp_{to} + max(0, dp_v)$. Then we need to run this process recursively from $to$ (store the answer, reroot the tree and so on) and when it ends we need to "rollback" our changes. Now $v$ is the root again and we can try the next child of $v$ as the root. Time complexity: $O(n)$.
|
[
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
vector<int> a;
vector<int> dp;
vector<int> ans;
vector<vector<int>> g;
void dfs(int v, int p = -1) {
dp[v] = a[v];
for (auto to : g[v]) {
if (to == p) continue;
dfs(to, v);
dp[v] += max(dp[to], 0);
}
}
void dfs2(int v, int p = -1) {
ans[v] = dp[v];
for (auto to : g[v]) {
if (to == p) continue;
dp[v] -= max(0, dp[to]);
dp[to] += max(0, dp[v]);
dfs2(to, v);
dp[to] -= max(0, dp[v]);
dp[v] += max(0, dp[to]);
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
a = dp = ans = vector<int>(n);
g = vector<vector<int>>(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
if (a[i] == 0) a[i] = -1;
}
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);
}
dfs(0);
dfs2(0);
for (auto it : ans) cout << it << " ";
cout << endl;
return 0;
}
|
1325
|
A
|
EhAb AnD gCd
|
You are given a positive integer $x$. Find \textbf{any} such $2$ positive integers $a$ and $b$ such that $GCD(a,b)+LCM(a,b)=x$.
As a reminder, $GCD(a,b)$ is the greatest integer that divides both $a$ and $b$. Similarly, $LCM(a,b)$ is the smallest integer such that both $a$ and $b$ divide it.
It's guaranteed that the solution always exists. If there are several such pairs $(a, b)$, you can output any of them.
|
$a=1$ and $b=x-1$ always work.
|
[
"constructive algorithms",
"greedy",
"number theory"
] | 800
|
"#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int t;\n scanf(\"%d\",&t);\n while (t--)\n {\n \tint x;\n \tscanf(\"%d\",&x);\n \tprintf(\"1 %d\\n\",x-1);\n }\n}"
|
1325
|
B
|
CopyCopyCopyCopyCopy
|
Ehab has an array $a$ of length $n$. He has just enough free time to make a new array consisting of $n$ copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.
|
Let the number of distinct elements in $a$ be called $d$. Clearly, the answer is limited by $d$. Now, you can construct your subsequence as follows: take the smallest element from the first copy, the second smallest element from the second copy, and so on. Since there are enough copies to take every element, the answer is $d$.
|
[
"greedy",
"implementation"
] | 800
|
"#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n int t;\n scanf(\"%d\",&t);\n while (t--)\n {\n \tint n;\n \tscanf(\"%d\",&n);\n \tset<int> s;\n \twhile (n--)\n \t{\n \t\tint a;\n \t\tscanf(\"%d\",&a);\n \t\ts.insert(a);\n \t}\n \tprintf(\"%d\\n\",s.size());\n }\n}"
|
1325
|
C
|
Ehab and Path-etic MEXs
|
You are given a tree consisting of $n$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:
- Every label is an integer between $0$ and $n-2$ inclusive.
- All the written labels are distinct.
- The largest value among $MEX(u,v)$ over all pairs of nodes $(u,v)$ is as small as possible.
Here, $MEX(u,v)$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $u$ to node $v$.
|
Notice that there will be a path that passes through the edge labeled $0$ and the edge labeled $1$ no matter how you label the edges, so there's always a path with $MEX$ $2$ or more. If any node has degree 3 or more, you can distribute the labels $0$, $1$, and $2$ to edges incident to this node and distribute the rest of the labels arbitrarily. Otherwise, the tree is a bamboo, and it doesn't actually matter how you label the edges, since there will be a path with $MEX$ $n-1$ anyway.
|
[
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | 1,500
|
"#include <bits/stdc++.h>\nusing namespace std;\nvector<int> v[100005];\nint ans[100005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=1;i<n;i++)\n\t{\n\t\tint a,b;\n\t\tscanf(\"%d%d\",&a,&b);\n\t\tv[a].push_back(i);\n\t\tv[b].push_back(i);\n\t\tans[i]=-1;\n\t}\n\tpair<int,int> mx(0,0);\n\tfor (int i=1;i<=n;i++)\n\tmx=max(mx,make_pair((int)v[i].size(),i));\n\tint cur=0;\n\tfor (int i:v[mx.second])\n\tans[i]=cur++;\n\tfor (int i=1;i<n;i++)\n\t{\n\t\tif (ans[i]==-1)\n\t\tans[i]=cur++;\n\t\tprintf(\"%d\\n\",ans[i]);\n\t}\n}"
|
1325
|
D
|
Ehab the Xorcist
|
Given 2 integers $u$ and $v$, find the shortest array such that bitwise-xor of its elements is $u$, and the sum of its elements is $v$.
|
First, let's look at some special cases. If $u>v$ or $u$ and $v$ have different parities, there's no array. If $u=v=0$, the answer is an empty array. If $u=v \neq 0$, the answer is $[u]$. Now, the length is at least 2. Let $x=\frac{v-u}{2}$. The array $[u,x,x]$ satisfies the conditions, so the length is at most 3. We just need to figure out whether there's a pair of number $a$ and $b$. Such that $a \oplus b=u$ and $a+b=v$. Notice that $a+b=a \oplus b+2*(a$&$b)$, so we know that $a$&$b=\frac{v-u}{2}=x$ (surprise surprise.) The benefit of getting rid of $a+b$ and looking at $a$&$b$ instead is that we can look at $a$ and $b$ bit by bit. If $x$ has a one in some bit, $a$ and $b$ must both have ones, so $a \oplus b=u$ must have a 0. If $x$ has a zero, there are absolutely no limitation on $u$. So, if there's a bit where both $x$ and $u$ have a one, that is to say if $x$&$u\neq0$, you can't find such $a$ and $b$, and the length will be 3. Otherwise, $x$&$u=0$ which means $x \oplus u=x+u$, so the array $[u+x,x]$ works. Can you see how this array was constructed? We took $[u,x,x]$ which more obviously works and merged the first 2 elements, benefiting from the fact that $u$&$x=0$.
|
[
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | 1,700
|
"#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tlong long u,v;\n\tscanf(\"%I64d%I64d\",&u,&v);\n\tif (u%2!=v%2 || u>v)\n\t{\n\t\tprintf(\"-1\");\n\t\treturn 0;\n\t}\n\tif (u==v)\n\t{\n\t\tif (!u)\n\t\tprintf(\"0\");\n\t\telse\n\t\tprintf(\"1\\n%I64d\",u);\n\t\treturn 0;\n\t}\n\tlong long x=(v-u)/2;\n\tif (u&x)\n\tprintf(\"3\\n%I64d %I64d %I64d\",u,x,x);\n\telse\n\tprintf(\"2\\n%I64d %I64d\",(u^x),x);\n}"
|
1325
|
E
|
Ehab's REAL Number Theory Problem
|
You are given an array $a$ of length $n$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.
|
Notice that for each element in the array, if some perfect square divides it, you can divide it by that perfect square, and the problem won't change. Let's define normalizing a number as dividing it by perfect squares until it doesn't contain any. Notice than any number that has 3 different prime divisors has at least 8 divisors, so after normalizing any element in the array, it will be $1$, $p$, or $p*q$ for some primes $p$ and $q$. Let's create a graph where the vertices are the prime numbers (and $1$,) and the edges are the elements of the array. For each element, we'll connect $p$ and $q$ (or $p$ and $1$ if it's a prime after normalizing, or $1$ with $1$ if it's $1$ after normalizing.) What's the significance of this graph? Well, if you take any walk from node $p$ to node $q$, multiply the elements on the edges you took, and normalize, the product you get will be $p*q$! That's because every node in the path will be visited an even number of times, except $p$ and $q$. So the shortest subsequence whose product is a perfect square is just the shortest cycle in this graph! The shortest cycle in an arbitrary graph takes $O(n^2)$ to compute: you take every node as a source and calculate the bfs tree, then you look at the edges the go back to the root to close the cycle. That only finds the shortest cycle if the bfs source is contained in one. The graph in this problem has a special condition: you can't connect 2 nodes with indices greater than $sqrt(maxAi)$. That's because their product would be greater than $maxAi$. So that means ANY walk in this graph has a node with index $\le\sqrt{maxAi}$. You can only try these nodes as sources for your bfs.
|
[
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | 2,600
|
"#include <bits/stdc++.h>\nusing namespace std;\n#define MX 1000000\nint lp[MX+5],dist[MX+5];\nvector<int> d[MX+5],v[MX+5],pr;\nvector<vector<int> > e;\nint main()\n{\n pr.push_back(1);\n\tfor (int i=2;i<=MX;i++)\n\t{\n\t\tif (!lp[i])\n\t\t{\n\t\t pr.push_back(i);\n\t\t\tfor (int j=i;j<=MX;j+=i)\n\t\t\tlp[j]=i;\n\t\t}\n\t\td[i]=d[i/lp[i]];\n\t\tauto it=find(d[i].begin(),d[i].end(),lp[i]);\n\t\tif (it!=d[i].end())\n\t\td[i].erase(it);\n\t\telse\n\t\td[i].push_back(lp[i]);\n\t}\n\tint n,ans=1e9;\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tint a;\n\t\tscanf(\"%d\",&a);\n\t\tif (d[a].empty())\n\t\t{\n\t\t\tprintf(\"1\");\n\t\t\treturn 0;\n\t\t}\n\t\tif (d[a].size()==1)\n\t\td[a].push_back(1);\n\t\te.push_back({d[a][0],d[a][1]});\n\t\tv[d[a][0]].push_back(i);\n\t\tv[d[a][1]].push_back(i);\n\t}\n\tfor (int i:pr)\n\t{\n\t if (i*i>MX)\n\t break;\n\t for (int j:pr)\n\t dist[j]=0;\n\t\tqueue<pair<int,int> > q;\n\t\tfor (int j:v[i])\n\t\t{\n\t\t\tq.push({j,(e[j][0]==i)});\n\t\t\tdist[e[j][0]^e[j][1]^i]=1;\n\t\t}\n\t\twhile (!q.empty())\n\t\t{\n\t\t\tauto p=q.front();\n\t\t\tq.pop();\n\t\t\tint node=e[p.first][p.second];\n\t\t\tfor (int u:v[node])\n\t\t\t{\n\t\t\t\tif (u!=p.first)\n\t\t\t\t{\n\t\t\t\t\tpair<int,int> np(u,(e[u][0]==node));\n\t\t\t\t\tint nnode=e[np.first][np.second];\n\t\t\t\t\tif (!dist[nnode] && nnode!=i)\n\t\t\t\t\t{\n\t\t\t\t\t\tq.push(np);\n\t\t\t\t\t\tdist[nnode]=dist[node]+1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\tans=min(ans,dist[node]+dist[nnode]+1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (ans==1e9)\n\tans=-1;\n\tprintf(\"%d\",ans);\n}"
|
1325
|
F
|
Ehab's Last Theorem
|
It's the year 5555. You have a graph, and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.
Given a connected graph with $n$ vertices, you can choose to either:
- find an independent set that has \textbf{exactly} $\lceil\sqrt{n}\rceil$ vertices.
- find a \textbf{simple} cycle of length \textbf{at least} $\lceil\sqrt{n}\rceil$.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.
|
Let $sq$ denote $\lceil\sqrt{n}\rceil$. If you're not familiar with back-edges, I recommend reading this first. Let's take the DFS tree of our graph. Assume you're currently in node $u$ in the DFS. If $u$ has $sq-1$ or more back-edges, look at the one that connects $u$ to its furthest ancestor. It forms a cycle of length at least $sq$. If $u$ doesn't have that many back-edges, you can add it to the independent set (if none of its neighbors was added.) That way, if you don't find a cycle, every node only blocks at most $sq-1$ other nodes, the ones connected to it by a back-edge, so you'll find an independent set! There's a pretty obvious greedy algorithm for finding large independent sets: take the node with the minimal degree, add it to the independent set, remove it and all its neighbors from the graph, and repeat. If at every step the node with the minimal degree has degree $<sq-1$, that algorithm solves the first problem. Otherwise, there's a step where EVERY node has degree at least $sq-1$. For graphs where every node has degree at least $d$, you can always find a cycle with length $d+1$. To do that, we'll first try to find a long path then close a cycle. Take an arbitrary node as a starting point, and keep trying to extend your path. If one of this node's neighbors is not already in the path, extend that path with it and repeat. Otherwise, all of the last node's $d$ neighbors are on the path. Take the edge to the furthest and you'll form a cycle of length at least $d+1$!
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | 2,500
|
"#include <bits/stdc++.h>\nusing namespace std;\nset<pair<int,int> > s;\nvector<int> v[100005];\nbool del[100005];\nint deg[100005],occ[100005];\nvoid remove(int node)\n{\n if (del[node])\n return;\n\ts.erase({deg[node],node});\n\tdel[node]=1;\n\tfor (int u:v[node])\n\t{\n\t\tif (!del[u])\n\t\t{\n\t\t\ts.erase({deg[u],u});\n\t\t\tdeg[u]--;\n\t\t\ts.insert({deg[u],u});\n\t\t}\n\t}\n}\nint main()\n{\n\tint n,m,sq=1;\n\tscanf(\"%d%d\",&n,&m);\n\twhile (sq*sq<n)\n\tsq++;\n\twhile (m--)\n\t{\n\t\tint a,b;\n\t\tscanf(\"%d%d\",&a,&b);\n\t\tv[a].push_back(b);\n\t\tv[b].push_back(a);\n\t\tdeg[a]++;\n\t\tdeg[b]++;\n\t}\n\tfor (int i=1;i<=n;i++)\n\ts.insert({deg[i],i});\n\tvector<int> ans;\n\twhile (!s.empty())\n\t{\n\t\tauto p=*s.begin();\n\t\ts.erase(s.begin());\n\t\tif (p.first+1>=sq)\n\t\t{\n\t\t\tprintf(\"2\\n\");\n\t\t\tvector<int> d({p.second});\n\t\t\tocc[p.second]=1;\n\t\t\twhile (1)\n\t\t\t{\n\t\t\t\tpair<int,int> nex(1e9,0);\n\t\t\t\tfor (int u:v[d.back()])\n\t\t\t\t{\n\t\t\t\t\tif (!del[u])\n\t\t\t\t\tnex=min(nex,make_pair(occ[u],u));\n\t\t\t\t}\n\t\t\t\tif (nex.first)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"%d\\n\",(int)d.size()-nex.first+1);\n\t\t\t\t\tfor (int i=nex.first-1;i<d.size();i++)\n\t\t\t\t\tprintf(\"%d \",d[i]);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\td.push_back(nex.second);\n\t\t\t\tocc[nex.second]=d.size();\n\t\t\t}\n\t\t}\n\t\tans.push_back(p.second);\n\t\tremove(p.second);\n\t\tfor (int u:v[p.second])\n\t\tremove(u);\n\t}\n\tprintf(\"1\\n\");\n\tfor (int i=0;i<sq;i++)\n\tprintf(\"%d \",ans[i]);\n}"
|
1326
|
A
|
Bad Ugly Numbers
|
You are given a integer $n$ ($n > 0$). Find \textbf{any} integer $s$ which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of $s$:
- $s > 0$,
- $s$ consists of $n$ digits,
- no digit in $s$ equals $0$,
- $s$ is not divisible by any of it's digits.
|
If $n = 1$, no solution exists. Otherwise, if $n \geq 2$, the number $\overline{2 3 3 \ldots 3}$ ($n$ digits) satisfies all conditions, because it is not divisible by $2$ and $3$.
|
[
"constructive algorithms",
"number theory"
] | 1,000
| null |
1326
|
B
|
Maximums
|
Alicia has an array, $a_1, a_2, \ldots, a_n$, of non-negative integers. For each $1 \leq i \leq n$, she has found a non-negative integer $x_i = max(0, a_1, \ldots, a_{i-1})$. Note that for $i=1$, $x_i = 0$.
For example, if Alicia had the array $a = \{0, 1, 2, 0, 3\}$, then $x = \{0, 0, 1, 2, 2\}$.
Then, she calculated an array, $b_1, b_2, \ldots, b_n$: $b_i = a_i - x_i$.
For example, if Alicia had the array $a = \{0, 1, 2, 0, 3\}$, $b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}$.
Alicia gives you the values $b_1, b_2, \ldots, b_n$ and asks you to restore the values $a_1, a_2, \ldots, a_n$. Can you help her solve the problem?
|
Let's restore $a_1, a_2, \ldots, a_n$ from left to right. $a_1 = b_1$. For $i>1$, $x_i = \max({a_1, \ldots, a_{i-1}})$, so we can maintain the maximum of previous elements and get the value of $x_i$. Using this value, we can restore $a_i$ as $b_i + x_i$.
|
[
"implementation",
"math"
] | 900
|
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <unordered_set>\n#include <iomanip>\n#include <bitset>\n#include <sstream>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef iq\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef iq\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n;\n cin >> n;\n vector <int> a(n);\n int x = 0;\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n a[i] += x;\n x = max(x, a[i]);\n cout << a[i] << ' ';\n }\n}"
|
1326
|
C
|
Permutation Partitions
|
You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$ and an integer $k$, such that $1 \leq k \leq n$. A permutation means that every number from $1$ to $n$ is contained in $p$ exactly once.
Let's consider all partitions of this permutation into $k$ disjoint segments. Formally, a partition is a set of segments $\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$, such that:
- $1 \leq l_i \leq r_i \leq n$ for all $1 \leq i \leq k$;
- For all $1 \leq j \leq n$ there exists \textbf{exactly one} segment $[l_i, r_i]$, such that $l_i \leq j \leq r_i$.
Two partitions are different if there exists a segment that lies in one partition but not the other.
Let's calculate the partition value, defined as $\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$, for all possible partitions of the permutation into $k$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $998\,244\,353$.
|
Note that the maximum possible partition value is equal to $(n - k + 1) + \ldots + (n - 1) + n$. Let's define $a_1, a_2, \ldots, a_k$ as positions of the numbers $(n-k+1), \ldots, n$ in the increasing order ($a_1 < a_2 < \ldots < a_k$). The number of partitions with the maximum possible value is equal to $\prod\limits_{i=1}^{k-1} {(a_{i+1}-a_i)}$. This is true because if we have the maximum possible value, each of the segments in a partition should contain exactly one of the values $(n-k+1), \ldots, n$, and thus, one of the positions $a_1, a_2, \ldots, a_k$. So, between each pair of neighboring positions, we should choose exactly one of the borders of the segments in the partition. There are $(a_{i+1}-a_i)$ ways to do this.
|
[
"combinatorics",
"greedy",
"math"
] | 1,300
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint n, k, a;\n\nint main()\n{\n ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n cin >> n >> k;\n int p = -1;\n int ans = 1;\n long long sum = 0;\n for (int i = 0; i < n; i++)\n {\n cin >> a;\n if (a >= n - k + 1)\n {\n if (p != -1)\n ans = 1LL * ans * (i - p) % MOD;\n sum += a;\n p = i;\n }\n }\n cout << sum << \" \" << ans << \"\\n\";\n return 0;\n}"
|
1326
|
D2
|
Prefix-Suffix Palindrome (Hard version)
|
\textbf{This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.}
You are given a string $s$, consisting of lowercase English letters. Find the longest string, $t$, which satisfies the following conditions:
- The length of $t$ does not exceed the length of $s$.
- $t$ is a palindrome.
- There exists two strings $a$ and $b$ (possibly empty), such that $t = a + b$ ( "$+$" represents concatenation), and $a$ is prefix of $s$ while $b$ is suffix of $s$.
|
Each possible string $t$ can be modeled as $s[1..l] + s[(n-r+1)..n]$ for some numbers $l,r$ such that $0 \leq l, r$ and $l + r \leq n$. Let's find the maximum integer $0 \leq k \leq \lfloor \frac{n}{2} \rfloor$ such that $s_1 = s_n, s_2 = s_{n-1}, \ldots, s_k = s_{n-k+1}$. In some optimal solution, where $t$ is as long as possible, $\min{(l, r)} = k$. This is because if $\min{(l, r)} < k$, we can increase $l$ or $r$ by $1$ and decrease the other variable by $1$ (if needed), and the string will be still a palindrome. So if we know that $\min{(l, r)} = k$, we just need to find the longest palindrome $w$ that is a prefix or suffix of the string $s[(k+1)..(n-k)]$. After that, the answer will be $s[1..k] + w + s[(n-k+1)..n]$. In order to find the longest palindrome which is a prefix of some string, $a$, let's find $p$ from the prefix function of the string $a +$ '#' $+ \overline{a}$, where $\overline{a}$ represents the reverse of $a$. The string $a[1..p]$ will be the longest palindrome which is a prefix of $a$. After that, we can repeat this process for $\overline{a}$ to find the longest palindrome which is a suffix of the string. Time complexity: $O(|s|)$.
|
[
"binary search",
"greedy",
"hashing",
"string suffix structures",
"strings"
] | 1,800
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = (int)(2e6 + 239);\n\nint pref[M], c;\n\nstring solve_palindrome(const string& s)\n{\n string a = s;\n reverse(a.begin(), a.end());\n a = s + \"#\" + a;\n c = 0;\n for (int i = 1; i < (int)a.size(); i++)\n {\n while (c != 0 && a[c] != a[i])\n c = pref[c - 1];\n if (a[c] == a[i])\n c++;\n pref[i] = c;\n }\n return s.substr(0, c);\n}\n\nvoid solve()\n{\n string t;\n cin >> t;\n int l = 0;\n while (l < (int)t.size() - l - 1)\n {\n if (t[l] != t[(int)t.size() - l - 1])\n break;\n l++;\n }\n if (l > 0)\n cout << t.substr(0, l);\n if ((int)t.size() > 2 * l)\n {\n string s = t.substr(l, (int)t.size() - 2 * l);\n string a = solve_palindrome(s);\n reverse(s.begin(), s.end());\n string b = solve_palindrome(s);\n if ((int)a.size() < (int)b.size())\n swap(a, b);\n cout << a;\n }\n if (l > 0)\n cout << t.substr((int)t.size() - l, l);\n cout << \"\\n\";\n}\n\nint main()\n{\n ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n int t;\n cin >> t;\n while (t--)\n solve();\n return 0;\n}"
|
1326
|
E
|
Bombs
|
You are given a permutation, $p_1, p_2, \ldots, p_n$.
Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.
For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, $A$.
For each $i$ from $1$ to $n$:
- Add $p_i$ to $A$.
- If the $i$-th position contains a bomb, remove the largest element in $A$.
After the process is completed, $A$ will be non-empty. The cost of the configuration of bombs equals the largest element in $A$.
You are given another permutation, $q_1, q_2, \ldots, q_n$.
For each $1 \leq i \leq n$, find the cost of a configuration of bombs such that there exists a bomb in positions $q_1, q_2, \ldots, q_{i-1}$.
For example, for $i=1$, you need to find the cost of a configuration without bombs, and for $i=n$, you need to find the cost of a configuration with bombs in positions $q_1, q_2, \ldots, q_{n-1}$.
|
Let's come up with some criteria that answer is $< x$. We claim that the answer is $< x$ if: There is at least one bomb after the rightmost value $\geq x$. There are at least two bombs after the next rightmost value $\geq x$.... ... There are at least $k$ bombs after the $k$-th rightmost value $\geq x$. Let $ans_i$ be the answer for bombs $q_1, q_2, \ldots, q_{i-1}$. Then, $ans_i \geq ans_{i+1}$. Let's add new bombs starting from $ans_{i-1}$, and while the actual answer is smaller than the current answer, decrease the actual answer. To do this quickly, we'll use a segment tree. In the segment tree, let's store $b_i =$ (number of values $\geq x$ on suffix $i \ldots n$) $-$ (number of bombs on this suffix). Then, the real answer is $< x$ if $b_i \leq 0$ for all $i$. Using range addition updates and max queries, we can update $b$ and decrease the answer quickly. The total complexity is $\mathcal{O}{(n \log n)}$. Bonus: is it possible to solve the problem in $\mathcal{O}{(n)}$?
|
[
"data structures",
"two pointers"
] | 2,400
| null |
1326
|
F2
|
Wise Men (Hard Version)
|
\textbf{This is the hard version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved.}
$n$ wise men live in a beautiful city. Some of them know each other.
For each of the $n!$ possible permutations $p_1, p_2, \ldots, p_n$ of the wise men, let's generate a binary string of length $n-1$: for each $1 \leq i < n$ set $s_i=1$ if $p_i$ and $p_{i+1}$ know each other, and $s_i=0$ otherwise.
For all possible $2^{n-1}$ binary strings, find the number of permutations that produce this binary string.
|
For each binary string $s$, let's calculate $f(s)$ - the number of permutations, such that, if $s_i=1$, then $p_i$ and $p_{i+1}$ know each other, otherwise, they may know or don't know each other. To get real answers, we may use inclusion-exclusion, which may be optimized using a straightforward sum over subsets dp. To calculate $f(s)$, we need to note that $f$ depends only on the multiset of lengths of blocks of $1$'s in it. For example, $f(110111) = f(111011)$, because the multiset of lengths is $\{1, 3, 4\}$ (note that block of size $x$ of $1$'s corresponds to length $x+1$). And note that there are exactly $P(n)$ (the number of partitions of $n$) possible multisets. $P(18) = 385$ To process further, at first let's calculate $g_{len, mask}$ - the number of paths of length $len$, which pass only through the vertices from $mask$ (and only through them). You can calculate it with a straightforward $dp_{mask, v}$ in $\mathcal{O}{(2^n \cdot n^2)}$. Then, let's fix the multiset of lengths $a_1, a_2, \ldots, a_k$. I claim that the $f(s)$ for this multiset is equal to $\sum{\prod{g_{a_i, m_i}}}$ over all masks $m_1, m_2, \ldots m_k$, such that the bitwise OR of $m_1, m_2, \ldots, m_k$ is equal to $2^n-1$ (note that we don't care about the number of bits like in a usual non-intersecting subsets convolution, because if some masks are intersecting, then their OR won't be equal to $2^n-1$ because $\sum{a_i} = n$). You can calculate this sum by changing $g_{len}$ to the sum over subsets. And then, for this partition, you can just calculate $d_{mask} = \prod{g_{a_i, mask}}$ in $\mathcal{O}{(k \cdot 2^n)}$, and you can restore the real value of $2^n-1$ by inclusion-exclusion in $\mathcal{O}{(2^n)}$. If you will calculate this naively, you will get the $\mathcal{O}$((sum of sizes of all partitions) $\cdot 2^n)$ solution, which is enough to get AC. But you can optimize this because you can maintain $d_{mask}$ during the brute force of all partitions. And in the tree of all partitions, there are $\mathcal{O}{(P(n))}$ intermediate vertices, so it will work in $\mathcal{O}{(P(n) \cdot 2^n)}$. The total complexity is $\mathcal{O}{((P(n) + n^2) \cdot 2^n))}$.
|
[
"bitmasks",
"dp",
"math"
] | 3,200
|
"#include <cmath>\n#include <functional>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <unordered_set>\n#include <iomanip>\n#include <bitset>\n#include <sstream>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\ntypedef unsigned long long ll;\n\n#ifdef iq\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nconst int N = 19;\n\nint g[N];\nll dp[1 << N][N+1];\nll ok[1 << N];\n\nll slen[N+1][1 << N];\n\nll cur[N+1][1 << N];\nll val[1 << N];\n\nll ans[1 << N];\n\nint main() {\n#ifdef iq\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n;\n cin >> n;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n char c;\n cin >> c;\n if (c == '1') {\n g[i] |= (1 << j);\n }\n }\n }\n for (int i = 0; i < n; i++) {\n dp[1 << i][i] = 1;\n }\n for (int mask = 0; mask < (1 << n); mask++) {\n for (int i = 0; i < n; i++) {\n int cands = g[i] & (~mask);\n for (int j = 0; j < n; j++) {\n if ((cands >> j) & 1) {\n dp[mask | (1 << j)][j] += dp[mask][i];\n }\n }\n ok[mask] += dp[mask][i];\n }\n }\n for (int len = 1; len <= n; len++) {\n for (int mask = 0; mask < (1 << n); mask++) {\n if (__builtin_popcount(mask) == len) {\n slen[len][mask] += ok[mask];\n }\n }\n for (int i = 0; i < n; i++) {\n for (int mask = 0; mask < (1 << n); mask++) {\n if ((mask >> i) & 1) {\n slen[len][mask] += slen[len][mask ^ (1 << i)];\n }\n }\n }\n }\n map <vector <int>, vector <int> > ok;\n for (int mask = 0; mask < (1 << (n - 1)); mask++) {\n int x = 0;\n vector <int> t;\n while (x < n) {\n int len = 1;\n while ((mask >> x) & 1) {\n x++;\n len++;\n }\n t.push_back(len);\n x++;\n }\n sort(t.begin(), t.end());\n ok[t].push_back(mask);\n }\n vector <int> a;\n for (int mask = 0; mask < (1 << n); mask++)\n val[mask] = 1;\n function<void(int,int)> f = [&] (int s, int last) {\n if (s == n) {\n ll ret = 0;\n int x = (1 << n) - 1;\n for (int mask = 0; mask < (1 << n); mask++) {\n if (__builtin_popcount(mask) % 2 == 0)\n ret += val[x ^ mask];\n else\n ret -= val[x ^ mask];\n }\n for (auto c : ok[a]) {\n ans[c] += ret;\n }\n return;\n }\n if (s + last > n) {\n return;\n }\n for (int mask = 0; mask < (1 << n); mask++) {\n cur[s][mask] = val[mask];\n }\n for (int i = last; s + i <= n; i++) {\n if (s + i != n && s + i + i > n) continue;\n a.push_back(i);\n for (int mask = 0; mask < (1 << n); mask++) {\n val[mask] *= slen[i][mask];\n }\n f(s + i, i);\n for (int mask = 0; mask < (1 << n); mask++) {\n val[mask] = cur[s][mask];\n }\n a.pop_back();\n }\n };\n f(0, 1);\n for (int i = 0; i < (n - 1); i++) {\n for (int mask = 0; mask < (1 << (n - 1)); mask++) {\n if (!((mask >> i) & 1)) {\n ans[mask] -= ans[mask + (1 << i)];\n }\n }\n }\n for (int mask = 0; mask < (1 << (n - 1)); mask++) {\n cout << ans[mask] << ' ';\n }\n cout << endl;\n}"
|
1326
|
G
|
Spiderweb Trees
|
Let's call a graph with $n$ vertices, each of which has it's own point $A_i = (x_i, y_i)$ with integer coordinates, a planar tree if:
- All points $A_1, A_2, \ldots, A_n$ are different and no three points lie on the same line.
- The graph is a tree, i.e. there are exactly $n-1$ edges there exists a path between any pair of vertices.
- For all pairs of edges $(s_1, f_1)$ and $(s_2, f_2)$, such that $s_1 \neq s_2, s_1 \neq f_2,$ $f_1 \neq s_2$, and $f_1 \neq f_2$, the segments $A_{s_1} A_{f_1}$ and $A_{s_2} A_{f_2}$ don't intersect.
Imagine a planar tree with $n$ vertices. Consider the convex hull of points $A_1, A_2, \ldots, A_n$. Let's call this tree a spiderweb tree if for all $1 \leq i \leq n$ the following statements are true:
- All leaves (vertices with degree $\leq 1$) of the tree lie on the border of the convex hull.
- All vertices on the border of the convex hull are leaves.
An example of a spiderweb tree:
The points $A_3, A_6, A_7, A_4$ lie on the convex hull and the leaf vertices of the tree are $3, 6, 7, 4$.
Refer to the notes for more examples.
Let's call the subset $S \subset \{1, 2, \ldots, n\}$ of vertices a subtree of the tree if for all pairs of vertices in $S$, there exists a path that contains only vertices from $S$. Note that any subtree of the planar tree is a planar tree.
You are given a planar tree with $n$ vertexes. Let's call a partition of the set $\{1, 2, \ldots, n\}$ into non-empty subsets $A_1, A_2, \ldots, A_k$ (i.e. $A_i \cap A_j = \emptyset$ for all $1 \leq i < j \leq k$ and $A_1 \cup A_2 \cup \ldots \cup A_k = \{1, 2, \ldots, n\}$) good if for all $1 \leq i \leq k$, the subtree $A_i$ is a spiderweb tree. Two partitions are different if there exists some set that lies in one parition, but not the other.
Find the number of good partitions. Since this number can be very large, find it modulo $998\,244\,353$.
|
Let's hang the tree on the vertex $1$. After that, we will calculate the value $dp_i$ for all vertices $i$, which is equal to the number of good partitions of the subtree of the vertex $i$ (subtree in the rooted tree). The answer to the problem in these definitions is $dp_1$. To calculate these values let's make dfs. We know in the vertex $p$ and we want to calculate $dp_p$. We know the values $dp_i$ for all $i$ in the subtree of $p$. Let's define the set of the partition, which contains $p$ as $S$. There are some cases: Case $1$: $|S| = 1$. In this case, the number of good partitions is $dp_{i_1} dp_{i_2} \ldots dp_{i_k}$, there $i_1, i_2, \ldots, i_k$ are all sons of the vertex $p$. Case $2$: $|S| = 2$. In this case, the number of good partitions is $\sum\limits_{i \in Sons(p)} {f_i \prod\limits_{j \in Sons(p), j \neq i} dp_{j}}$, there $f_i = dp_{i_1} dp_{i_2} \ldots dp_{i_k}$, there $i_1, i_2, \ldots, i_k$ are all sons of the vertex $i$. The values in these cases are easy to find. We have one, last case: Case $3$: $|S| \geq 3$. In this case, the number of good partitions is $\sum\limits_{p \in S, \, S \, is \, spiderweb} func(S)$. Let's define $func(S)$ as the product of $dp_i$ for all vertices $i$, which are going from $S$ (it means, that $i$ isn't in $S$, but ancestor of $i$ is in $S$). Let's try to calculate this sum faster. Let's call a pair of vertices $(i, j)$ good if they are not connected and all vertices $t$ on the path from $i$ to $j$ lies on the left side from the vector $\overrightarrow{A_i A_j}$. It can be shown, that if the polygon $A_{i_1} A_{i_2} \ldots A_{i_k}$ is convex and all pairs $(i_{j}, i_{j+1})$ are good, the subtree with leafs $i_1, i_2, \ldots, i_k$ is spiderweb. So, let's fix all leaf vertices in $S$: $i_1, i_2, \ldots, i_k$ (these are the vertices of the subtree of $p$, they can be equal to $p$). If $S$ is the spiderweb tree, the ways $(i_j, i_{j+1})$ divide the plane into infinite parts (for explanation look at the picture): The part is defined only with the way in the tree. Let's define $value_{ij}$ as the product of $dp_t$ for all vertices $t$, such that $A_t$ lies in the part for the way $(i, j)$, the vertex $t$ doesn't lie on the way and the ancestor of $t$ lies on the way. So, it's easy to see, that $func(S) = \prod\limits_{i=1}^{k} {value_{i_j i_{j+1}}}$. We can calculate the value for each path only one time during the dfs, after the moment, when all needed values of dp will be defined. So, let's take all pairs of vertices $(i, j)$, such that $i$ and $j$ are in the subtree of vertex $p$, the way $(i, j)$ is good and the point $A_p$ lies on the left side from the vector $\overrightarrow{A_i A_j}$. After that, we should calculate the sum of products of $value_{i_j i_{j+1}}$ for all convex polygons $A_{i_1} A_{i_2} \ldots A_{i_k}$, which contains the vertex $p$ on some path $(i_j i_{j+1)}$. This thing can be done by the standard dp in time $O(n^3)$ (the same dp as how we calculate the number of convex polygons). To fix the last condition we can make this dp two times: with all good pairs and with good pairs, which don't contain the vertex $p$. After that, the needed number is the subtraction of these two numbers. So, we have the solution with time complexity $O(n^4)$.
|
[
"dp",
"geometry",
"trees"
] | 3,500
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pi;\n#define prev _prev\n#define stack _stack\n\nll scal(pi a, pi b)\n{\n return (ll)a.first * (ll)a.second + (ll)b.first * (ll)b.second;\n}\n\nll mul(pi a, pi b)\n{\n return (ll)a.first * (ll)b.second - (ll)a.second * (ll)b.first;\n}\n\nint half(pi a)\n{\n if (a.second > 0 || (a.second == 0 && a.first >= 0))\n return 0;\n return 1;\n}\n\nint half(pi a, pi b)\n{\n ll pr = mul(a, b);\n if (pr != 0)\n return (pr <= 0);\n return (scal(a, b) < 0);\n}\n\nconst int M = 210;\nconst int MOD = 998244353;\n\nint n, x[M], y[M], dp[M], val[M][M], ml[M], ei[M][M], first[M][M], last[M][M], sum[2 * M], ok[M][M];\nvector<int> v[M];\nvector<int> way[M][M];\n\npi vect(int i, int j)\n{\n return make_pair(x[j] - x[i], y[j] - y[i]);\n}\n\npi vect(pi t)\n{\n return make_pair(x[t.second] - x[t.first], y[t.second] - y[t.first]);\n}\n\nvoid dfs_help(int p, int pr)\n{\n int id = -1;\n for (int i = 0; i < (int)v[p].size(); i++)\n {\n if (v[p][i] == pr)\n id = i;\n else\n dfs_help(v[p][i], p);\n }\n if (id != -1)\n {\n swap(v[p][id], v[p].back());\n v[p].pop_back();\n }\n}\n\nvector<int> stack;\n\nvoid dfs_way(int p, int pr, int st)\n{\n stack.push_back(p);\n if (p != st && (int)stack.size() >= 3)\n {\n bool ch = true;\n for (int i : stack)\n if (mul(vect(st, p), vect(st, i)) < 0)\n {\n ch = false;\n break;\n }\n if (ch)\n way[st][p] = stack;\n }\n for (int i : v[p])\n if (i != pr)\n dfs_way(i, p, st);\n stack.pop_back();\n}\n\nbool cmp(pi a, pi b)\n{\n pi va = vect(a);\n pi vb = vect(b);\n int ha = half(va);\n int hb = half(vb);\n if (ha != hb)\n return ha < hb;\n ll pr = mul(va, vb);\n if (pr != 0)\n return (pr > 0);\n return a < b;\n}\n\nbool good(pi a, pi b, pi c)\n{\n int hb = half(a, b);\n int hc = half(a, c);\n if (hb != hc)\n return hb < hc;\n return mul(b, c) > 0;\n}\n\nvector<int> g[M];\n\nvector<int> dfs(int p)\n{\n ml[p] = 1;\n vector<int> now = {p};\n for (int i : v[p])\n {\n vector<int> to = dfs(i);\n for (int x : to)\n now.push_back(x);\n ml[p] = (ll)ml[p] * dp[i] % MOD;\n }\n dp[p] = ml[p];\n for (int i : v[p])\n {\n int cur = ml[i];\n for (int j : v[p])\n if (j != i)\n cur = (ll)cur * dp[j] % MOD;\n dp[p] += cur;\n if (dp[p] >= MOD)\n dp[p] -= MOD;\n }\n for (int i : now)\n g[i].clear();\n int k = 0;\n for (int i : now)\n for (int j : v[i])\n {\n g[i].push_back(j);\n g[j].push_back(i);\n ei[i][j] = k++;\n ei[j][i] = k++;\n }\n for (int i : now)\n for (int j : now)\n ok[i][j] = 0;\n vector<pi> al;\n for (int i : now)\n for (int j : now)\n if (!way[i][j].empty() && mul(vect(i, j), vect(i, p)) >= 0)\n {\n al.push_back(make_pair(i, j));\n first[i][j] = ei[way[i][j][0]][way[i][j][1]];\n last[i][j] = ei[way[i][j][(int)way[i][j].size() - 1]][way[i][j][(int)way[i][j].size() - 2]];\n if (val[i][j] != -1)\n continue;\n ok[i][j] = 1;\n val[i][j] = 1;\n for (int x = 0; x < (int)way[i][j].size(); x++)\n {\n int v_cur = way[i][j][x];\n pi lb, rb;\n if (x == 0)\n {\n lb = vect(v_cur, way[i][j][x + 1]);\n lb.first = -lb.first, lb.second = -lb.second;\n }\n else\n lb = vect(v_cur, way[i][j][x - 1]);\n if (x + 1 == (int)way[i][j].size())\n {\n rb = vect(v_cur, way[i][j][x - 1]);\n rb.first = -rb.first, rb.second = -rb.second;\n }\n else\n rb = vect(v_cur, way[i][j][x + 1]);\n for (int to : v[v_cur])\n if (good(lb, vect(v_cur, to), rb))\n {\n if (x != 0 && to == way[i][j][x - 1])\n continue;\n if (x + 1 < (int)way[i][j].size() && to == way[i][j][x + 1])\n continue;\n val[i][j] = (ll)val[i][j] * dp[to] % MOD;\n }\n }\n }\n sort(al.begin(), al.end(), cmp);\n for (int v_st : now)\n for (int ig : g[v_st])\n {\n if (half(vect(v_st, ig)))\n continue;\n for (int ban = -1; ban <= 1; ban += 2)\n {\n for (int i = 0; i < k; i++)\n sum[i] = 0;\n sum[ei[v_st][ig]] = 1;\n for (pi t : al)\n {\n if (ban == -1 && ok[t.first][t.second])\n continue;\n int S = first[t.first][t.second];\n int F = last[t.first][t.second];\n sum[F] += (ll)sum[S] * val[t.first][t.second] % MOD;\n if (sum[F] >= MOD)\n sum[F] -= MOD;\n }\n sum[ei[v_st][ig]]--;\n if (sum[ei[v_st][ig]] < 0)\n sum[ei[v_st][ig]] += MOD;\n dp[p] += ban * sum[ei[v_st][ig]];\n if (dp[p] >= MOD)\n dp[p] -= MOD;\n if (dp[p] < 0)\n dp[p] += MOD;\n }\n }\n return now;\n}\n\nint main()\n{\n cin >> n;\n for (int i = 0; i < n; i++)\n cin >> x[i] >> y[i];\n for (int i = 0; i < n - 1; i++)\n {\n int s, f;\n cin >> s >> f;\n s--, f--;\n v[s].push_back(f);\n v[f].push_back(s);\n }\n for (int i = 0; i < n; i++)\n dfs_way(i, -1, i);\n dfs_help(0, -1);\n memset(val, -1, sizeof(val));\n dfs(0);\n cout << dp[0] << \"\\n\";\n return 0;\n}"
|
1327
|
A
|
Sum of Odd Integers
|
You are given two integers $n$ and $k$. Your task is to find if $n$ can be represented as a sum of $k$ \textbf{distinct positive odd} (not divisible by $2$) integers or not.
You have to answer $t$ independent test cases.
|
First of all, notice that the sum of the first $k$ odd integers is $k^2$. If $k^2 > n$ then the answer obviously "NO". And if $n \% 2 \ne k \% 2$ then the answer is "NO" also ($\%$ is modulo operation). Otherwise, the answer is always "YES" and it seems like this: $[1, 3, 5, \dots, 2(k-1)-1, rem]$, where $rem = n - \sum\limits_{i=1}^{k-1} (2i-1)$. It is obviously greater than $2(k-1)-1$ because $k^2 \le n$ and it is obviously odd because the parity of $n$ and $k$ is the same.
|
[
"math"
] | 1,100
|
for i in range(int(input())):
n, k = map(int, input().split())
print('YES' if k * k <= n and n % 2 == k % 2 else 'NO')
|
1327
|
B
|
Princesses and Princes
|
The King of Berland Polycarp LXXXIV has $n$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $n$ other kingdoms as well.
So Polycarp LXXXIV has enumerated his daughters from $1$ to $n$ and the kingdoms from $1$ to $n$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.
Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.
For the first daughter he takes \textbf{the kingdom with the lowest number from her list} and marries the daughter to their prince. For the second daughter he takes \textbf{the kingdom with the lowest number from her list, prince of which hasn't been taken already}. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $n$-th daughter.
For example, let there be $4$ daughters and kingdoms, the lists daughters have are $[2, 3]$, $[1, 2]$, $[3, 4]$, $[3]$, respectively.
In that case daughter $1$ marries the prince of kingdom $2$, daughter $2$ marries the prince of kingdom $1$, daughter $3$ marries the prince of kingdom $3$, leaving daughter $4$ nobody to marry to.
Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. \textbf{Note that this kingdom should not be present in the daughter's list.}
Polycarp LXXXIV wants to increase the number of married couples.
Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.
If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.
For your and our convenience you are asked to answer $t$ independent test cases.
|
Simulate the process without adding the new entry. For this you can just maintain an array $taken$, $i$-th value of which is true if the $i$-th prince is married and false otherwise. Now observe that there are two possible outcomes: Every daughter is married - the answer is optimal. There is a daughter who isn't married. That means that there is a free prince as well. Marry them to each other because doing that won't affect any other marriages and add a new one to the answer. Overall complexity: $O(n + m)$.
|
[
"brute force",
"graphs",
"greedy"
] | 1,200
|
from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
used = [False for i in range(n)]
v = -1
for i in range(n):
l = [int(x) - 1 for x in stdin.readline().split()][1:]
for j in l:
if not used[j]:
used[j] = True
break
else:
v = i
if v == -1:
stdout.write("OPTIMAL\n")
else:
u = used.index(False)
stdout.write("IMPROVE\n" + str(v + 1) + " " + str(u + 1) + "\n")
|
1327
|
C
|
Game with Chips
|
Petya has a rectangular Board of size $n \times m$. Initially, $k$ chips are placed on the board, $i$-th chip is located in the cell at the intersection of $sx_i$-th row and $sy_i$-th column.
In one action, Petya can move \textbf{all the chips} to the left, right, down or up by $1$ cell.
If the chip was in the $(x, y)$ cell, then after the operation:
- left, its coordinates will be $(x, y - 1)$;
- right, its coordinates will be $(x, y + 1)$;
- down, its coordinates will be $(x + 1, y)$;
- up, its coordinates will be $(x - 1, y)$.
If the chip is located by the wall of the board, and the action chosen by Petya moves it towards the wall, then the chip remains in its current position.
\textbf{Note that several chips can be located in the same cell.}
For each chip, Petya chose the position which it should visit. Note that it's not necessary for a chip to end up in this position.
Since Petya does not have a lot of free time, he is ready to do no more than $2nm$ actions.
You have to find out what actions Petya should do so that each chip visits the position that Petya selected for it at least once. Or determine that it is not possible to do this in $2nm$ actions.
|
Note that $2nm$ is a fairly large number of operations. Therefore, we can first collect all the chips in one cell, and then go around the entire board. Let's calculate the required number of operations. First, let's collect all the chips in the $(1, 1)$ cell. To do this, let's do $n-1$ operations $U$ so that all the chips are in the first row, then do $m-1$ operations $L$. After such operations, wherever the chip is initially located, it will end up in the $(1, 1)$ cell. After that, we need to go around the entire board. Let's do it in such a way that the rows with odd numbers are be bypassed from left to right, and the even ones - from right to left. We also need $n-1$ operations $D$ to move from one row to the next one. In total, we got $(n-1) + (m-1) + n * (m-1) + (n-1) = nm + n + m - 3$ operations, which is completely suitable for us.
|
[
"constructive algorithms",
"implementation"
] | 1,600
|
n, m, _ = map(int, input().split())
print(2 * (n - 1) + (n + 1) * (m - 1))
print("U" * (n - 1) + "L" * (m - 1), end="")
for i in range(n):
if i != 0:
print("D", end="")
if i % 2 == 0:
print("R" * (m - 1), end="")
else:
print("L" * (m - 1), end="")
|
1327
|
D
|
Infinite Path
|
You are given a colored permutation $p_1, p_2, \dots, p_n$. The $i$-th element of the permutation has color $c_i$.
Let's define an infinite path as infinite sequence $i, p[i], p[p[i]], p[p[p[i]]] \dots$ where all elements have \textbf{same color} ($c[i] = c[p[i]] = c[p[p[i]]] = \dots$).
We can also define a multiplication of permutations $a$ and $b$ as permutation $c = a \times b$ where $c[i] = b[a[i]]$. Moreover, we can define a power $k$ of permutation $p$ as $p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$.
Find the minimum $k > 0$ such that $p^k$ has at least one infinite path (i.e. there is a position $i$ in $p^k$ such that the sequence starting from $i$ is an infinite path).
It can be proved that the answer always exists.
|
Let's look at the permutation as at a graph with $n$ vertices and edges $(i, p_i)$. It's not hard to prove that the graph consists of several cycles (self-loops are also considered as cycles). So, the sequence $i, p[i], p[p[i]], \dots$ is just a walking on the corresponding cycle. Let's consider one cycle $c_1, c_2, \dots, c_m$. In permutation $p$ we have $p[c_i] = c_{(i + 1) \mod m}$. But since $p^2 = p \times p$ or $p^2[i] = p[p[i]]$, so $p^2[c_i] = c_{(i + 2) \mod m}$ and in general case, $p^k[c_i] = c_{(i + k) \mod m}$. Now, walking with step $k$ we can note, that the initial cycle $c$ split up on $GCD(k, m)$ cycles of length $\frac{m}{GCD(k, m)}$. Looking at the definition of infinite path we can understand that all we need to do is to check that at least one of $GCD(k, m)$ cycles have all vertices of the same color. We can check it in $O(m)$ time for the cycle $c$ and fixed $k$. The final observation is next: for $k_1$ and $k_2$ such that $GCD(k_1, m) = GCD(k_2, m)$ the produced cycles will have the same sets of vertices and differ only in the order of walking, so we can check only one representative for each $GCD(k, m)$, i.e. we can take only such $k$ which divide $m$. We can handle each cycle of $p$ separately. So, using the approximation that the number of divisors of $n$ is $O(n^{\frac{1}{3}})$, we get $O(n^{\frac{4}{3}})$ time complexity.
|
[
"brute force",
"dfs and similar",
"graphs",
"math",
"number theory"
] | 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);
int n;
vector<int> p, c;
inline bool read() {
if(!(cin >> n))
return false;
p.resize(n);
c.resize(n);
fore(i, 0, n) {
cin >> p[i];
p[i]--;
}
fore(i, 0, n)
cin >> c[i];
return true;
}
inline void solve() {
vector<int> used(n, 0);
int ans = INF;
fore(st, 0, n) {
if(used[st])
continue;
vector<int> cycle;
int v = st;
while(!used[v]) {
used[v] = 1;
cycle.push_back(v);
v = p[v];
}
fore(step, 1, sz(cycle) + 1) {
if(sz(cycle) % step != 0)
continue;
fore(s, 0, step) {
bool eq = true;
for(int pos = s; pos + step < sz(cycle); pos += step) {
if(c[cycle[pos]] != c[cycle[pos + step]])
eq = false;
}
if(eq) {
ans = min(ans, step);
break;
}
}
}
}
cout << ans << 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;
}
|
1327
|
E
|
Count The Blocks
|
You wrote down all integers from $0$ to $10^n - 1$, padding them with leading zeroes so their lengths are exactly $n$. For example, if $n = 3$ then you wrote out 000, 001, ..., 998, 999.
A block in an integer $x$ is a consecutive segment of equal digits that cannot be extended to the left or to the right.
For example, in the integer $00027734000$ there are three blocks of length $1$, one block of length $2$ and two blocks of length $3$.
For all integers $i$ from $1$ to $n$ count the number of blocks of length $i$ among the written down integers.
Since these integers may be too large, print them modulo $998244353$.
|
Presume that we want to calculate the number of blocks of length $len$. Let's divide this blocks into two types: blocks which first element is a first element of integer, or blocks which last element is a last element of integer (for example blocks $111$ and $0$ in integer $11173220$); other blocks. At first let's calculate the number of blocks of first type. We can choose $2$ positions of this block (at the start of end of the integer). Now we can choose $10$ digit for this block. After that we can chose $9$ digits of adjacent block (if these blocks contain the same digit then we length of blocks which we want calculate greater than $len$, so we have only $9$ variations of digit in adjacent block). Finally, the can chose the remaining digit $10^{n-len-1}$ ways. So, the total number of block of first type is $2 \cdot 10 \cdot 9 \cdot 10^{n-len-1}$. Now let's calculate the number of blocks of second type. We can choose $n - len - 1$ positions of this block (all position except the start and end of integer). Now we can choose 10 digit for this block. After that we can chose $9^2$ digits of adjacent block ($9$ for block to the left and $9$ for block to the right). Finally, the can chose the remaining digit $10^{n-len-2}$ ways. So, the total number of block of second type is $(n - len - 1) \cdot 10 \cdot 9^2 \cdot 10^{n-len-2}$. That's almost all. We have one corner case. If $len = n$, then we number of blocks is always $10$.
|
[
"combinatorics",
"dp",
"math"
] | 1,800
|
MOD = 998244353
p = [1] * 200005
for i in range(1, 200005):
p[i] = (p[i - 1] * 10) % MOD
n = int(input())
for i in range(1, n):
res = 2 * 10 * 9 * p[n - i - 1]
res += (n - 1 - i) * 10 * 9 * 9 * p[n - i - 2]
print(res % MOD, end = ' ')
print(10)
|
1327
|
F
|
AND Segments
|
You are given three integers $n$, $k$, $m$ and $m$ conditions $(l_1, r_1, x_1), (l_2, r_2, x_2), \dots, (l_m, r_m, x_m)$.
Calculate the number of distinct arrays $a$, consisting of $n$ integers such that:
- $0 \le a_i < 2^k$ for each $1 \le i \le n$;
- bitwise AND of numbers $a[l_i] \& a[l_i + 1] \& \dots \& a[r_i] = x_i$ for each $1 \le i \le m$.
Two arrays $a$ and $b$ are considered different if there exists such a position $i$ that $a_i \neq b_i$.
The number can be pretty large so print it modulo $998244353$.
|
We will solve the problem for each bit separately, and then multiply the results. Obviously, if the position is covered by a segment with the value $1$, then we have no choice, and we must put $1$ there. For segments with the value $0$, there must be at least one position that they cover and its value is $0$. So we can write the following dynamic programming: $dp_i$ - the number of arrays such that the last $0$ was exactly at the position $i$, and all $0$-segments to the left of it contain at least one zero. It remains to determine which states $j$ we can update from. The only restriction we have is that there should not be any segment $(l, r)$ with the value $0$, such that $j < l$ and $r < i$. Since in this case, this segment will not contain any zero values. For each position $i$, we may precalculate the rightmost position $f_i$ where some segment ending before $i$ begins, and while calculating $dp_i$, we should sum up only the values starting from position $f_i$. This can be done with prefix sums.
|
[
"bitmasks",
"combinatorics",
"data structures",
"dp",
"two pointers"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#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)
typedef pair<int, int> pt;
const int MOD = 998244353;
const int N = 500 * 1000 + 13;
int n, k, m;
pair<pt, int> q[N];
int ones[N];
int mx[N], sum[N];
int add(int x, int y) {
x += y;
if (x >= MOD) x -= MOD;
if (x < 0) x += MOD;
return x;
}
int calc(int t) {
memset(ones, 0, sizeof(ones));
memset(mx, -1, sizeof(mx));
forn(i, m) {
int l = q[i].x.x, r = q[i].x.y;
if (q[i].y & (1 << t)) {
ones[l]++;
ones[r + 1]--;
} else {
mx[r] = max(mx[r], l);
}
}
int j = -1;
forn(i, n) {
int cur = 0;
if (!ones[i]) {
cur = sum[i];
if (j == -1) cur = add(cur, 1);
else cur = add(cur, -sum[j]);
}
sum[i + 1] = add(sum[i], cur);
ones[i + 1] += ones[i];
j = max(j, mx[i]);
}
return add(sum[n], j != -1 ? -sum[j] : 1);
}
int main() {
scanf("%d%d%d", &n, &k, &m);
forn(i, m) {
scanf("%d%d%d", &q[i].x.x, &q[i].x.y, &q[i].y);
--q[i].x.x; --q[i].x.y;
}
int ans = 1;
forn(i, k) ans = (ans * 1ll * calc(i)) % MOD;
printf("%d\n", ans);
}
|
1327
|
G
|
Letters and Question Marks
|
You are given a string $S$ and an array of strings $[t_1, t_2, \dots, t_k]$. Each string $t_i$ consists of lowercase Latin letters from a to n; $S$ consists of lowercase Latin letters from a to n and \textbf{no more than $14$} question marks.
Each string $t_i$ has its cost $c_i$ — an integer number. The value of some string $T$ is calculated as $\sum\limits_{i = 1}^{k} F(T, t_i) \cdot c_i$, where $F(T, t_i)$ is the number of occurences of string $t_i$ in $T$ as a substring. For example, $F(\text{aaabaaa}, \text{aa}) = 4$.
You have to replace all question marks in $S$ with \textbf{pairwise distinct} lowercase Latin letters from a to n so the value of $S$ is maximum possible.
|
Suppose we want to calculate the value of some already fixed string (we should be able to do so at least to solve the test cases without question marks). How can we do it? We can use some substring searching algorithms to calculate $F(S, t_i)$, but a better solution is to build an Aho-Corasick automaton over the array $[t_1, t_k]$, and then for each node calculate the sum of costs of all strings ending in that node (these are the strings represented by that node and the strings represented by other nodes reachable by suffix links). After that, process $S$ by the automaton and calculate the sum of the aforementioned values over all states that were reached. Building an Aho-Corasick automaton can be done in $O(\sum \limits_{i = 1}^{k} |t_i|)$, and processing the string $S$ - in $O(|S|)$. Okay, what if we've got some question marks in our string? The first solution that comes to mind is to calculate $dp[i][mask][c]$ - we processed $i$ first positions in $S$, used a $mask$ of characters for question marks, and the current state of the automaton is $c$; then $dp[i][mask][c]$ denotes the maximum value of first $i$ characters of $S$ we could have got. But it's $O(L|S|2^KK)$, where $L = \sum \limits_{i = 1}^{k} |t_i|$ and $K$ is the size of the alphabet, which is too slow. To speed it up, we can see that there are only $14$ positions in our string where we actually choose something in our dynamic programming. All substrings not containing question marks can be skipped in $O(1)$ as follows: for each substring of $S$ bounded by two question marks (or bounded by one question mark and one of the ends of $S$) and each state of the automaton $x$, we may precalculate the resulting state of the automaton and the change to the value of the string, if we process this substring by the automaton with the initial state $x$. This precalculation is done in $O(L|S|)$ overall, and using this, we may skip the states of dynamic programming such that $i$ is not a position with a question mark, so our complexity becomes $O(L2^KK + L|S|)$. A note about the model solution: it's a bit more complicated because we wanted to increase the constraints to $|S| \le 8 \cdot 10^6$, but then we decided that it would be too complicated to code, so the main function still contains some parts of the code that were used to improve its complexity. We will post a clearer version of the model solution soon.
|
[
"bitmasks",
"dp",
"string suffix structures"
] | 2,800
|
#include<bits/stdc++.h>
using namespace std;
const int N = 8000043;
const int K = 15;
const int M = 1043;
int k;
char buf[N], buf2[M];
vector<string> t;
vector<int> c;
string s;
map<char, int> nxt[M];
int lnk[M];
int p[M];
char pchar[M];
map<char, int> go[M];
int term[M];
int ts = 1;
int A[M][K];
int F[M][K];
int dp[M];
int get_nxt(int x, char c)
{
if(!nxt[x].count(c))
{
p[ts] = x;
pchar[ts] = c;
nxt[x][c] = ts++;
}
return nxt[x][c];
}
void add_string(int i)
{
int cur = 0;
for(auto x : t[i])
{
cur = get_nxt(cur, x);
}
term[cur] += c[i];
}
int get_go(int x, char c);
int get_lnk(int x)
{
if(lnk[x] != -1)
return lnk[x];
if(x == 0 || p[x] == 0)
return lnk[x] = 0;
return lnk[x] = get_go(get_lnk(p[x]), pchar[x]);
}
int get_dp(int x)
{
if(dp[x] != -1)
return dp[x];
dp[x] = term[x];
if(get_lnk(x) != x)
dp[x] += get_dp(get_lnk(x));
return dp[x];
}
int get_go(int x, char c)
{
if(go[x].count(c))
return go[x][c];
if(nxt[x].count(c))
return go[x][c] = nxt[x][c];
if(x == 0)
return go[x][c] = 0;
return go[x][c] = get_go(get_lnk(x), c);
}
void build_skip(const string& s, vector<int>& sA, vector<long long>& sF)
{
sA = vector<int>(ts);
for(int i = 0; i < ts; i++)
sA[i] = i;
sF = vector<long long>(ts);
for(auto c : s)
{
int ci = int(c - 'a');
for(int i = 0; i < ts; i++)
{
sF[i] += F[sA[i]][ci];
sA[i] = A[sA[i]][ci];
}
}
}
long long solve(const string& s)
{
long long BAD = (long long)(-1e18);
vector<int> pos;
for(int i = 0; i < s.size(); i++)
if(s[i] == '?')
pos.push_back(i);
int cntQ = pos.size();
vector<vector<int> > skip_A(cntQ + 1);
vector<vector<long long> > skip_F(cntQ + 1);
build_skip(s.substr(0, pos[0]), skip_A[0], skip_F[0]);
for(int i = 1; i < cntQ; i++)
build_skip(s.substr(pos[i - 1] + 1, pos[i] - pos[i - 1] - 1), skip_A[i], skip_F[i]);
build_skip(s.substr(pos.back() + 1, s.size() - pos.back() - 1), skip_A[cntQ], skip_F[cntQ]);
vector<vector<long long> > dp(1 << (K - 1), vector<long long>(ts, BAD));
vector<int> used(1 << K);
dp[0][skip_A[0][0]] = skip_F[0][0];
queue<int> q;
q.push(0);
used[0] = 1;
long long ans = BAD;
while(!q.empty())
{
int k = q.front();
q.pop();
int step = __builtin_popcount(k);
if(step == cntQ)
{
for(int i = 0; i < ts; i++)
ans = max(ans, dp[k][i]);
continue;
}
for(int i = 0; i < K - 1; i++)
{
if(k & (1 << i)) continue;
int nk = (k ^ (1 << i));
if(used[nk] == 0)
{
used[nk] = 1;
q.push(nk);
}
for(int j = 0; j < ts; j++)
{
if(dp[k][j] == BAD)
continue;
int nj = get_go(j, char('a' + i));
int newSt = skip_A[step + 1][nj];
long long add = get_dp(nj) + skip_F[step + 1][nj];
dp[nk][newSt] = max(dp[nk][newSt], dp[k][j] + add);
}
}
}
return ans;
}
int main()
{
scanf("%d", &k);
t.resize(k);
c.resize(k);
for(int i = 0; i < k; i++)
{
scanf("%s %d", buf2, &c[i]);
t[i] = buf2;
}
scanf("%s", buf);
s = buf;
for(int i = 0; i < k; i++)
add_string(i);
for(int i = 0; i < ts; i++)
{
lnk[i] = -1;
dp[i] = -1;
}
for(int i = 0; i < ts; i++)
{
get_lnk(i);
for(char c = 'a'; c <= 'o'; c++)
get_go(i, c);
}
for(int i = 0; i < ts; i++)
get_dp(i);
for(int i = 0; i < ts; i++)
{
for(int j = 0; j < K; j++)
{
A[i][j] = get_go(i, char('a' + j));
F[i][j] = dp[A[i][j]];
}
}
int n = s.size();
vector<int> leftQ(n, -1);
vector<int> rightQ(n, -1);
for(int i = 0; i < n; i++)
{
if(i != 0)
leftQ[i] = leftQ[i - 1];
if(s[i] == '?')
leftQ[i] = i;
}
for(int i = n - 1; i >= 0; i--)
{
if(i != n - 1)
rightQ[i] = rightQ[i + 1];
if(s[i] == '?')
rightQ[i] = i;
}
vector<int> bad(n, 0);
if(leftQ.back() == -1)
bad = vector<int>(n, 1);
long long ans = 0;
int curSt = 0;
string news = "";
for(int i = 0; i < n; i++)
{
int ci = (s[i] == '?' ? 14 : int(s[i] - 'a'));
if(bad[i])
ans += F[curSt][ci];
curSt = A[curSt][ci];
if(!bad[i])
news.push_back(s[i]);
else if(i != 0 && !bad[i - 1])
news.push_back('o');
}
if(!news.empty())
ans += solve(news);
printf("%lld\n", ans);
}
|
1328
|
A
|
Divisibility Problem
|
You are given two positive integers $a$ and $b$. In one move you can increase $a$ by $1$ (replace $a$ with $a+1$). Your task is to find the minimum number of moves you need to do in order to make $a$ divisible by $b$. It is possible, that you have to make $0$ moves, as $a$ is already divisible by $b$. You have to answer $t$ independent test cases.
|
If $a \% b = 0$ ($a$ is divisible by $b$), just print $0$. Otherwise, we need exactly $b - a \% b$ moves to make zero remainder of $a$ modulo $b$. $\%$ is modulo operation.
|
[
"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 == 0) cout << 0 << endl;
else cout << b - a % b << endl;
}
return 0;
}
|
1328
|
B
|
K-th Beautiful String
|
For the given integer $n$ ($n > 2$) let's write down all the strings of length $n$ which contain $n-2$ letters 'a' and two letters 'b' in \textbf{lexicographical} (alphabetical) order.
Recall that the string $s$ of length $n$ is lexicographically less than string $t$ of length $n$, if there exists such $i$ ($1 \le i \le n$), that $s_i < t_i$, and for any $j$ ($1 \le j < i$) $s_j = t_j$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.
For example, if $n=5$ the strings are (the order does matter):
- aaabb
- aabab
- aabba
- abaab
- ababa
- abbaa
- baaab
- baaba
- babaa
- bbaaa
It is easy to show that such a list of strings will contain exactly $\frac{n \cdot (n-1)}{2}$ strings.
You are given $n$ ($n > 2$) and $k$ ($1 \le k \le \frac{n \cdot (n-1)}{2}$). Print the $k$-th string from the list.
|
Let's try to find the position of the leftmost occurrence of 'b' (iterate over all positions from $n-2$ to $0$). If $k \le n - i - 1$ then this is the required position of the leftmost occurrence of 'b'. Then the position of rightmost occurrence is $n - k$ so we can print the answer. Otherwise, let's decrease $k$ by $n-i-1$ (remove all strings which have the leftmost 'b' at the current position) and proceed to the next position. It is obvious that in such a way we consider all possible strings in lexicographic order.
|
[
"binary search",
"brute force",
"combinatorics",
"implementation",
"math"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n, k;
cin >> n >> k;
string s(n, 'a');
for (int i = n - 2; i >= 0; i--) {
if (k <= (n - i - 1)) {
s[i] = 'b';
s[n - k] = 'b';
cout << s << endl;
break;
}
k -= (n - i - 1);
}
}
}
|
1328
|
C
|
Ternary XOR
|
A number is ternary if it contains only digits $0$, $1$ and $2$. For example, the following numbers are ternary: $1022$, $11$, $21$, $2002$.
You are given a long ternary number $x$. The first (leftmost) digit of $x$ is guaranteed to be $2$, the other digits of $x$ can be $0$, $1$ or $2$.
Let's define the ternary XOR operation $\odot$ of two ternary numbers $a$ and $b$ (both of length $n$) as a number $c = a \odot b$ of length $n$, where $c_i = (a_i + b_i) \% 3$ (where $\%$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $3$. For example, $10222 \odot 11021 = 21210$.
Your task is to find such ternary numbers $a$ and $b$ both of length $n$ and both without leading zeros that $a \odot b = x$ and $max(a, b)$ is the minimum possible.
You have to answer $t$ independent test cases.
|
Let's iterate from left to right over the digits of $x$. If the current digit is either $0$ or $2$ then we can set $a_i = b_i = 0$ or $a_i = b_i = 1$ correspondingly. There are no better choices. And if the current digit $x_i$ is $1$ then the optimal choise is to set $a_i = 1$ and $b_i = 0$. What happens after the first occurrence of $1$? Because of this choice $a$ is greater than $b$ even if all remaining digits in $b$ are $2$. So for each $j > i$ set $a_j = 0$ and $b_j = x_j$ and print the answer. The case without $1$ is even easier and in fact we handle it automatically.
|
[
"greedy",
"implementation"
] | 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;
string x;
cin >> n >> x;
string a(n, '0'), b(n, '0');
for (int i = 0; i < n; ++i) {
if (x[i] == '1') {
a[i] = '1';
b[i] = '0';
for (int j = i + 1; j < n; ++j) {
b[j] = x[j];
}
break;
} else {
a[i] = b[i] = '0' + (x[i] - '0') / 2;
}
}
cout << a << endl << b << endl;
}
return 0;
}
|
1328
|
D
|
Carousel
|
The round carousel consists of $n$ figures of animals. Figures are numbered from $1$ to $n$ in order of the carousel moving. Thus, after the $n$-th figure the figure with the number $1$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $i$-th figure equals $t_i$.
\begin{center}
{\small The example of the carousel for $n=9$ and $t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$}.
\end{center}
You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.
Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $k$ distinct colors, then the colors of figures should be denoted with integers from $1$ to $k$.
|
The answer to this problem is at most $3$. Let's prove it by construction. Firstly, if all $t_i$ are equal then the answer is $1$. Otherwise, there are at least two different values in the array $t$ so the answer is at least $2$. If $n$ is even then the answer is always $2$ because you can color figures in the following way: $[1, 2, 1, 2, \dots, 1, 2]$. If $n$ is odd then consider two cases. The first case is when some pair of adjacent figures have the same type. Then the answer is $2$ because you can merge these two values into one and get the case of even $n$. Otherwise, all pairs of adjacent figures have different types and if you consider this cyclic array as a graph (cycle of length $n$) then you can notice that it isn't bipartite so you need at least $3$ colors to achieve the answer (color all vertices in such a way that any two adjacent vertices have different colors). And the answer looks like $[1, 2, 1, 2, \dots, 1, 2, 3]$.
|
[
"constructive algorithms",
"dp",
"graphs",
"greedy",
"math"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
if (count(a.begin(), a.end(), a[0]) == n) {
cout << 1 << endl;
for (int i = 0; i < n; ++i) {
cout << 1 << " ";
}
cout << endl;
return 0;
}
if (n % 2 == 0) {
cout << 2 << endl;
for (int i = 0; i < n; ++i) {
cout << i % 2 + 1 << " ";
}
cout << endl;
return 0;
}
for (int i = 0; i < n; ++i) {
if (a[i] == a[(i + 1) % n]) {
vector<int> ans(n);
for (int j = 0, pos = i + 1; pos < n; ++pos, j ^= 1) {
ans[pos] = j + 1;
}
for (int j = 0, pos = i; pos >= 0; --pos, j ^= 1) {
ans[pos] = j + 1;
}
cout << 2 << endl;
for (int pos = 0; pos < n; ++pos) {
cout << ans[pos] << " ";
}
cout << endl;
return 0;
}
}
cout << 3 << endl;
for (int i = 0; i < n - 1; ++i) {
cout << i % 2 + 1 << " ";
}
cout << 3 << endl;
return 0;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int qq = 0; qq < q; qq++) {
solve();
}
return 0;
}
|
1328
|
E
|
Tree Queries
|
You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$.
A tree is a connected undirected graph with $n-1$ edges.
You are given $m$ queries. The $i$-th query consists of the set of $k_i$ distinct vertices $v_i[1], v_i[2], \dots, v_i[k_i]$. Your task is to say if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path.
|
Firstly, let's choose some deepest (farthest from the root) vertex $fv$ in the query (among all such vertices we can choose any). It is obvious that every vertex in the query should either belong to the path from the root to $fv$ or the distance to some vertex of this path should be at most one. Now there are two ways: write some LCA algorithms and other hard stuff which is unnecessary in this problem or write about $15$ lines of code and solve the problem. Let's take every non-root vertex (except $fv$) and replace it with its parent. So, what's next? Now the answer is "YES" if each vertex (after transformation) belongs to the path from root to $fv$. Now we just need to check if it is true. We can do this using the very standard technique: firstly, let's run dfs from the root and calculate for each vertex the first time we visited it ($tin$) and the last time we visited it ($tout$). We can do this using the following code: Initially, $T$ equals zero. Now we have a beautiful structure giving us so much information about the tree. Consider all segments $[tin_v; tout_v]$. We can see that there is no pair of intersecting segments. The pair of segments $[tin_v; tout_v]$ and $[tin_u; tout_u]$ is either non-intersecting at all or one segment lies inside the other one. The second beautiful fact is that for each vertex $u$ in the subtree of $v$ the segment $[tin_u; tout_u]$ lies inside the segment $[tin_v; tout_v]$. So, we can check if one vertex is the parent of the other: the vertex $v$ is the parent of the vertex $u$ if and only if $tin_v \le tin_u$ and $tout_u \le tout_v$ (the vertex is the parent of itself). How do we check if the vertex $u$ lies on the path from the root to the vertex $fv$? It lies on this path if the root is the parent of $u$ (it is always true) and $u$ is the parent of $fv$. This approach can be used for each vertical path (such a path from $x$ to $y$ that $lca(x, y)$ is either $x$ or $y$). Time complexity: $O(n + m)$.
|
[
"dfs and similar",
"graphs",
"trees"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
int T;
vector<int> p, d;
vector<int> tin, tout;
vector<vector<int>> g;
void dfs(int v, int par = -1, int dep = 0) {
p[v] = par;
d[v] = dep;
tin[v] = T++;
for (auto to : g[v]) {
if (to == par) continue;
dfs(to, v, dep + 1);
}
tout[v] = T++;
}
bool isAnc(int v, int u) {
return tin[v] <= tin[u] && tout[u] <= tout[v];
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m;
cin >> n >> m;
T = 0;
p = d = vector<int>(n);
tin = tout = 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);
}
dfs(0);
for (int i = 0; i < m; ++i) {
int k;
cin >> k;
vector<int> v(k);
for (auto &it : v) {
cin >> it;
--it;
}
int u = v[0];
for (auto it : v) if (d[u] < d[it]) u = it;
for (auto &it : v) {
if (it == u) continue;
if (p[it] != -1) it = p[it];
}
bool ok = true;
for (auto it : v) ok &= isAnc(it, u);
if (ok) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
|
1328
|
F
|
Make k Equal
|
You are given the array $a$ consisting of $n$ elements and the integer $k \le n$.
You want to obtain \textbf{at least} $k$ equal elements in the array $a$. In one move, you can make one of the following two operations:
- Take \textbf{one} of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $a$ is $mn$ then you choose such index $i$ that $a_i = mn$ and set $a_i := a_i + 1$);
- take \textbf{one} of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $a$ is $mx$ then you choose such index $i$ that $a_i = mx$ and set $a_i := a_i - 1$).
Your task is to calculate the minimum number of moves required to obtain \textbf{at least} $k$ equal elements in the array.
|
This problem is just all about the implementation. Firstly, let's sort the initial values and compress them to pairs $(i, cnt[val])$, where $cnt[val]$ is the number of elements $val$. The first observation is pretty standard and easy: some equal elements will remain unchanged. So let's iterate over all elements $val$ in some order and suppose that all elements $val$ will remain unchanged. Firstly, we need $need = max(0, k - cnt[val])$ elements which we should obtain by some moves. The second observation is that we first need to take elements from one end (only less or only greater) and only then from the other (if needed). Consider the case when we first take less elements. The other case is almost symmetric. Let $needl = min(need, prefcnt_{prv})$ be the number of less than $val$ which we need to increase to $val$. If $needl = 0$ then skip the following step. Otherwise, let $prefcnt_i$ be the number of elements less than or equal to $i$, $prefsum_i$ be the sum of all elements less than or equal to $i$ and $prv$ be the previous value (the maximum value less than $val$). Then we need to increase all elements less than or equal to $prv$ at least to the value $val-1$. It costs $(val - 1) \cdot prefcnt_{prv} - prefsum_{prv}$ moves. And then we need $needl$ moves to increase $needl$ elements to $val$. And let $needr = max(0, need - needl)$ be the number of elements greater than $val$ which we need to decrease to $val$ if we increased $needl$ elements already. If $needr = 0$ then skip the following step. Otherwise, let $sufcnt_i$ be the number of elements greater than or equal to $i$, $prefsum_i$ be the sum of all elements greater than or equal to $i$ and $nxt$ be the next value (the minimum value greater than $val$). Then we need to decrease all elements greater than or equal to $prv$ at least to the value $val+1$. It costs $sufsum_{nxt} - (val + 1) \cdot sufcnt_{nxt}$ moves. And then we need $needr$ moves to decrease $needr$ elements to $val$. So we can update the answer with the sum of values described above and proceed to the next value. Arrays $prefcnt, sufcnt, prefsum, sufsum$ are just simple prefix and suffix sums which can be calculated in $O(n)$ using very standard and easy dynamic programming. Don't forget about the overflow. Total time complexity: $O(n \log n)$ because of sorting.
|
[
"greedy"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
const long long INF64 = 1e18;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector<int> a(n);
for (auto &it : a) cin >> it;
sort(a.begin(), a.end());
vector<pair<int, int>> cnt;
for (auto it : a) {
if (cnt.empty() || cnt.back().first != it) {
cnt.push_back({it, 1});
} else {
++cnt.back().second;
}
}
vector<long long> prefsum, sufsum;
vector<int> prefcnt, sufcnt;
for (int i = 0; i < int(cnt.size()); ++i) {
long long cursum = cnt[i].first * 1ll * cnt[i].second;
int curcnt = cnt[i].second;
if (prefsum.empty()) {
prefsum.push_back(cursum);
prefcnt.push_back(curcnt);
} else {
prefsum.push_back(prefsum.back() + cursum);
prefcnt.push_back(prefcnt.back() + curcnt);
}
}
for (int i = int(cnt.size()) - 1; i >= 0; --i) {
long long cursum = cnt[i].first * 1ll * cnt[i].second;
int curcnt = cnt[i].second;
if (sufsum.empty()) {
sufsum.push_back(cursum);
sufcnt.push_back(curcnt);
} else {
sufsum.push_back(sufsum.back() + cursum);
sufcnt.push_back(sufcnt.back() + curcnt);
}
}
reverse(sufsum.begin(), sufsum.end());
reverse(sufcnt.begin(), sufcnt.end());
long long ans = INF64;
for (int i = 0; i < int(cnt.size()); ++i) {
int cur = max(0, k - cnt[i].second);
int needl = 0;
if (i > 0) needl = min(cur, prefcnt[i - 1]);
int needr = max(0, cur - needl);
long long res = 0;
if (i > 0 && needl > 0) {
res += prefcnt[i - 1] * 1ll * (cnt[i].first - 1) - prefsum[i - 1];
res += needl;
}
if (i + 1 < int(cnt.size()) && needr > 0) {
res += sufsum[i + 1] - sufcnt[i + 1] * 1ll * (cnt[i].first + 1);
res += needr;
}
ans = min(ans, res);
needr = 0;
if (i + 1 < int(cnt.size())) needr = min(cur, sufcnt[i + 1]);
needl = max(0, cur - needr);
res = 0;
if (i > 0 && needl > 0) {
res += prefcnt[i - 1] * 1ll * (cnt[i].first - 1) - prefsum[i - 1];
res += needl;
}
if (i + 1 < int(cnt.size()) && needr > 0) {
res += sufsum[i + 1] - sufcnt[i + 1] * 1ll * (cnt[i].first + 1);
res += needr;
}
ans = min(ans, res);
}
cout << ans << endl;
return 0;
}
|
1329
|
A
|
Dreamoon Likes Coloring
|
Dreamoon likes coloring cells very much.
There is a row of $n$ cells. Initially, all cells are empty (don't contain any color). Cells are numbered from $1$ to $n$.
You are given an integer $m$ and $m$ integers $l_1, l_2, \ldots, l_m$ ($1 \le l_i \le n$)
Dreamoon will perform $m$ operations.
In $i$-th operation, Dreamoon will choose a number $p_i$ from range $[1, n-l_i+1]$ (inclusive) and will paint all cells from $p_i$ to $p_i+l_i-1$ (inclusive) in $i$-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.
Dreamoon hopes that after these $m$ operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose $p_i$ in each operation to satisfy all constraints.
|
After reading the statement, you may find this is a problem that will be tagged as "constructive algorithms" in Codefores. And you also can find this problem is just problem A in Div. 1. So basically we can expect there exist some simple methods to solve it. If a "constructive algorithms" problem asks you to determine whether the solution exists or not, usually they have a common pattern(especially in problem hardness which is before Div. 1 B(inclusive)), this is, there are some simple constraints can divide test data into "Yes", and "No". Therefore, the first thing to solve this problem is finding some trivial conditions that cannot achieve Dreamoon's hope. After some try, you may find there are two trivial conditions that achieving Dreamoon's hope is impossible. The two conditions are listed as follows: 1. Sum of $l_i$ is less than $n$. In this condition, there always is at least one empty grid. 2. There exists some $i$ such that $l_i + i - 1 > n$. If $n - l_i < i - 1$, it means after you do $i$-th operation, there only $n - l_i$ grid is not colored by $i$-th color. So at least one of previous $i-1$ color will disapear after this operation. Now I want to talk about another feature of some "constructive algorithms" first. Sometimes, the condition given by the problem is to "open", this is to say that if we added some more strict constraint, the problem is still can be solved. And when the constraint it more strict, we can deduce the solution more easily. One of common "strict constraint" is "sorted". I believe you have ever seen many problems that the first step is sorting something. Now, we also want to apply "sorted" in the problem. After applying "sort", we firstly consider the edge cases of above two impossible conditions. The first case is "sum of $l_i$ is equal to $n$". In this case, we have a unique solution after applying "sort", $p_i = m - \sum\limits_{j=i+1}^{m} l_j + 1$. The second case is $l_i + i - 1 = n$ is hold for all $i$. In this case, there is also a unique solution that $p_i = i$. The two cases coressond to $n$ is largest and $n$ is smallest among all $n$ that exist solutions for same $l_i$. And for same $l_i$, when we decrase $n$ from the largest possible value, we can just change $p_i$ from $m - \sum\limits_{j=i+1}^{m} l_j + 1$ to $i$ for some smallest indices $i$ to get solution. To sum it up, finally, we get the answer. The answer is just $p_i = \max(i, n - suffix\_sum[i] + 1)$, for each $i$. There exist many other methods to construct solutions. I believe the construction method one can think out is relative to the study experience.
|
[
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,800
|
#include<bits/stdc++.h>
const int SIZE = 100002;
int len[SIZE];
long long suffix_sum[SIZE];
void err() {puts("-1");}
void solve() {
int N, M;
scanf("%d%d", &N, &M);
for(int i = 1; i <= M; i++) {
scanf("%d", &len[i]);
if(len[i] + i - 1 > N) {
err();
return;
}
}
for(int i = M; i > 0; i--) {
suffix_sum[i] = suffix_sum[i + 1] + len[i];
}
if(suffix_sum[1] < N) {
err();
return;
}
for(int i = 1; i <= M; i++) {
printf("%lld", std::max((long long)i, N - suffix_sum[i] + 1));
if(i < M) putchar(' ');
else puts("");
}
}
int main() {
solve();
return 0;
}
|
1329
|
B
|
Dreamoon Likes Sequences
|
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:
You are given two integers $d, m$, find the number of arrays $a$, satisfying the following constraints:
- The length of $a$ is $n$, $n \ge 1$
- $1 \le a_1 < a_2 < \dots < a_n \le d$
- Define an array $b$ of length $n$ as follows: $b_1 = a_1$, $\forall i > 1, b_i = b_{i - 1} \oplus a_i$, where $\oplus$ is the bitwise exclusive-or (xor). After constructing an array $b$, the constraint $b_1 < b_2 < \dots < b_{n - 1} < b_n$ should hold.
Since the number of possible arrays may be too large, you need to find the answer modulo $m$.
|
Firstly, we define a function $h(x)$ as the position of the highest bit which is set to 1 in a positive integer $x$. For example, $h(1) = 0, h(2) = h(3) = 1$, and $h(4) = h(7) = 2$. If the constraints in this problem is satisfied, there is some observations, $h(a_i) = h(b_i)$ and $h(a_i)$ must less than $h(a_{i+1})$. And luckily, if $h(a_i) < h(a_{i+1})$ is always hold, the constraints in this problem will also be satisfied (Please prove them by yourself or wait for someone prove it in comments : ) P.S. the link of proof written by someone is int the end. ) In other words, for each non-negative integer $v$, there is at most one $i$ such that $h(a_i) = v$. This is, at most one of the positive numbers in range $[2^v, min(2^{(v+1)}-1,d)]$ can occur in $a_i$. In each non-empty range, we can choose one integer in it or don't choose anyone. So for each of them we have $min(2^{(v+1)}-1,d) - 2^v + 2$ different choice. Then according to the rule of product, we can multiply all number of choices for different $v$ and minus the value by one to get the answer. For example, when d = 6, there are $2$ choices for $v = 0$, $3$ choices for $v=1$, $4$ choices for $v=2$. So the answer for $d = 6$ is $2 \times 3 \times 4 - 1 = 23$. UPD: onthefloor provides proof for what I mention here.
|
[
"bitmasks",
"combinatorics",
"math"
] | 1,700
|
#include<bits/stdc++.h>
void solve(){
int d, m;
scanf("%d%d",&d, &m);
long long answer=1;
for(int i = 0; i < 30; i++) {
if(d < (1 << i)) break;
answer = answer * (std::min((1 << (i+1)) - 1, d) - (1 << i) + 2) % m;
}
answer--;
if(answer < 0) answer += m;
printf("%lld\n",answer);
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
solve();
}
}
|
1329
|
C
|
Drazil Likes Heap
|
Drazil likes heap very much. So he created a problem with heap:
There is a max heap with a height $h$ implemented on the array. The details of this heap are the following:
This heap contains exactly $2^h - 1$ \textbf{distinct} positive non-zero integers. All integers are distinct. These numbers are stored in the array $a$ indexed from $1$ to $2^h-1$. For any $1 < i < 2^h$, $a[i] < a[\left \lfloor{\frac{i}{2}}\right \rfloor]$.
Now we want to reduce the height of this heap such that the height becomes $g$ with exactly $2^g-1$ numbers in heap. To reduce the height, we should perform the following action $2^h-2^g$ times:
Choose an index $i$, which contains an element and call the following function $f$ in index $i$:
Note that we suppose that if $a[i]=0$, then index $i$ don't contain an element.
After all operations, the remaining $2^g-1$ element must be located in indices from $1$ to $2^g-1$. Now Drazil wonders what's the minimum possible sum of the remaining $2^g-1$ elements. Please find this sum and find a sequence of the function calls to achieve this value.
|
The property of heap we concern in this problem mainly are: 1. The tree is a binary tree, each node has a weight value. 2. The weight of a node is always larger than the weight of its children. 3. We use $a[I]$ to record the weight of vertex $i$, and the number of its children are $2 \times i$ and vertex $2 \times i + 1$ (if exist). Another key point we should consider seriously is before all operations and after all operations, the tree must be a perfect binary tree. Many contestants didn't notice the constraint during the contest. I think there are two different thinking directions for this problem. One is considering node from bottom to top. Another one is considering node from top to bottom. For me, from bottom to top is more intuitive. Now we talk about "from bottom to top" first, it means we consider node from larger index to smaller index in the tree after all operations (call it final tree after). For the leaves in the final tree, it's not hard to know, the minimum possible final weight of each leaf is the minimum weight of nodes in its subtree before all operations (call it beginning tree after). For the other nodes in the final tree, its weight must satisfy two constraints, one is it should be larger than the final weight of his children, another is the weight should exist in its subtree of the beginning tree. Luckily, these lower bounds are all constraints we should consider to get the answer. For each leaf in the final tree, we maintain a data structure that stores all weight of its subtree in the beginning tree. Then the minimum value in this data structure is its final weight. For other nodes in the final tree, we merge the two data structures of its children. the remove all value which is less than the final weight of his children. There are many data structure can do these operations, such as min heap(author's code) or sorted array(isaf27's code). With the above method, we get the minimum possible sum of the remaining $2^g-1$ elements. But we still don't know how to construct it. All we know is which weight values are reaming in the final tree. Now I want to prove that no matter how the order I call the function $f$, if the remaining weight values set is the same, the final shape of the final tree will be the same. This time I prove it from top to bottom. We only know which weight values set to remain in the final, Then We iterate node from smallest index to the larger one. We always can determine the weight value of the iterated node, because the weight value only can be the maximum value in its subtree. This trait also can let us know that the final tree we get in our method is a perfect binary tree. Conclude all things above. after we can apply the function $f$ from bottom to top on these nodes with weight value doesn't exist in the final tree. In the "from bottom to top" method, it has some thinking level difference between calculating the minimum sum and constructing a list of possible operations. So I determine let competitors output the operations. - - - Now we talk about the "from top to bottom" method. The main idea of this method is iterating index from $1$ to $2^g-1$ and in each iteration, applying the function $f$ on $i$-th node until the shape of the final tree is impossible to become a perfect binary tree. The method is quite easy to write and almost has no difference when asking you to output the operations. But I think it's hard to prove. Evenly, I think the solution should be wrong until I write this solution and test it. Firstly I want to prove the minimum possible final weight value of node $1$ is the same as the above "from top to bottom" method get. We call the value as $mi_1$. If some algorithm $B$ can get more small weight value in the final tree, It means all weight values which are not smaller than $mi_1$ disappear. But according to the conclusion "if the remaining weight values set is the same, the final shape of the final tree will be the same.". the final tree generated by $B$ can also get with firstly applying the function $f$ on node $1$ at least one more time than above "from top to bottom" algorithm, and do some other operations. But it will make the final tree is impossible to be the perfect binary tree. Now we disprove it. Now we want to prove the final weight value of node $i$($i>1$) is the same as the above "from top to bottom" method get. Only when applying function $f$ on ancestors and descendants of node $i$ will affect the final weight value of node $i$. And when we apply on its ancestors, the $f$ may recursively apply $f$ on $it$ at most once. So each time $f$ applies on its ancestors is equivalent to apply on itself once or do nothing. Therefore, The proof can be don as what we do on node $1$ just by only considering the subtree of node $i$. Now, we have proved the "top to bottom" algorithm can make each node of the final tree has the minimum possible weight value. When I found the "top to bottom" algorithm during preparing the contest, I ever consider changing the problem to something else because the method is too easy to guess and to write. But I have no other more proper problem that can be used. It's a little pity for me. a super simple solution which is differet to this blog provided by Swistakk.
|
[
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
const int SIZE = 1<<20;
int INF = 1000000001;
int a[SIZE], ops[SIZE];
int h, g;
int qq[24], qn;
int pull(int id) {
int tmp = a[id];
a[id] = 0;
qn = 0;
qq[qn++] = id;
while(id * 2 < (1 << h) && a[id] < max(a[id<<1], a[(id<<1)|1])) {
if(a[id<<1] > a[(id << 1) | 1]) {
swap(a[id<<1], a[id]);
id <<= 1;
}
else {
swap(a[(id<<1)|1], a[id]);
id = (id << 1) | 1;
}
qq[qn++] = id;
}
if(id < (1 << g)) {
for(int i = qn - 1; i > 0; i--) {
a[qq[i]] = a[qq[i - 1]];
}
a[qq[0]] = tmp;
return 0;
}
return tmp;
}
void solve() {
scanf("%d%d", &h, &g);
long long an = 0;
for(int i = 1; i < (1 << h); i++) {
scanf("%d", &a[i]);
an += a[i];
}
int need = 0;
for(int i = 1; i < (1 << g); i++) {
while(1) {
int v = pull(i);
if(v) {
an -= v;
ops[need++] = i;
}
else break;
}
}
printf("%lld\n", an);
for(int i = 0; i < need; i++) printf("%d%c", ops[i], " \n"[i == need - 1]);
}
int main(){
int T;
scanf("%d", &T);
while(T--) solve();
return 0;
}
|
1329
|
D
|
Dreamoon Likes Strings
|
Dreamoon likes strings. Today he created a game about strings:
String $s_1, s_2, \ldots, s_n$ is \textbf{beautiful} if and only if for each $1 \le i < n, s_i \ne s_{i+1}$.
Initially, Dreamoon has a string $a$. In each step Dreamoon can choose a \textbf{beautiful} substring of $a$ and remove it. Then he should concatenate the remaining characters (in the same order).
Dreamoon wants to use the smallest number of steps to make $a$ empty. Please help Dreamoon, and print any sequence of the smallest number of steps to make $a$ empty.
|
Denoting a string of length two which contains two $i$-th letter as $t_i$. For example, $t_0$ is "aa", $t_1$ is "bb" . And let $c_i$ be the occurrence count of $t_i$ as a substring in $a$. For example, when $a =$ "aaabbcaa", $c_0 = 3, c_1 = 1$, and for other $i$, $c_i = 0$. In this problem, if only asking contestants output the smallest number of steps to make $a$ empty, the answer is simple. You just need to output $\max(\left \lceil\frac{\sum c_i}{2} \right\rceil,\max_{0 \le i \le 25}\limits{c_i})+1$. (I will call this fomula for a given string $a$ as $f(a)$ behind.) Firstly, let's see how the value of all $c_i$ change in one step. There are only four kinds of possible change for all $c_i$. 1. For some $i$, $c_i$ is decreased by one. For example, deleting the first two letters of "abb". 2. For two different values $i$ and $j$. $c_i$ and $c_j$ are both decrease by one. For example, deleting the second and third letter of "aabb". 3. Nothing changes for all $c_i$. For example, deleting the first letter from "abb". 4. For some $i$, $c_i$ is added by one. For example, deleting the second letter from "aba". Now, Let's consider how will these changes affect the $f(a)$. Amazing! All possible changes will decrease the value of $f(a)$ at most one! So if we can construct an algorithm to achieve it, then we solve it. Now I introduce an algorithm of which time complexity is $O(n)$. The algorithm can be divided into three phases. 1. In this phase, we maintain a stack that stores the position of substring $t_i$ in the current string from left to right. When we iterate to a string $t_i$, there are two cases. Assum the top element in the stack is $t_j$. When $i$ is equal to $j$, we just add t_i into the stack. But if $i \ne j$, we do a step that removing all letters from the second letter of $t_j$ to the first letter of $t_i$. and pop $t_j$ from the stack. If there is any moment that $\left \lceil\frac{\sum c_i}{2} \right\rceil \le \max_{0 \le i \le 25}\limits{c_i})+1$ is hold (So maybe you won't do anything in this phase), the phase will be terminated. 2. In this phase, there must be an unique $x$ satisifying $c_x \ge \left \lceil\frac{\sum c_i}{2} \right\rceil$. we also maintain a stack that stores the position of substring $t_i$ in the current string from left to right. But when we iterate to a string $t_i$, the action we should do are different from the first phase. Assum the top element in the stack is $t_j$. When there is exactly one number among $i$ and $j$ is $x$, we do a step that removing all letters from the second letter of $t_j$ to the first letter of $t_i$. and pop $t_j$ from the stack. Otherwise, we just add $t_i$ into the stack. 3. When the algorithm enters the phase, for all $i$ except $x$, $c_i$ will be $0$. So we can use all occurrence of $t_x$ to divide the string into $c_x+1$ segment and remove each segment one by on. After that the string will become empty. Please see the reference code for the implementation detail.
|
[
"constructive algorithms",
"data structures"
] | 3,100
|
#include<bits/stdc++.h>
using namespace std;
const int SIZE = 2e5+10;
char s[SIZE];
int cnt[SIZE];
int cc[26];
int all_cnt;
int ma;
void update_ma() {
while(ma > 0 && !cnt[ma]) ma--;
}
void dec1(int id) {
cnt[cc[id]]--;
cc[id]--;
cnt[cc[id]]++;
}
pair<int, int> stk[SIZE];
int sn;
int m;
int now;
int last_len;
void add(int i, bool flag) {
if(flag) {
dec1(stk[sn - 1].second);
dec1(stk[i].second);
all_cnt -= 2;
printf("%d %d\n",now + 1, now + stk[i].first);
update_ma();
sn--;
now -= stk[sn].first;
if(i + 1 < m) {
stk[i + 1].first += stk[sn].first;
}
else{
last_len += stk[sn].first;
}
}
else {
stk[sn++] = stk[i];
now += stk[i].first;
}
}
void solve(){
scanf("%s", s);
int n = strlen(s);
all_cnt = 0;
int lt = 0;
m = 0;
for(int i = 1; i < n; i++) {
if(s[i] == s[i - 1]) {
cc[s[i] - 'a']++;
all_cnt++;
stk[m++] = make_pair(i - lt, (int)(s[i] - 'a'));
lt = i;
}
}
last_len = n - lt;
ma = 0;
for(int i = 0; i < 26; i++) {
cnt[cc[i]]++;
ma = max(ma, cc[i]);
}
printf("%d\n", 1 + max(ma, (all_cnt + 1) / 2));
if(ma * 2 < all_cnt) {
sn = now = 0;
for(int i = 0; i < m; i++) {
add(i, sn && stk[sn - 1].second != stk[i].second && ma * 2 < all_cnt);
}
m = sn;
}
int main_id = -1;
for(int i = 0; i < 26; i++) {
if(cc[i] == ma) main_id = i;
}
sn = now = 0;
for(int i = 0; i < m; i++) {
add(i, sn && ((stk[sn - 1].second == main_id) ^ (stk[i].second == main_id)));
}
for(int i = 0; i < sn; i++) {
printf("%d %d\n",1 ,stk[i].first);
}
printf("%d %d\n", 1, last_len);
memset(cc, 0, sizeof(cc));
memset(cnt, 0, sizeof(int) * (ma + 1));
}
int main(){
int T;
scanf("%d", &T);
for(int i = 1; i <= T; i++) solve();
return 0;
}
|
1329
|
E
|
Dreamoon Loves AA
|
There is a string of length $n+1$ of characters 'A' and 'B'. The first character and last character of the string are equal to 'A'.
You are given $m$ indices $p_1, p_2, \ldots, p_m$ ($0$-indexation) denoting the other indices of characters 'A' in the string.
Let's denote the minimum distance between two neighboring 'A' as $l$, and maximum distance between neighboring 'A' as $r$.
For example, $(l,r)$ of string "ABBAABBBA" is $(1,4)$.
And let's denote the \textbf{balance degree} of a string as the value of $r-l$.
Now Dreamoon wants to change exactly $k$ characters from 'B' to 'A', and he wants to make the \textbf{balance degree} of the string as small as possible.
Please calculate the required minimum possible value of balance degree.
|
The idea of this problem comes to my brain when I recall that I'm cooking and I want to cut a carrot into many pieces and make the size of each piece as evenly as possible. I think this problem is very interesting. So that's why I determine to prepare a Codeforces contest after so many years. I hope I can share this problem with as many people as possible. There are some methods to solve this problem. I only show the most beautiful one below. This method is given by isaf27 (And most AC users solve it with this method. I admire them very much). Firstly, we translate the problem into a more convenient model. Let $p_{m+1} = n$, $a_i = p_i - p_{i-1}$ ($1 \le i \le m+1$), $M = m + 1$, and $K = m + 1 + k$. Then the problem is equivalent to we want to do integer partition on $M$ integers $a_1, a_2, \ldots, a_M$, such that $a_i$ is divided into $d_i$ positive integers where $\sum d_i = K$. Our target is to minimize the difference between the largest integer and smallest integer after division. An important observation is, we always can achieve our target by making the difference of the largest integer and the smallest integer that is divided from the same integer is at most one. So our target is minimizing $\max_{1 \le i \le M}\limits{(\left\lceil \frac{a_i}{d_i} \right \rceil)} - \min_{1 \le i \le M}\limits{(\left\lfloor \frac{a_i}{d_i} \right \rfloor)}$ where $1 \le d_i$ and $\sum_{i=1 \sim M}\limits d_i = K$. There are two key values under the constraints $1 \le d_i$ and $\sum_{i=1 \sim M}\limits d_i = K$, one is the minimum value of $\max_{1 \le i \le M}\limits{(\left\lceil \frac{a_i}{d_i} \right \rceil)}$ (Let's call it $U$ after), another is the maximum value of $\min_{1 \le i \le M}\limits{(\left\lfloor \frac{a_i}{d_i} \right \rfloor)}$ (Let's call it $D$ after). $L$ and $U$ can be calculated by binary searching with time complexity $O(M log M)$. (This part is relatively easy so I won't mention it here.) There are two conditions after calculating $L$ and $U$. One is, for all valid $i$, there exists at least one positive integer $d_i$ such that $L \le \left\lfloor \frac{a_i}{d_i} \right \rfloor \le \left\lceil \frac{a_i}{d_i} \right \rceil \le U$. In this case, the answer is just $U - L$. proof is as below. Let $du_i$ as the largest positive integer such that $L \le \left\lfloor \frac{a_i}{d_i} \right \rfloor$ and $dl_i$ as the smallest positive integer such that $\left\lceil \frac{a_i}{d_i} \right \rceil \le U$. By the define of $L$ and $U$, we can get $\sum\limits_{i=1 \sim M} du_i \ge K$ and $\sum\limits_{i=1 \sim M} dl_i \le K$. So we always can choose some d_i where $d_l \le d_i \le d_u$ such that $\sum\limits_{i=1 \sim M} d_i = K$ and $L \le \left\lfloor \frac{a_i}{d_i} \right \rfloor \le \left\lceil \frac{a_i}{d_i} \right \rceil \le U$. Now the essential condition is resolved. Another condition is there are some indices $i$ that we cannot find any positive integer $d_i$ such that $L \le \left\lfloor \frac{a_i}{d_i} \right \rfloor \le \left\lceil \frac{a_i}{d_i} \right \rceil \le U$. Let's call the set of these indices as $I$. For each element $j \in I$, let's calculate another two key values for index $j$. That is, we want to know the closest two values of $\frac{a_j}{d_j}$ near to range $[L, U]$ (one is above $[L,U]$ another is below $[L,U]$). Formulaically say, let $v$ be the smallest $d_j$ such that $\left\lfloor \frac{a_j}{d_j} \right \rfloor < L$ and call $\left\lfloor \frac{a_j}{v} \right \rfloor$ as $x_j$. And let $u$ be the largest $d_j$ such that $\left\lceil \frac{a_j}{d_j} \right \rceil > U$ and call $\left\lceil \frac{a_j}{u} \right \rceil$ as $y_j$. Imaging we have a set $S$ initially contains two positive integer $L$ and $U$. Now for each $j \in I$, we want to choose either $x_i$ or $y_i$ to add to $S$. Then the minimum possbile value of difference between largest element and smallest element in $S$ is the answer in this condition. The minimum possible value can be calculated as below. Initially, for all $j \in I$, we choose $y_j$ to add to the set $S$. Then iterate from largest $y_j$ to smallest $y_j$. In each iteration, we remove $y_j$ from $S$ and add $x_j$ to $S$. The minimum possible value will exist during the process. These steps can also be done in time complexity $O(M log M)$. The proof of correctness of the second condition is almost same as the first condition. We always can adjust $d_i$ such that $\sum\limits_{i=1 \sim M} d_i$ equal to $K$ for constructed result. The overall time complexity is $O(m log m)$ for the above method. In the end, I want to thanks everyone who takes part in this contest. The worth of the contest will reveal on you, when you learn thing from these problems. Thanks a lot.
|
[
"binary search",
"greedy"
] | 3,300
|
/*{{{*/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<iostream>
#include<sstream>
#include<set>
#include<map>
#include<queue>
#include<bitset>
#include<vector>
#include<limits.h>
#include<assert.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define FORS(I, S) for (int I = 0; S[I]; ++I)
#define RS(X) scanf("%s", (X))
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define CASET int ___T; scanf("%d", &___T); for(int cs=1;cs<=___T;cs++)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define F first
#define S second
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef vector<PII> VPII;
typedef pair<LL,LL> PLL;
typedef vector<PLL> VPLL;
template<class T> void _R(T &x) { cin >> x; }
void _R(int &x) { scanf("%d", &x); }
void _R(LL &x) { scanf("%lld", &x); }
void _R(double &x) { scanf("%lf", &x); }
void _R(char &x) { scanf(" %c", &x); }
void _R(char *x) { scanf("%s", x); }
void R() {}
template<class T, class... U> void R(T &head, U &... tail) { _R(head); R(tail...); }
template<class T> void _W(const T &x) { cout << x; }
void _W(const int &x) { printf("%d", x); }
void _W(const LL &x) { printf("%lld", x); }
void _W(const double &x) { printf("%.16f", x); }
void _W(const char &x) { putchar(x); }
void _W(const char *x) { printf("%s", x); }
template<class T,class U> void _W(const pair<T,U> &x) {_W(x.F); putchar(' '); _W(x.S);}
template<class T> void _W(const vector<T> &x) { for (auto i = x.begin(); i != x.end(); _W(*i++)) if (i != x.cbegin()) putchar(' '); }
void W() {}
template<class T, class... U> void W(const T &head, const U &... tail) { _W(head); putchar(sizeof...(tail) ? ' ' : '\n'); W(tail...); }
#ifdef HOME
#define DEBUG(...) {printf("# ");printf(__VA_ARGS__);puts("");}
#else
#define DEBUG(...)
#endif
int MOD = 1e9+7;
void ADD(LL& x,LL v){x=(x+v)%MOD;if(x<0)x+=MOD;}
/*}}}*/
const int SIZE = 1e6+10;
LL a[SIZE],num[SIZE];
bool done[SIZE],be_added[SIZE];
int n;
LL K;
LL get_upper_bound(int i){
LL v=a[i]/num[i];
if(v*num[i]!=a[i])v++;
return v;
}
LL get_next_upper_bound(int i){
LL v=a[i]/(num[i]-1);
if(v*(num[i]-1)!=a[i])v++;
return v;
}
LL go(){
if(K==n){
return a[n-1]-a[0];
}
LL ll=1,rr=a[n-1];
while(ll<rr){
LL mm=(ll+rr)/2;
LL need=0;
REP(i,n){
if(a[i]>mm)need+=a[i]/mm;
else need++;
}
if(need>=K)ll=mm+1;
else rr=mm;
}
LL low=ll;
VPLL pp;
LL need=0;
REP(i,n){
if(a[i]>=low){
num[i]=a[i]/low;
pp.PB({a[i]/(num[i]+1),i});
}
else {
num[i]=1;
}
need+=num[i];
}
{
bool fail=0;
REP(i,n){
if(get_upper_bound(i)>=low){
fail=1;
break;
}
}
if(!fail) return low-1-min(low-1,a[0]);
}
REP(i,n){
if(a[i]>=low&&a[i]/(num[i]+1)==low-1){
LL v=a[i]/(low-1);
LL mi=min(v-num[i],K-need);
num[i]+=mi;
need+=mi;
if(need==K)break;
}
}
priority_queue<PLL,VPLL,greater<PLL>>added;
priority_queue<PLL>top;
LL mi=a[0];
REP(i,n){
if(num[i]>1){
added.push(MP(get_next_upper_bound(i),i));
}
top.push(MP(get_upper_bound(i),i));
mi=min(mi,a[i]/num[i]);
}
LL an=top.top().F-mi;
REP(i,n)be_added[i]=done[i]=0;
LL ma=low-1;
while(!top.empty()&&!added.empty()){
int id=top.top().S;
if(be_added[id])break;
done[id]=1;
top.pop();
num[id]++;
mi=min(mi,a[id]/num[id]);
auto tmp=added.top();
added.pop();
if(done[tmp.S])break;
be_added[tmp.S]=1;
num[tmp.S]--;
if(num[tmp.S]>1)added.push({get_next_upper_bound(tmp.S),tmp.S});
ma=max(ma,tmp.F);
an=min(an,(top.empty()?ma:max(ma,top.top().F))-mi);
}
return an;
}
void solve(){
LL L;
//R(n,K,L);
R(L,n,K);
K+=n+1;
LL lt=0;
REP(i,n){
LL x;
R(x);
a[i]=x-lt;
lt=x;
}
a[n++]=L-lt;
sort(a,a+n);
W(go());
}
int main(){
CASET{
solve();
}
return 0;
}
|
1330
|
A
|
Dreamoon and Ranking Collection
|
Dreamoon is a big fan of the Codeforces contests.
One day, he claimed that he will collect all the places from $1$ to $54$ after two more rated contests. It's amazing!
Based on this, you come up with the following problem:
There is a person who participated in $n$ Codeforces rounds. His place in the first round is $a_1$, his place in the second round is $a_2$, ..., his place in the $n$-th round is $a_n$.
You are given a positive non-zero integer $x$.
Please, find the largest $v$ such that this person can collect all the places from $1$ to $v$ after $x$ more rated contests.
In other words, you need to find the largest $v$, such that it is possible, that after $x$ more rated contests, for each $1 \leq i \leq v$, there will exist a contest where this person took the $i$-th place.
For example, if $n=6$, $x=2$ and $a=[3,1,1,5,7,10]$ then answer is $v=5$, because if on the next two contest he will take places $2$ and $4$, then he will collect all places from $1$ to $5$, so it is possible to get $v=5$.
|
The total number of rounds this person participates after $x$ more rated contests is $n+x$. So the number of places this person collects cannot exceed $n + x$. Then we can iterate $k$ from $n+x$ to $1$. In each iteration, let $r$ be the number of integers from $1$ to $k$ which doesn't appear in $a_i$. This person can collect all places from $1$ to $k$ if only if $r \le x$. So the answer is the first $k$ meeting the condition $r \le x$ when iterating. The solution can be implemented in time complexity $O((n+x)^2)$ as a reference solution. There are also many $O(n)$ solutions that can solve this problem. But in the experience of author and testers, it's easy to make some mistake in the detail when writing $O(n)$ solution : ) Please try it by yourself.
|
[
"implementation"
] | 900
|
#include<cstdio>
const int MAX_V = 201;
bool achieve[MAX_V];
void solve() {
int n, x;
scanf("%d%d", &n, &x);
for(int i = 1; i <= n + x; i++) {
achieve[i] = false;
}
for(int i = 1; i <= n; i++) {
int ranking;
scanf("%d", &ranking);
achieve[ranking] = true;
}
for(int k = n + x; k > 0; k--) {
int v = 0;
for(int i = 1; i <= k; i++) {
if(!achieve[i]) v++;
}
if(v <= x) {
printf("%d\n", k);
return;
}
}
}
int main() {
int T;
scanf("%d", &T);
while(T--) solve();
return 0;
}
|
1330
|
B
|
Dreamoon Likes Permutations
|
The sequence of $m$ integers is called the permutation if it contains all integers from $1$ to $m$ exactly once. The number $m$ is called the length of the permutation.
Dreamoon has two permutations $p_1$ and $p_2$ of non-zero lengths $l_1$ and $l_2$.
Now Dreamoon concatenates these two permutations into another sequence $a$ of length $l_1 + l_2$. First $l_1$ elements of $a$ is the permutation $p_1$ and next $l_2$ elements of $a$ is the permutation $p_2$.
You are given the sequence $a$, and you need to find two permutations $p_1$ and $p_2$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)
|
Let $ma$ be the maximum value of all elements in $a$ . If you can recover the the array $a$ to two permutations $p1$ abd $p2$, then $ma$ must be $\max(len1, len2)$. So there are at most two case: 1. $len1 = ma, len2 = n - ma$, 2. $len1 = n - ma, len2 = ma$. We can check the two cases separately with time complexity $O(n)$. Please see the example code for detail.
|
[
"implementation",
"math"
] | 1,400
|
#include<cstdio>
const int SIZE = 200000;
int p[SIZE];
int ans[SIZE][2];
int ans_cnt;
bool judge(int a[], int n){
static int used[SIZE+1];
for(int i = 1; i <= n; i++) used[i] = 0;
for(int i = 0; i < n; i++) used[a[i]] = 1;
for(int i = 1; i <= n; i++) {
if(!used[i]) return 0;
}
return 1;
}
bool judge(int len1, int n){
return judge(p, len1) && judge(p + len1, n - len1);
}
int main() {
int t = 0;
scanf("%d", &t);
while(t--) {
ans_cnt = 0;
int n;
scanf("%d", &n);
int ma=0;
for(int i = 0; i < n; i++) {
scanf("%d", &p[i]);
if(ma < p[i]) ma = p[i];
}
if(judge(n - ma,n)) {
ans[ans_cnt][0] = n - ma;
ans[ans_cnt++][1] = ma;
}
if(ma * 2 != n && judge(ma,n)) {
ans[ans_cnt][0] = ma;
ans[ans_cnt++][1] = n - ma;
}
printf("%d\n", ans_cnt);
for(int i = 0; i < ans_cnt; i++) {
printf("%d %d\n", ans[i][0], ans[i][1]);
}
}
return 0;
}
|
1332
|
A
|
Exercising Walk
|
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell $(x,y)$ of an infinite grid. According to Alice's theory, cat needs to move:
- exactly $a$ steps left: from $(u,v)$ to $(u-1,v)$;
- exactly $b$ steps right: from $(u,v)$ to $(u+1,v)$;
- exactly $c$ steps down: from $(u,v)$ to $(u,v-1)$;
- exactly $d$ steps up: from $(u,v)$ to $(u,v+1)$.
Note that the moves can be performed in an \textbf{arbitrary order}. For example, if the cat has to move $1$ step left, $3$ steps right and $2$ steps down, then the walk right, down, left, right, right, down is valid.
Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is \textbf{always} in the area $[x_1,x_2]\times [y_1,y_2]$, i.e. for every cat's position $(u,v)$ of a walk $x_1 \le u \le x_2$ and $y_1 \le v \le y_2$ holds.
Also, note that the cat can visit the same cell multiple times.
Can you help Alice find out if there exists a walk satisfying her wishes?
Formally, the walk should contain exactly $a+b+c+d$ unit moves ($a$ to the left, $b$ to the right, $c$ to the down, $d$ to the up). Alice can do the moves in \textbf{any} order. Her current position $(u, v)$ should \textbf{always} satisfy the constraints: $x_1 \le u \le x_2$, $y_1 \le v \le y_2$. The staring point is $(x, y)$.
You are required to answer $t$ test cases \textbf{independently}.
|
The key observation is x-axis and y-axis is independent in this task as the area is a rectangle. Therefore, we should only consider 1D case (x-axis, for example). The optimal path to choose alternates between right and left moves until only one type of move is possible. And sometimes there is no place to make even one move, which has to handled separately. So the verdict is "Yes" if and only if $x_1 \le x-a+b \le x_2$ and ($x_1<x_2$ or $a+b=0$).
|
[
"greedy",
"implementation",
"math"
] | 1,100
|
#include<bits/stdc++.h>
using namespace std;
int a,b,c,d,x,y,x1,y1,x2,y2,xx,yy;
int main(){
int t;
cin>>t;
while (t--){
cin>>a>>b>>c>>d;
cin>>x>>y>>x1>>y1>>x2>>y2;
xx=x,yy=y;
x+=-a+b, y+=-c+d;
if (x>=x1&&x<=x2&&y>=y1&&y<=y2&&(x2>x1||a+b==0)&&(y2>y1||c+d==0)){
cout<<"Yes\n";
}
else{
cout<<"No\n";
}
}
return 0;
}
|
1332
|
B
|
Composite Coloring
|
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than $1$. For example, the following numbers are composite: $6$, $4$, $120$, $27$. The following numbers aren't: $1$, $2$, $3$, $17$, $97$.
Alice is given a sequence of $n$ composite numbers $a_1,a_2,\ldots,a_n$.
She wants to choose an integer $m \le 11$ and color each element one of $m$ colors from $1$ to $m$ so that:
- for each color from $1$ to $m$ there is at least one element of this color;
- each element is colored and colored exactly one color;
- the greatest common divisor of any two elements that are colored the same color is greater than $1$, i.e. $\gcd(a_i, a_j)>1$ for each pair $i, j$ if these elements are colored the same color.
Note that equal elements can be colored different colors — you just have to choose one of $m$ colors for each of the indices from $1$ to $n$.
Alice showed already that if all $a_i \le 1000$ then she can always solve the task by choosing some $m \le 11$.
Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $m$ from $1$ to $11$.
|
The solution is obvious once one note that for any composite number $k$, there exists a prime $d$ such that $d \le \sqrt{k}$ and $k$ is divisible by $d$. Coincidentally, there are exactly $11$ primes below $\sqrt{1000}$. Thus, one can color balls according to their smallest divisor. That works because if all numbers of the same color have the same divisor then each pair has at least this divisor in their GCD.
|
[
"brute force",
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,400
|
#include<bits/stdc++.h>
using namespace std;
int n,t;
vector<int> ans[1007];
int res[1007];
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
auto f=[&](int u){
for (int i=2;i<=u;++i){
if (u%i==0) return i;
}
};
cin>>t;
while (t--){
cin>>n;
for (int i=1;i<=1000;++i) ans[i].clear();
for (int i=1;i<=n;++i){
int u;
cin>>u; ans[f(u)].push_back(i);
}
int ret=0;
for (int i=1;i<=1000;++i){
if (ans[i].size()){
++ret;
for (auto c:ans[i]){
res[c]=ret;
}
}
}
cout<<ret<<"\n";
for (int i=1;i<=n;++i){
cout<<res[i]<<" ";
}
cout<<"\n";
}
return 0;
}
|
1332
|
C
|
K-Complete Word
|
Word $s$ of length $n$ is called $k$-complete if
- $s$ is a palindrome, i.e. $s_i=s_{n+1-i}$ for all $1 \le i \le n$;
- $s$ has a period of $k$, i.e. $s_i=s_{k+i}$ for all $1 \le i \le n-k$.
For example, "abaaba" is a $3$-complete word, while "abccba" is not.
Bob is given a word $s$ of length $n$ consisting of only lowercase Latin letters and an integer $k$, such that $n$ is divisible by $k$. He wants to convert $s$ to any $k$-complete word.
To do this Bob can choose some $i$ ($1 \le i \le n$) and replace the letter at position $i$ with some other lowercase Latin letter.
So now Bob wants to know the minimum number of letters he has to replace to convert $s$ to any $k$-complete word.
Note that Bob can do zero changes if the word $s$ is already $k$-complete.
You are required to answer $t$ test cases \textbf{independently}.
|
One should notice that word $s$ of length $n$ is $k$-complete if and only if there exists a palindrome $t$ of length $k$ such that $s$ can be generated by several concatenations of $t$. So in the final string all characters at positions $i$, $k - i + 1$, $k + i$, $2k - i + 1$, $2k + i$, $3k - i + 1$, $\dots$ for all $1 \le i \le k$ should all be equal. This helps us to solve the problem independently for each $i$. To minimize the required number of changes, you should make all the letters equal to the one which appears at these positions the most initially. Calculate that maximum number of appearances and sum up over all $i$. Be careful with an odd $k$ because the letter in the center of each block has a different formula.
|
[
"dfs and similar",
"dsu",
"greedy",
"implementation",
"strings"
] | 1,500
|
#include<bits/stdc++.h>
using namespace std;
const int maxn=200007;
int n,k,ans=0;
int cnt[maxn][26];
string s;
int differ(int u,int v){
int ret=0,mx=0;
for (int j=0;j<26;++j){
ret+=cnt[u][j]+cnt[v][j];
mx=max(mx,cnt[u][j]+cnt[v][j]);
}
return ret-mx;
}
int main(){
int t;
cin>>t;
while (t--){
cin>>n>>k>>s;
for (int i=0;i<k;++i){
for (int j=0;j<26;++j){
cnt[i][j]=0;
}
}
for (int i=0;i<n;++i){
cnt[i%k][s[i]-'a']++;
}
int ans=0;
for (int i=0;i<k;++i){
ans+=differ(i,k-1-i);
}
cout<<ans/2<<"\n";
}
return 0;
}
|
1332
|
D
|
Walk on Matrix
|
Bob is playing a game named "Walk on Matrix".
In this game, player is given an $n \times m$ matrix $A=(a_{i,j})$, i.e. the element in the $i$-th row in the $j$-th column is $a_{i,j}$. Initially, player is located at position $(1,1)$ with score $a_{1,1}$.
To reach the goal, position $(n,m)$, player can move right or down, i.e. move from $(x,y)$ to $(x,y+1)$ or $(x+1,y)$, as long as player is still on the matrix.
However, each move changes player's score to the bitwise AND of the current score and the value at the position he moves to.
Bob can't wait to find out the maximum score he can get using the tool he recently learnt — dynamic programming. Here is his algorithm for this problem.
However, he suddenly realize that the algorithm above fails to output the maximum score for some matrix $A$. Thus, for any given non-negative integer $k$, he wants to find out an $n \times m$ matrix $A=(a_{i,j})$ such that
- $1 \le n,m \le 500$ (as Bob hates large matrix);
- $0 \le a_{i,j} \le 3 \cdot 10^5$ for all $1 \le i\le n,1 \le j\le m$ (as Bob hates large numbers);
- the difference between the maximum score he can get and the output of his algorithm is \textbf{exactly} $k$.
It can be shown that for any given integer $k$ such that $0 \le k \le 10^5$, there exists a matrix satisfying the above constraints.
Please help him with it!
|
In fact, the following matrix will work: $\left( \begin{array}{ccc} 2^{17}+k & 2^{17} & 0\\ k & 2^{17}+k & k\\ \end{array} \right)$ To find such a matrix, one should find out why the dp solution fails. One should notice that $dp_{2,2}=\max(a_{1,1}\&a_{1,2}\&a_{2,2},a_{1,1}\&a_{2,1}\&a_{2,2})$ and dp solution will choose the optimal path from $(1,1)$ to $(2,2)$ for later decision. However, we should notice that we can only discard the suboptimal result if and only if $ans_{suboptimal} \& ans_{optimal}=ans_{suboptimal}$ rather than $ans_{suboptimal} < ans_{optimal}$. Based on above analysis, we can construct the matrix easily. In fact, even if $n,m$ is fixed satisfying that $n \ge 2,m \ge 2$ and $n\cdot m>4$, we could easily construct a matrix for a given $k$ based on our $2 \times 3$ matrix.
|
[
"bitmasks",
"constructive algorithms",
"math"
] | 1,700
|
k = int(input())
x = 2**17
print(2, 3)
print(x^k, x, 0)
print(k, x^k, k)
|
1332
|
E
|
Height All the Same
|
Alice has got addicted to a game called Sirtet recently.
In Sirtet, player is given an $n \times m$ grid. Initially $a_{i,j}$ cubes are stacked up in the cell $(i,j)$. Two cells are called adjacent if they share a side. Player can perform the following operations:
- stack up one cube in two \textbf{adjacent} cells;
- stack up two cubes in one cell.
Cubes mentioned above are identical in height.
Here is an illustration of the game. States on the right are obtained by performing one of the above operations on the state on the left, and grey cubes are added due to the operation.
Player's goal is to \textbf{make the height of all cells the same} (i.e. so that each cell has the same number of cubes in it) using above operations.
Alice, however, has found out that on some starting grids she may never reach the goal no matter what strategy she uses. Thus, she is wondering the number of initial grids such that
- $L \le a_{i,j} \le R$ for all $1 \le i \le n$, $1 \le j \le m$;
- player can reach the goal using above operations.
Please help Alice with it. Notice that the answer might be large, please output the desired value modulo $998,244,353$.
|
Observation 1. The actual values in the cells don't matter, only parity matters. Proof. Using the second operation one can make all the values of same parity equal by applying it to the lowest value until done. That observation helps us to get rid of the second operation, let us only have the first one. Observation 2. Player is able to change parity of any pair of cells at the same time. Proof. For any given cell $u$ and cell $v$, there exists a path from $u$ to $v$, namely $p=w_0w_1\ldots w_k$, such that $w_0=u$ and $w_n=v$. Perform operation for adjacent cells $w_{i-1}$ and $w_{i}$ for all $1 \le i \le n$ Observation 3. If $n \times m$ is odd, player can always reach the goal no matter what the initial state is. Proof. There are two cases: there is an even number of even cells or there is an even number of odd cells. Whichever of these holds, we can change all cells of that parity to the opposite one with the aforementioned operation, making all cells the same parity. Observation 4. If $n \times m$ is even, and $\sum_{i=1}^n \sum_{j=1}^m a_{i,j}$ is even, player can reach the goal. Proof. Similar to the proof of Observation 3. Proof is omitted. Observation 5. If $n \times m$ is even and $\sum_{i=1}^n \sum_{j=1}^m a_{i,j}$ is odd, player can never reach the goal no matter what strategies player takes. Proof. Note that applying the operation never changes the parity of the number of cells of each parity (i.e. if we start with an odd number of odd cells and an odd number of even cells, they will both be odd until the end). Thus, there is no way to make zero cells of some parity. How does that help us to calculate the answer? The first case ($n \times m$ is odd) is trivial, the answer is all grids. Let's declare this as $total$ value. The second case ($n \times m$ is even) is harder. Me and pikmike have different formulas to obtain it but the answer is the same. WLOG, let's move the range of values from $[L; R]$ to $[0; R - L]$, let $k = R - L$. Easy combinatorics solution (me): Let's find out the number of ways to choose the grid such that the number of even cells is even and $0 \le a_i \le k$. Suppose that there are $E$ even numbers in $[0,k]$, $O$ odds. Therefore, for any given $0 \le i \le nm$, the number of ways to have exactly $i$ even numbers should be $E^i O^{nm-i} \times \binom{nm}{i}$. Thus, the total answer should be $\sum \limits_{i=0}^{nm/2} E^{2i} O^{nm-2i} \binom{nm}{2i}$, which should remind you of the Newton expansion. Note that $(E+O)^{nm}=\sum_{i=0}^{nm/2}E^{2i}O^{nm-2i}\binom{nm}{2i}+\sum_{i=1}^{nm/2}E^{2i-1} O^{nm-(2i-1)} \binom{nm}{2i-1}$ and $(E-O)^{nm}=\sum_{i=0}^{nm/2}E^{2i}O^{nm-2i}\binom{nm}{2i}-\sum_{i=1}^{nm/2}E^{2i-1} O^{nm-(2i-1)} \binom{nm}{2i-1}$ Adding those two formulas will get us exactly the formula we were looking for but doubled. Thus, the answer is that divided by $2$. Easy intuition solution (pikmike): There is a general solution to this kind of problems. Let's try to pair up each valid grid with exactly one invalid grid. Valid in our problem is such a grid that the number of even cells is even. If such a matching exists then the answer is exactly half of all grids $(\frac{total}{2})$. Let's come up with some way to pair them up. For example, this works but leaves us with two cases to handle. Let $k$ be odd. For each grid let's replace $a_{0,0}$ with $a_{0,0}~xor~1$. You can see that the parity changed, thus the number of even cells also changed its parity. So if the grid was invalid it became valid and vice versa. For an even $k$ it's slightly trickier but actually one can show that almost all grids pair up with each other and only a single grid remains unpaired. So we can add a fake grid and claim that the answer is $\frac{total + 1}{2}$. The algorithm is the following. Find the first position such that the value $a_{i,j}$ on it is not equal to $k$. Replace it with $a_{i,j}~xor~1$. You can easily see that only grid that consists of all numbers $k$ has no pair.
|
[
"combinatorics",
"constructive algorithms",
"math",
"matrices"
] | 2,100
|
MOD = 998244353
n, m, l, r = map(int, input().split())
if n * m % 2 == 1:
print(pow(r - l + 1, n * m, MOD))
else:
e = r // 2 - (l - 1) // 2
o = (r - l + 1) - e
print((pow(e + o, n * m, MOD) + pow(e - o, n * m, MOD)) * (MOD + 1) // 2 % MOD)
|
1332
|
F
|
Independent Set
|
Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.
Given a graph $G=(V,E)$, an independent set is a subset of vertices $V' \subset V$ such that for every pair $u,v \in V'$, $(u,v) \not \in E$ (i.e. no edge in $E$ connects two vertices from $V'$).
An edge-induced subgraph consists of a subset of edges $E' \subset E$ and all the vertices in the original graph that are incident on at least one edge in the subgraph.
Given $E' \subset E$, denote $G[E']$ the edge-induced subgraph such that $E'$ is the edge set of the subgraph. Here is an illustration of those definitions:
In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:
Given a tree $G=(V,E)$, calculate the sum of $w(H)$ over all except null edge-induced subgraph $H$ of $G$, where $w(H)$ is the number of independent sets in $H$. Formally, calculate $\sum \limits_{\emptyset \not= E' \subset E} w(G[E'])$.
Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo $998,244,353$.
|
We will call one vertice is colored if and only if it is in the independent set. And a coloring is valid if and only if no two adjacent vertices are both colored. Therefore, we are asked to calculate the sum of number of valid colorings over all edge induced subgraphs. To deal with the task, one should notice that for a edge induced subgraph and one valid coloring, we may add those vertices which are removed due to the generation of edge induced subgraph, and remain it uncolored. Therefore, for a coloring on the original graph $G=(V,E)$, we could consider removing edges such that it will behave the same with above procedure. In fact, given a coloring, we can define edge removing is valid if and only if there is no adjacent colored vertice and no isolated vertex is colored. We can actually show that there is almost a one to one corresponding relation betweeen those two procedure except for the case where all vertices remains uncolored and all edges are removed. Therefore, we can actually solve the following task: Given a tree $G=(V,E)$, for any given coloring, define a edge removal is valid if it satisfies above constrains. And it will suddenly becoming something easy to solve with tree dp. Define $dp_{u,0}$ be the answer for subtree rooted at $u$ with additional constraint such that $u$ is not colored, $dp_{u,1}$ be the answer where $u$ is colored and $dp_u$ be the answer where edges from $u$ to its children are removed. Therefore, the dp formula should be $dp_{u,0}=\prod_{v}(2dp_{v,0}+2dp_{v,1}-dp_v)$ $dp_{u,1}=\prod_{v}(2dp_{v,0}+dp_{v,1}-dp_v)$ $dp_{u}=\prod_{v}(dp_{v,0}+dp_{v,1}-dp_v)$ The answer is easily calculated with those three states.
|
[
"dfs and similar",
"dp",
"trees"
] | 2,500
|
#include<bits/stdc++.h>
#define int long long
#define ULL unsigned long long
#define F first
#define S second
#define pb push_back
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define rep1(i,n) for(int i=1;i<=(int)(n);++i)
#define range(a) a.begin(), a.end()
#define PI pair<int,int>
#define VI vector<int>
#define debug cout<<"potxdy"<<endl;
using namespace std;
typedef long long ll;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int maxn=300007;
const int mod=998244353;
int n,dp[maxn][2],f[maxn];
VI vec[maxn];
int mult(int u,int v){
u=(u%mod+mod)%mod, v=(v%mod+mod)%mod;
return 1ll*u*v%mod;
}
void dfs(int u,int p){
dp[u][0]=dp[u][1]=f[u]=1;
for (auto c:vec[u]){
if (c==p) continue;
dfs(c,u);
dp[u][0]=mult(dp[u][0],2*dp[c][0]+2*dp[c][1]-f[c]);
dp[u][1]=mult(dp[u][1],dp[c][1]+2*dp[c][0]-f[c]);
f[u]=mult(f[u],dp[c][0]+dp[c][1]-f[c]);
}
}
#undef int
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>n;
for (int i=1;i<n;++i){
int u,v;
cin>>u>>v;
vec[u].pb(v), vec[v].pb(u);
}
dfs(1,0);
cout<<(dp[1][0]+dp[1][1]-f[1]-1+2*mod)%mod<<endl;
return 0;
}
|
1332
|
G
|
No Monotone Triples
|
Given a sequence of integers $a$ of length $n$, a tuple $(i,j,k)$ is called monotone triples if
- $1 \le i<j<k\le n$;
- $a_i \le a_j \le a_k$ or $a_i \ge a_j \ge a_k$ is satisfied.
For example, $a=[5,3,4,5]$, then $(2,3,4)$ is monotone triples for sequence $a$ while $(1,3,4)$ is not.
Bob is given a sequence of integers $a$ of length $n$ in a math exam. The exams itself contains questions of form $L, R$, for each of them he is asked to find any subsequence $b$ \textbf{with size greater than $2$ (i.e. $|b| \ge 3$)} of sequence $a_L, a_{L+1},\ldots, a_{R}$.
Recall that an sequence $b$ is a subsequence of sequence $a$ if $b$ can be obtained by deletion of several (possibly zero, or all) elements.
However, he hates monotone stuff, and he wants to find a subsequence \textbf{free from monotone triples}. Besides, he wants to find one subsequence with the \textbf{largest} length among all subsequences free from monotone triples for every query.
Please help Bob find out subsequences meeting the above constraints.
|
We will solve this task with the following observations. Observation 1. If an array $x$ of length $k$ ($k \ge 3$) has no monotone triple, then one of the following is true: $x_1<x_2>x_3<x_4>x_5<\ldots$ $x_1>x_2<x_3>x_4<x_5>\ldots$ Observation 2. If an array $x$ of length $k$ ($k \ge 4$) has no monotone triple, then its subsequence has no monotone triple. Observation 3. If an array $x$ of length 4 has no monotone triple, then $max(x_2,x_3)>max(x_1,x_4)$, $min(x_2,x_3)<min(x_1,x_4)$,vice versa. Proof. WLOG, we assume $max(x_2,x_3)\le x_1$, by observation 1 we will know that $x_1>x_2<x_3>x_4$, since $x_1\ge x_3$, we get a monotone triple $(1,3,4)$, leading to contradiction. Second part can be verified easily. Observation 4. For every array $x$ of length $k$ ($k \ge 5$), $x$ must have monotone triple. Proof. WLOG, we just need to prove the observation holds when $k=5$ and cases when not all elements are equal. In that case, one of extremal can be reached in position other than $3$. WLOG, we will assume that maximum is reached at position $2$. However, $x_2,x_3,x_4,x_5$ cannot be monotone-triple-free, leading to contradiction! Combining those observations (or Erdos-Szekeres theorem if you know it), we would like to get the following solution, which runs in $O(q n^4)$. If the subsequence is monotone, the answer should be 0. If there exists $i,j,k,l$ such that $L \le i<j<k<l \le R$ and $a_i$, $a_l$ fails to reach maximum and minimum among those four numbers, the answer should be 4. Otherwise, the answer should be 3. In the following paragraphs, we will only focus on the case of $4$. Other stuffs can be dealt similarly (or easily). $O(n^2)$ solution(the observation is crucial to obtain a faster solution) Notice that constraint is equivalent to that there exists $i,j$ such that $a_i,a_j$ fails to reach maximum and minimum among $a_i,a_{i+1},\ldots,a_j$. This observation allows us to solve this task in $O(n^2)$ with some precalculation. (though it's still not enough to get accepted). $O(n \log n)$ solution Let's solve the task for a sequence of a pairwise distinct numbers and then change the conditions to a general sequence. Let's fix $a_i$ - the leftmost element of $b$ and look at what we are asked to find. So there should be some position $j$ to the right of $i$ so that the range of values on positions $[i, j]$ excluding the greatest and the smallest values includes both $a_i$ and $a_j$. Let's process the array from right to left, maintaining two stacks. The top element in both stacks is the currently processed one. Next element of the first stack is the closest to the right element greater than the top one, and the next element of the second stack is the closest to the right smaller than the top one. And the stacks go like that until the end of array. Iterating over one of these stacks will show the increase of the range of values in one direction, iterating over both at the same time will show how the range of values changes in total. So I claim that the sequence we are looking for exists iff both stacks include more than $1$ element and there is an element to the right of second elements of both stacks such that it is included in neither of the stacks. Naturally that condition tells that there is some position in which neither maximum, nor minimum values are updated. The values that are in neither of stacks can be maintained in a queue or in a BIT. Basically, the position when the range of values doesn't change is such a value which is both smaller than the maximum value on the segment and greater than the minimum one. Thus, we can choose $a_i$, the latest elements in both stacks up to that position and that position itself. How to deal with not pairwise distinct elements? Well, it's enough to change the conditions in stacks to the next greater or equal and the next smaller or equal. However, that will push the elements equal to the current one right next to it to the both stacks. Previously we kinda used the fact that no element except the current one is in both stacks. I think that the easiest way to deal with it is to get the answer for the rightmost of the consecutive equal elements and then just say that the answer for the rest of them is the same. Finally, push all these consecutive equal elements to the both stacks. As for queries. I previously said that we can take the position where the value range doesn't change. Basically, the first valid position is coincidentally the shortest length valid segment starting from $i$. So to find the first position you just need to do a binary search over that queue or BIT of the values which are in neither of the stacks. We can easily remember it for each position and then do a range minimum query checking if any of the positions in $[l, r]$ have their shortest right border smaller than $r$.
|
[
"data structures"
] | 3,100
|
#include<bits/stdc++.h>
using namespace std;
const int maxn=200007;
int n,q,a[maxn],b[maxn],c[maxn],t[maxn],sum[maxn];
int st1[maxn],st2[maxn],p1,p2,r1,r2,s1,s2;
int ans1[maxn][4],ans2[maxn][4];
set<int> s;
bool cmp1(int u,int v){
return a[u]<a[v];
}
bool cmp2(int u,int v){
return a[u]>a[v];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>n>>q;
for (int i=1;i<=n;++i){
cin>>a[i];
}
p1=p2=r1=r2=0;
s.insert(n+1);
for (int i=n;i>0;--i){
while (p1){
int u=st1[p1];
if (a[u]>a[i]){
t[u]--;
if (!t[u]) s.insert(u);
p1--;
r1=0;
}
else{
break;
}
}
while (p2){
int u=st2[p2];
if (a[u]<a[i]){
t[u]--;
if (!t[u]) s.insert(u);
p2--;
r2=0;
}
else{
break;
}
}
s1=lower_bound(st1+1,st1+p1+1,i,cmp1)-st1-1, s2=lower_bound(st2+1,st2+p2+1,i,cmp2)-st2-1;
b[i]=i+max(r1,r2)+1;
ans1[i][0]=i, ans1[i][1]=b[i]-1, ans1[i][2]=b[i];
if (s1&&s2){
c[i]=*s.lower_bound(max(st1[s1],st2[s2]));
if (c[i]<=n){
int u=lower_bound(st1+1,st1+p1+1,c[i],greater<int>())-st1,v=lower_bound(st2+1,st2+p2+1,c[i],greater<int>())-st2;
ans2[i][0]=i, ans2[i][1]=min(st1[u],st2[v]), ans2[i][2]=max(st1[u],st2[v]), ans2[i][3]=c[i];
}
}
else{
c[i]=n+1;
}
st1[++p1]=i;
st2[++p2]=i;
r1++, r2++;
t[i]+=2;
if (i<n&&b[i]>b[i+1]){
b[i]=b[i+1];
for (int j=0;j<3;++j){
ans1[i][j]=ans1[i+1][j];
}
}
if (i<n&&c[i]>c[i+1]){
c[i]=c[i+1];
for (int j=0;j<4;++j){
ans2[i][j]=ans2[i+1][j];
}
}
}
while (q--){
int l,r;
cin>>l>>r;
if (r>=c[l]){
cout<<"4\n";
for (int j=0;j<4;++j){
cout<<ans2[l][j]<<" ";
}
cout<<"\n";
}
else{
if (r>=b[l]){
cout<<"3\n";
for (int j=0;j<3;++j){
cout<<ans1[l][j]<<" ";
}
cout<<"\n";
}
else{
cout<<"0\n\n";
}
}
}
return 0;
}
|
1333
|
A
|
Little Artem
|
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an $n \times m$ board. Each cell of the board should be colored in white or black.
Lets $B$ be the number of black cells that have at least one white neighbor adjacent by the side. Let $W$ be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called \textbf{good} if $B = W + 1$.
The first coloring shown below has $B=5$ and $W=4$ (all cells have at least one neighbor with the opposite color). However, the second coloring is not \textbf{good} as it has $B=4$, $W=4$ (only the bottom right cell doesn't have a neighbor with the opposite color).
Please, help Medina to find any \textbf{good} coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.
|
In this problem it is enough to simply paint the upper left corner white and all the others black for any size of the board Like this: And there are $W=1$ (cell with coordinates $\{1, 1\}$) and $B=2$ (cells with coordinates $\{1, 2\}$ and $\{2, 1\}$). In the first version, the task restrictions were $1 \le n, m$, but we thought it would be too difficult for div2A.
|
[
"constructive algorithms"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m; cin >> n >> m;
string black_row(m, 'B');
vector<string> result(n, black_row);
result[0][0] = 'W';
for (int i = 0; i < n; ++i) {
cout << result[i] << '\n';
}
}
int main() {
int t; cin >> t;
while(t--) solve();
}
|
1333
|
B
|
Kind Anton
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times:
- Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once.
- Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
|
First of all, note that we can add an element with index $i$ to an element with index $j$ iff $i < j$. This means that the element $a_n$ cannot be added to any other element because there is no index $j > n$ in the array. This is why we can first equalize the elements $a_n$ and $b_n$. If $a_n = b_n$, they are already equal. If $a_n < b_n$, then we need to have element equal to $1$ along the elements $a$ with indexes $\{1,..., n-1\}$. For $a_n > b_n$, we need to have $-1$ along these elements. After the elements with index $n$ become equal, we can go to the element with index $n-1$ and do the same. Then indexes $n-2$, $n-3$, ..., $1$. You can implement this idea yourself! Final time complexity: $O(n)$
|
[
"greedy",
"implementation"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n; cin >> n;
vector<int> a(n), b(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < n; ++i) {
cin >> b[i];
}
vector<int> good(2, 0);
for (int i = 0; i < n; ++i) {
if (a[i] > b[i] && !good[0]) {
cout << "NO\n";
return;
} else if (a[i] < b[i] && !good[1]) {
cout << "NO\n";
return;
}
if (a[i] == -1) good[0] = 1;
if (a[i] == 1) good[1] = 1;
}
cout << "YES\n";
}
int main() {
int t; cin >> t;
while(t--) {
solve();
}
}
|
1333
|
C
|
Eugene and an array
|
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array $c$ is a subarray of an array $b$ if $c$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array \textbf{good} if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $[-1, 2, -3]$ is \textbf{good}, as all arrays $[-1]$, $[-1, 2]$, $[-1, 2, -3]$, $[2]$, $[2, -3]$, $[-3]$ have nonzero sums of elements. However, array $[-1, 2, -1, -3]$ isn't \textbf{good}, as his subarray $[-1, 2, -1]$ has sum of elements equal to $0$.
Help Eugene to calculate the number of nonempty \textbf{good} subarrays of a given array $a$.
|
Let's solve this problem in $O(n^2 \times log (n))$for now. Note that if the subarray $[a_i,..., a_j]$ is good, then the subarray $[a_i,..., a_{j-1}]$ is also good, and if the subset $[a_i,..., a_j]$ is not good, then the subarray $[a_i,..., a_{j+1}]$ is not good either. Then for each left border $a_i$ we want to find the rightmost border $a_j$ such that $[a_i,..., a_j]$ is good and add to the answer $j - i + 1$ (subarrays $[a_i, ..., a_j], [a_i, ..., a_{j-1}], ..., [a_i]$) [1]. Let's denote the rightmost border $j$ for border $i$ as $R (i)$. Let's calculate the prefix-sum of the array $P$. $P_0 = 0, P_i = a_1 + .. + a_i, 1 \le i \le n$. Note that a subset of $[a_i,..., a_j]$ has a zero sum iff $P_{i-1} = P_j$. Then the subset $[a_i,..., a_j]$ is a good iff sum of prefixes $[P_{i-1},..., P_j]$ has no duplicates [2]. Using [1] and [2], we can simply iterate over $i$ from $0$ to $n$ and over $j$ from $i$ to $n$ and count the set of prefix sums $[P_i,..., P_j]$. The first moment $j_0$ when this set contains duplicates gives us the rightmost border $j_0-1$, and we add $(j_0-1) - i$ (no $+1$, because it is an array of prefix sums) to answer. To improve this solution to $O (n \times log(n))$, we need to note that $R(i)$ is monotonous over $i$. Now we can iterate over $i$ from $0$ to $n$ and over $j$ from $R (i-1)$ to $n$ uses a set of prefix sums from the previous iteration. Thus we have a solution $O (n \times log(n))$, because $j$ points to each element of the array exactly once. If you code in C++, it is important not to use std:: unordered_set in this task, but use std::set. One of the participants hacked the solution using std:: unordered_set, using collisions in this structure. I highly recommend you to read this blog for more info https://codeforces.com/blog/entry/62393. Final time complexity: $O(n \times log(n))$
|
[
"binary search",
"data structures",
"implementation",
"two pointers"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
vector<long long> prefix(n + 1, 0);
for (int i = 0; i < n; ++i) {
int x; cin >> x;
prefix[i + 1] = prefix[i] + x;
}
int begin = 0, end = 0;
long long ans = 0;
set<long long> s = {0};
while(begin < n) {
while(end < n && !s.count(prefix[end + 1])) {
++end;
s.insert(prefix[end]);
}
ans += end - begin;
s.erase(prefix[begin]);
++begin;
}
cout << ans << endl;
}
|
1333
|
D
|
Challenges in school №41
|
There are $n$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are \textbf{looking at each other} can \textbf{simultaneously} turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second \textbf{at least one} pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number $n$, the initial arrangement of children and the number $k$. You have to find a way for the children to act if they want to finish the process in exactly $k$ seconds. More formally, for each of the $k$ moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and $k = 2$ children can do the following steps:
At the beginning, two pairs make move: $(1, 2)$ and $(3, 4)$. After that, we receive the following configuration: At the second move pair $(2, 3)$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $n^2$ "headturns".
|
If solution exist let's count the minimum and maximum bounds for $k$ for initial arrangement of children. A minimum $k$ achieved all possible pairs of children turn theirs heads at every step. The maximum $k$ reached if only one of possible pairs of children turn theirs heads at every step. This values is easy to count, I'll leave it to you! If $k$ from the statement not fit within our bounds, then we need to print $-1$. Otherwise solution exist and we need to construct them. For each next move we can use all pairs of children to turn theirs heads, decrease $k$ by 1 and recalculate maximum bound (lets call it $U$) on $k$ (just decrease them on the number of pairs used). If after moving new value of $k$ fits in the bound ($k \le U$), then we proceed to the next iteration. Otherwise, we roll back to the previous iteration and use $U - k + 1$ pairs in this move. Number of remaining moves will be $k - 1$ and upper bound will be $U - (U - k + 1) = k - 1$. And from that moment, just use only one pair in one move to the end of the process (to find one of the pair quickly we need to store them in the queue). Final time complexity: $O(n^2)$
|
[
"brute force",
"constructive algorithms",
"games",
"graphs",
"greedy",
"implementation",
"sortings"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<int> find_steps(const vector<int>& a) {
vector<int> steps;
for (int i = 0; i < n - 1; ++i) {
if (a[i] == 1 && a[i + 1] == 0) steps.push_back(i);
}
return steps;
}
int main() {
cin >> n >> k;
string s; cin >> s;
vector<int> a(n);
for (int i = 0; i < n; ++i) a[i] = (s[i] == 'L') ? 0 : 1;
int maxi = 0, mini = 0;
int cnt = 0;
int last = -1;
for (int i = n - 1; i >= 0; --i) {
if (a[i] == 0) {
++cnt;
} else {
if (cnt == 0) continue;
maxi += cnt;
mini = max(cnt, last + 1);
last = mini;
}
}
if (k < mini || k > maxi) {
cout << -1;
return 0;
}
bool is_min = false;
vector<int> have_step;
for (int i = 0; i < k; ++i) {
if (!is_min) {
auto steps = find_steps(a);
cout << min(int(steps.size()), maxi - k + i + 1) << ' ';
int cur = 0;
while (k - i - 1 < maxi && cur < steps.size()) {
cout << steps[cur] + 1 << ' ';
a[steps[cur]] = 0;
a[steps[cur] + 1] = 1;
++cur;
--maxi;
}
if (maxi == k - i - 1) {
is_min = true;
have_step = find_steps(a);
}
} else {
int v = have_step.back();
have_step.pop_back();
cout << "1 " << v + 1;
a[v] = 0;
a[v + 1] = 1;
if (v > 0 && a[v - 1] == 1) {
have_step.push_back(v - 1);
}
if (v + 2 < n && a[v + 2] == 0) {
have_step.push_back(v + 1);
}
}
cout << '\n';
}
}
|
1333
|
E
|
Road to 1600
|
Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!
Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess \textbf{rook} moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The \textbf{queen} walks in all directions vertically and diagonally at any distance. You can see the examples below.
To reach the goal, Egor should research the next topic:
There is an $N \times N$ board. Each cell of the board has a number from $1$ to $N ^ 2$ in it and numbers in all cells are distinct.
In the beginning, some chess figure stands in the cell with the number $1$. Note that this cell is already considered as visited. After that every move is determined by the following rules:
- Among all \textbf{not visited} yet cells to which the figure can get in one move, it goes to the cell that has \textbf{minimal} number.
- If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of $1$ \textbf{vun}.
- If all cells are already visited, the process is stopped.
Egor should find an $N \times N$ board on which the rook pays \textbf{strictly less vuns} than the queen during the round with this numbering. Help him to find such $N \times N$ numbered board, or tell that it doesn't exist.
|
First of all notice that there are no such boards for $N=1,2$. Then you can find an example for $N=3$ by yourself or with counting all cases with program. One of possible examples (I find it using paper, pencil and my hands): $N=3$: For large $N$ we can walk by spiral (like snake) to the case $N=3$. $N=4$: $N=5$: Rook and Queen first going in a spiral and arrive to $N=3$ case. It can be used any of such spiral, not just this one. Final time complexity: $O(N^2)$
|
[
"brute force",
"constructive algorithms"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
if (n < 3) {
cout << -1;
return 0;
}
vector<int> solution = {
1, 3, 4, 8, 2, 7, 9, 5, 6
};
vector<vector<int>> table(n, vector<int>(n, 0));
int cur = 1;
for (int i = 0; i < n - 3; ++i) {
if (i & 1) {
for (int j = n - 1; j >= 0; --j) {
table[i][j] = cur;
++cur;
}
} else {
for (int j = 0; j < n; ++j) {
table[i][j] = cur;
++cur;
}
}
}
if ((n - 3) & 1) {
for (int j = n - 1; j >= 0; --j) {
if (j & 1) {
for (int i = n - 3; i < n; ++i) {
if (j > 2) {
table[i][j] = cur;
++cur;
} else {
table[i][j] = solution[(2 - j) * 3 + i - n + 3] + n * n - 9;
}
}
} else {
for (int i = n - 1; i >= n - 3; --i) {
if (j > 2) {
table[i][j] = cur;
++cur;
} else {
table[i][j] = solution[(2 - j) * 3 + n - 1 - i] + n * n - 9;
}
}
}
}
} else {
for (int j = 0; j < n; ++j) {
if (j & 1) {
for (int i = n - 1; i >= n - 3; --i) {
if (j < n - 3) {
table[i][j] = cur;
++cur;
} else {
table[i][j] = solution[(j - n + 3) * 3 + n - 1 - i] + n * n - 9;
}
}
} else {
for (int i = n - 3; i < n; ++i) {
if (j < n - 3) {
table[i][j] = cur;
++cur;
} else {
table[i][j] = solution[(j - n + 3) * 3 + i - n + 3] + n * n - 9;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << table[i][j] << ' ';
}
cout << '\n';
}
}
|
1333
|
F
|
Kate and imperfection
|
Kate has a set $S$ of $n$ integers $\{1, \dots, n\} $.
She thinks that \textbf{imperfection} of a subset $M \subseteq S$ is equal to the \textbf{maximum} of $gcd(a, b)$ over all pairs $(a, b)$ such that both $a$ and $b$ are in $M$ and $a \neq b$.
Kate is a very neat girl and for each $k \in \{2, \dots, n\}$ she wants to find a subset that has the \textbf{smallest imperfection} among all subsets in $S$ of size $k$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $k$, will name it $I_k$.
Please, help Kate to find $I_2$, $I_3$, ..., $I_n$.
|
Let $A = \{a_1, a_2, ..., a_k\}$ be one of the possible subsets with smallest imperfection. If for any number $a_i$ in $A$ not all of its divisors contained in $A$ then we can replace $a_i$ with one of it divisor. The size os the subset does not change and imperfection may only decrease. Then we can assume that for any $a_i$ all of it divisors contained in $A$. Let $d(n)$ be the greatest divisor of $n$ exclude $n$ ($d(1)=1$). Since $A$ contains element with its divisors then smallest gcd of pair of an elements not less than maximum of $d(a_i)$ over elements of $A$ (because $A$ contains $a_i$ with $d(a_i)$). And for any element $a_i$ there is no element $a_j < a_i$ in $A$ with $gcd(a_i, a_j) > d(a_i)$ (because $d(a_i)$ is the greatest divisor). Then imperfection of $A$ is equal to greatest $d(a_i)$ over elements of $A$. After this observation we can just sort elements $\{1, ..., n\}$ by theirs $d(*)$ and take smallest $k$ for every $2 \le k \le n$. You can calculate $d(*)$ using the sieve of Eratosthenes. Final time complexity: $O(n \times log(n))$
|
[
"greedy",
"implementation",
"math",
"number theory",
"sortings",
"two pointers"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
vector<int> max_div;
void eratosthenes(int limit) {
max_div.assign(limit + 1, 0);
max_div[0] = limit + 10;
max_div[1] = 1;
for (int i = 2; i <= limit; ++i) {
if (max_div[i]) continue;
for (int j = i; j <= limit; j += i) {
if (max_div[j]) continue;
max_div[j] = j / i;
}
}
}
int main() {
int n; cin >> n;
eratosthenes(n);
sort(max_div.begin(), max_div.end());
for (int i = 1; i < n; ++i) {
cout << max_div[i] << ' ';
}
}
|
1334
|
A
|
Level Statistics
|
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $1$. If he manages to finish the level successfully then the number of clears increases by $1$ as well. \textbf{Note that both of the statistics update at the same time} (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).
Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.
So he peeked at the stats $n$ times and wrote down $n$ pairs of integers — $(p_1, c_1), (p_2, c_2), \dots, (p_n, c_n)$, where $p_i$ is the number of plays at the $i$-th moment of time and $c_i$ is the number of clears at the same moment of time. \textbf{The stats are given in chronological order} (i.e. the order of given pairs is exactly the same as Polycarp has written down).
Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.
Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.
Help him to check the correctness of his records.
For your convenience you have to answer multiple independent test cases.
|
Let's use the fact that initially the level has $0$ plays and $0$ clears. Call the differences before the previous stats and the current ones $\Delta p$ and $\Delta c$. The stats are given in chronological order, so neither the number of plays, nor the number of clears should decrease (i.e. $\Delta p \ge 0$ and $\Delta c \ge 0$). Finally, $\Delta p$ should be greater or equal to $\Delta c$. It's easy to show that if $\Delta c$ players pass the level successfully and $\Delta p - \Delta c$ players just try the level then such deltas are achieved. So in implementation it's enough to check these three conditions between the consecutive pieces of data (including the initial ($0, 0$)). Overall complexity: $O(n)$.
|
[
"implementation",
"math"
] | 1,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int tc;
scanf("%d", &tc);
while (tc--){
int n;
scanf("%d", &n);
int p = 0, c = 0;
bool fl = true;
forn(i, n){
int x, y;
scanf("%d%d", &x, &y);
if (x < p || y < c || y - c > x - p)
fl = false;
p = x, c = y;
}
puts(fl ? "YES" : "NO");
}
return 0;
}
|
1334
|
B
|
Middle Class
|
Many years ago Berland was a small country where only $n$ people lived. Each person had some savings: the $i$-th one had $a_i$ burles.
The government considered a person as wealthy if he had at least $x$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:
- the government chooses some subset of people (maybe all of them);
- the government takes all savings from the chosen people and redistributes the savings among the chosen people equally.
For example, consider the savings as list $[5, 1, 2, 1]$: if the government chose the $1$-st and the $3$-rd persons then it, at first, will take all $5 + 2 = 7$ burles and after that will return $3.5$ burles to the chosen people. As a result, the savings will become $[3.5, 1, 3.5, 1]$.
A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.
|
In fact, to carry out only one reform is always enough. And it's easy to prove if you make only one reform it's always optimal to take the maximum such $k$ that the average of $k$ maximums in the array $a$ is at least $x$ (i.e. sum greater or equal to $kx$). So the solution is next: sort array $a$ and find the suffix with maximum length $k$ such that the sum on the suffix is at least $kx$. === To prove the fact about one reform we can prove another fact: after each reform, the sum of $k$ maximums doesn't increase for each $k$. We'll prove it in two steps. The first step. Let's look at some reform and form an array $b$ from the chosen elements in $a$ in descending order. After the reform we'll get array $b'$ where all $b'[i] = \frac{1}{|b|} \sum_{i=1}^{|b|}{b[i]}$. Let's just skip the proof and say it's obvious enough that $\sum_{i=1}^{y}{b[i]} \ge \sum_{i=1}^{y}{b'[i]}$ for any $y$. The second step. Let fix $k$ and divide array $a$ on two parts: $k$ maximums as $a_1$ and other $n - k$ elements as $a_2$. And let's make the same division of $a'$ (the array after performing the reform) on $a'_1$ and $a'_2$. So, we need to prove that $sum(a'_1) \le sum(a_1)$. Suppose $m$ elements were chosen in the reform: $cnt$ of them were in $a_1$ and $cnt'$ now in $a'_1$. If $cnt \ge cnt'$ then we can think like maximum $cnt'$ elements from $cnt$ elements in $a$ were replaced by the average and other $cnt - cnt'$ were replaced by elements from $a_2$. Since $\sum_{i=1}^{cnt'}{b[i]} \ge \sum_{i=1}^{cnt'}{b'[i]}$ and any element from $a_1$ is greater or equal to any element from $a_2$ then we proved that $sum(a'_1) \le sum(a_1)$ when $cnt \ge cnt'$. If $cnt < cnt'$ then let's look at $a_2$ and $a'_2$. The $a_2$ has $m - cnt$ chosen elements and $a'_2$ has $m - cnt'$, so $m - cnt > m - cnt'$ and we can prove that $sum(a'_2) \ge sum(a_2)$ practically in the same way as before. Obviously, if $sum(a') = sum(a)$ and $sum(a'_2) \ge sum(a_2)$ then $sum(a'_1) \le sum(a_1)$. Q.E.D. The last step is easy, let's prove that the only reform is enough. The answer after several reforms is clearly equal to $k$ maximums which are at least $x$. But it means that the sum of $k$ maximums is at least $kx$, therefore the sum of $k$ maximums in the initial array is at least $kx$. So we can make them all at least $k$ by only one reform.
|
[
"greedy",
"sortings"
] | 1,100
|
fun main() {
val T = readLine()!!.toInt()
for (tc in 1..T) {
val (n, x) = readLine()!!.split(' ').map { it.toInt() }
val a = readLine()!!.split(' ').map { it.toInt() }.sortedDescending()
var cnt = 0
var sum = 0L
while (cnt < n && sum + a[cnt] >= (cnt + 1) * x.toLong()) {
sum += a[cnt]
cnt++
}
println(cnt)
}
}
|
1334
|
C
|
Circle of Monsters
|
You are playing another computer game, and now you have to slay $n$ monsters. These monsters are standing in a circle, numbered clockwise from $1$ to $n$. Initially, the $i$-th monster has $a_i$ health.
You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by $1$ (deals $1$ damage to it). Furthermore, when the health of some monster $i$ becomes $0$ or less than $0$, it dies and explodes, dealing $b_i$ damage to the next monster (monster $i + 1$, if $i < n$, or monster $1$, if $i = n$). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.
You have to calculate the minimum number of bullets you have to fire to kill all $n$ monsters in the circle.
|
We cannot utilize the explosion of the last monster we kill. So the naive approach is to iterate on the monster we kill the last, break the circle between this monster and the next one, and then shoot the first monster in the broken circle until it's dead, then the second one, and so on. Let's calculate the number of bullets we will fire this way. If the circle is broken after the monster $i$, then the first monster gets $a_{i + 1}$ bullets, the second one - $\max(0, a_{i + 2} - b_{i + 1})$, and so on; all monsters except the first one get exactly $\max(0, a_i - b_{i - 1})$ bullets. So we should choose an index $i$ such that $a_{i + 1} - \max(0, a_{i + 1} - b_i)$ is minimum possible, since this is the number of bullets we have to spend additionally since we cannot utilize the explosion of the $i$-th monster. After breaking the circle between the monsters $i$ and $i + 1$, you may use a formula to calculate the required number of bullets, or just model the shooting.
|
[
"brute force",
"constructive algorithms",
"greedy",
"math"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
typedef long long li;
const int N = 300 * 1000 + 13;
int n;
li a[N], b[N];
void solve() {
scanf("%d", &n);
forn(i, n) scanf("%lld%lld", &a[i], &b[i]);
li ans = 0, mn = 1e18;
forn(i, n) {
int ni = (i + 1) % n;
li val = min(a[ni], b[i]);
ans += a[ni] - val;
mn = min(mn, val);
}
ans += mn;
printf("%lld\n", ans);
}
int main() {
int T;
scanf("%d", &T);
forn(i, T)
solve();
}
|
1334
|
D
|
Minimum Euler Cycle
|
You are given a complete directed graph $K_n$ with $n$ vertices: each pair of vertices $u \neq v$ in $K_n$ have both directed edges $(u, v)$ and $(v, u)$; there are no self-loops.
You should find such a cycle in $K_n$ that visits every directed edge exactly once (allowing for revisiting vertices).
We can write such cycle as a list of $n(n - 1) + 1$ vertices $v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$ — a visiting order, where each $(v_i, v_{i + 1})$ occurs exactly once.
Find the \textbf{lexicographically smallest} such cycle. It's not hard to prove that the cycle always exists.
Since the answer can be too large print its $[l, r]$ segment, in other words, $v_l, v_{l + 1}, \dots, v_r$.
|
The solution of the problem can be found clearly in constructive way. An example for $n=5$: (1 2 1 3 1 4 1 5 (2 3 2 4 2 5 (3 4 3 5 (4 5 ()))) 1) where brackets mean that we call here some recursive function $calc$. Since on each level of recursion we have only $O(n)$ elements and there $O(n)$ levels then the generation of the certificate is quite easy: if on the currect level of recursion we can skip the whole part - let's just skip it. Otherwise let's build this part. Anyway, the built part of the cycle will have only $O(n + (r - l))$ length so the whole algorithm has $O(n + (r - l))$ complexity. The answer is lexicographically minimum by the construction, since on each level of recursion there is no way to build lexicographically smaller sequence.
|
[
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 1,800
|
#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;
int n;
li l, r;
inline bool read() {
if(!(cin >> n >> l >> r))
return false;
return true;
}
bool intersect(li l1, li r1, li l2, li r2) {
return min(r1, r2) > max(l1, l2);
}
vector<int> ans;
void calc(int lf, int rg, li &id) {
if(lf == rg) return;
if(intersect(l, r, id, id + 2 * (rg - lf))) {
fore(to, lf + 1, rg + 1) {
if(l <= id && id < r)
ans.push_back(lf);
id++;
if(l <= id && id < r)
ans.push_back(to);
id++;
}
} else
id += 2 * (rg - lf);
calc(lf + 1, rg, id);
if(lf == 0) {
if(l <= id && id < r)
ans.push_back(lf);
id++;
}
}
inline void solve() {
ans.clear();
li id = 0;
l--;
calc(0, n - 1, id);
assert(sz(ans) == r - l);
assert(id == n * li(n - 1) + 1);
for(int v : ans)
cout << v + 1 << " ";
cout << 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;
}
|
1334
|
E
|
Divisor Paths
|
You are given a positive integer $D$. Let's build the following graph from it:
- each vertex is a divisor of $D$ (not necessarily prime, $1$ and $D$ itself are also included);
- two vertices $x$ and $y$ ($x > y$) have an undirected edge between them if $x$ is divisible by $y$ and $\frac x y$ is a prime;
- the weight of an edge is the number of divisors of $x$ that are not divisors of $y$.
For example, here is the graph for $D=12$:
Edge $(4,12)$ has weight $3$ because $12$ has divisors $[1,2,3,4,6,12]$ and $4$ has divisors $[1,2,4]$. Thus, there are $3$ divisors of $12$ that are not divisors of $4$ — $[3,6,12]$.
There is no edge between $3$ and $2$ because $3$ is not divisible by $2$. There is no edge between $12$ and $3$ because $\frac{12}{3}=4$ is not a prime.
Let the length of the path between some vertices $v$ and $u$ in the graph be the total weight of edges on it. For example, path $[(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)]$ has length $1+2+2+3+1+2=11$. The empty path has length $0$.
So the shortest path between two vertices $v$ and $u$ is the path that has the minimal possible length.
Two paths $a$ and $b$ are different if there is either a different number of edges in them or there is a position $i$ such that $a_i$ and $b_i$ are different edges.
You are given $q$ queries of the following form:
- $v$ $u$ — calculate the \textbf{number of the shortest paths} between vertices $v$ and $u$.
The answer for each query might be large so print it modulo $998244353$.
|
Let's define the semantics of moving along the graph. On each step the current number is either multiplied by some prime or divided by it. I claim that the all shortest paths from $x$ to $y$ always go through $gcd(x, y)$. Moreover, the vertex numbers on the path first only decrease until $gcd(x, y)$ and only increase after it. Let's watch what happens to the divisors list on these paths. At first, all the divisors of $x$ that are not divisors of $y$ are removed from the list. Now we reach gcd and we start adding the divisors of $y$ that are missing from the list. The length of the path is this total number of changes to the list. That shows us that these paths are the shortest by definition. If we ever take a turn off that path, we either will add some divisor that we will need to remove later or remove some divisor that we will need to add later. That makes the length of the path not optimal. Now let's learn to calculate the number of paths. The parts before gcd and after it will be calculated separately, the answer is the product of answers for both parts. How many paths are there to gcd? Well, let's divide $x$ by $gcd$, that will give us the primes that should be removed from $x$. You can remove them in any order because the length of the path is always the same. That is just the number of their permutations with repetitions (you might also know that formula as multinomial coefficient). The number of paths from $gcd$ to $y$ is calculated the same way. To find the primes in $\frac{x}{gcd(x, y)}$ you can factorize $D$ beforehand and only iterate over the primes of $D$. Overall complexity: $O(\sqrt{D} + q \log D)$.
|
[
"combinatorics",
"graphs",
"greedy",
"math",
"number theory"
] | 2,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = 998244353;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
if (a < 0)
a += MOD;
return a;
}
int mul(int a, int b){
return a * 1ll * b % MOD;
}
int binpow(int a, int b){
int res = 1;
while (b){
if (b & 1)
res = mul(res, a);
a = mul(a, a);
b >>= 1;
}
return res;
}
int main() {
long long d;
scanf("%lld", &d);
int q;
scanf("%d", &q);
vector<long long> primes;
for (long long i = 2; i * i <= d; ++i) if (d % i == 0){
primes.push_back(i);
while (d % i == 0) d /= i;
}
if (d > 1){
primes.push_back(d);
}
vector<int> fact(100), rfact(100);
fact[0] = 1;
for (int i = 1; i < 100; ++i)
fact[i] = mul(fact[i - 1], i);
rfact[99] = binpow(fact[99], MOD - 2);
for (int i = 98; i >= 0; --i)
rfact[i] = mul(rfact[i + 1], i + 1);
forn(i, q){
long long x, y;
scanf("%lld%lld", &x, &y);
vector<int> up, dw;
for (auto p : primes){
int cnt = 0;
while (x % p == 0){
--cnt;
x /= p;
}
while (y % p == 0){
++cnt;
y /= p;
}
if (cnt < 0) dw.push_back(-cnt);
else if (cnt > 0) up.push_back(cnt);
}
int ans = 1;
ans = mul(ans, fact[accumulate(up.begin(), up.end(), 0)]);
for (auto it : up) ans = mul(ans, rfact[it]);
ans = mul(ans, fact[accumulate(dw.begin(), dw.end(), 0)]);
for (auto it : dw) ans = mul(ans, rfact[it]);
printf("%d\n", ans);
}
return 0;
}
|
1334
|
F
|
Strange Function
|
Let's denote the following function $f$. This function takes an array $a$ of length $n$ and returns an array. Initially the result is an empty array. For each integer $i$ from $1$ to $n$ we add element $a_i$ to the end of the resulting array if it is greater than all previous elements (more formally, if $a_i > \max\limits_{1 \le j < i}a_j$). Some examples of the function $f$:
- if $a = [3, 1, 2, 7, 7, 3, 6, 7, 8]$ then $f(a) = [3, 7, 8]$;
- if $a = [1]$ then $f(a) = [1]$;
- if $a = [4, 1, 1, 2, 3]$ then $f(a) = [4]$;
- if $a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10]$ then $f(a) = [1, 3, 6, 8, 11]$.
You are given two arrays: array $a_1, a_2, \dots , a_n$ and array $b_1, b_2, \dots , b_m$. You can delete some elements of array $a$ (possibly zero). To delete the element $a_i$, you have to pay $p_i$ coins (the value of $p_i$ can be negative, then you get $|p_i|$ coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality $f(a) = b$.
|
The "naive" version of the solution is just dynamic programming: let $dp_{i, j}$ be the minimum cost of removed elements (or the maximum cost of remaining elements) if we considered first $i$ elements of $a$, and the resulting sequence maps to the first $j$ elements of $b$. There are two versions of this solution, both working in $O(n^2)$: calculate this dp "as it is", so there are $O(nm)$ states and $O(1)$ transitions from each state; ensure that the $i$-th element is taken into $f(a)$, so there are $O(n)$ states (since each element appears in $b$ exactly once, the second state can be deduces from the first one), but up to $O(n)$ transitions from each state. It turns out that we can optimize the second approach. Let's calculate the values of $dp_i$ in ascending order of $a_i$: first of all, we calculate the values of $dp_i$ such that $a_i = b_1$, then transition into states such that $a_i = b_2$, and so on. Calculating $dp_i$ for $a_i = b_1$ is easy: since the first element of $a$ is always the first element of $f(a)$, we should delete all elements before the $i$-th if we want it to be the first element in $f(a)$. So, if $dp_i$ is the maximum possible sum of costs of remaining elements, if we considered the first $i$ elements of $a$ (and the $i$-th element gets included in $f(a)$), then $dp_i = c_i$ for indices $i$ such that $a_i = b_1$. Okay, now let's consider advancing from $b_k$ to $b_{k + 1}$. If we want to go from $dp_i$ to $dp_j$ such that $a_i = b_k$ and $a_j = b_{k + 1}$, we should leave the element $a_j$ in the array and delete some elements between indices $i$ and $j$. Which ones should be deleted? First of all, they are all elements with negative deletion cost; but we should also get rid of all elements which could replace $a_j$ in $f(a)$ - that is, all elements that are greater than $a_i$. So the remaining elements are $x$ which have $i < x < j$, $c_x > 0$ and $a_x \le a_i$, and we should be able to compute the sum of such elements. Even if we manage to do it in $O(\log n)$, which is possible, there may be up to $O(n^2)$ possible pairs of $dp_i$ and $dp_j$ to consider. The easiest way to get rid of that is to sort all occurences of $b_k$ and $b_{k + 1}$, and process them in ascending order, maintaining the best $dp_i$ that was already met. That way, each of the elements of $a$ will be considered at most twice, so this solution runs in $O(n \log n)$. We know how to calculate the $dp$ values now, but how to determine the answer? We should consider all values of $dp_i$ such that $a_i = b_m$ and delete all elements with negative costs and all elements that are greater than $a_i$ from the suffix $[i + 1, n]$ - so this is another query of the form "compute the sum of $c_x$ over $x$ which have $i < x < j$, $c_x > 0$ and $a_x \le a_i$". The most straightforward way to process them in $O(\log n)$ is to use a persistent segment tree, but since $a_i$ does not decrease in these queries as we process them, we may maintain the elements we are interested in with a much simpler data structure, for example, Fenwick tree.
|
[
"binary search",
"data structures",
"dp",
"greedy"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
typedef long long li;
const li INF64 = li(1e18);
const int N = 500043;
li f[N];
li get(int x)
{
li ans = 0;
for (; x >= 0; x = (x & (x + 1)) - 1)
ans += f[x];
return ans;
}
void inc(int x, li d)
{
for (; x < N; x = (x | (x + 1)))
f[x] += d;
}
li get(int l, int r)
{
return get(r) - get(l - 1);
}
li dp[N];
int a[N], b[N], p[N];
int n, m;
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
for(int i = 0; i < n; i++)
scanf("%d", &p[i]);
scanf("%d", &m);
for(int i = 0; i < m; i++)
scanf("%d", &b[i]);
for(int i = 0; i < n; i++)
dp[i] = -INF64;
map<int, vector<int> > pos;
for(int i = 0; i < n; i++)
pos[a[i]].push_back(i);
set<pair<int, int> > q;
for(int i = 0; i < n; i++)
q.insert(make_pair(a[i], i));
for(auto x : pos[b[0]])
dp[x] = p[x];
while(!q.empty() && q.begin()->first <= b[0])
{
int k = q.begin()->second;
q.erase(q.begin());
if(p[k] > 0)
inc(k, p[k]);
}
for(int i = 1; i < m; i++)
{
int i1 = b[i - 1], i2 = b[i];
vector<int> both_pos;
for(auto x : pos[i1])
both_pos.push_back(x);
for(auto x : pos[i2])
both_pos.push_back(x);
li best = -INF64;
int last = -1;
sort(both_pos.begin(), both_pos.end());
for(auto x : both_pos)
{
best += get(last + 1, x);
last = x;
if(a[x] == i1)
best = max(best, dp[x]);
else
dp[x] = best + p[x];
}
while(!q.empty() && q.begin()->first <= i2)
{
int k = q.begin()->second;
q.erase(q.begin());
if(p[k] > 0)
inc(k, p[k]);
}
}
li best_dp = -INF64;
for(int i = 0; i < n; i++)
if(a[i] == b[m - 1])
best_dp = max(best_dp, dp[i] + get(i + 1, n - 1));
li ans = 0;
for(int i = 0; i < n; i++)
ans += p[i];
ans -= best_dp;
if(ans > li(1e15))
puts("NO");
else
printf("YES\n%lld\n", ans);
}
|
1334
|
G
|
Substring Search
|
You are given a permutation $p$ consisting of exactly $26$ integers from $1$ to $26$ (since it is a permutation, each integer from $1$ to $26$ occurs in $p$ exactly once) and two strings $s$ and $t$ consisting of lowercase Latin letters.
A substring $t'$ of string $t$ is an \textbf{occurence} of string $s$ if the following conditions are met:
- $|t'| = |s|$;
- for each $i \in [1, |s|]$, either $s_i = t'_i$, or $p_{idx(s_i)} = idx(t'_i)$, where $idx(c)$ is the index of character $c$ in Latin alphabet ($idx(\text{a}) = 1$, $idx(\text{b}) = 2$, $idx(\text{z}) = 26$).
For example, if $p_1 = 2$, $p_2 = 3$, $p_3 = 1$, $s = \text{abc}$, $t = \text{abcaaba}$, then three substrings of $t$ are occurences of $s$ (they are $t' = \text{abc}$, $t' = \text{bca}$ and $t' = \text{aba}$).
For each substring of $t$ having length equal to $|s|$, check if it is an \textbf{occurence} of $s$.
|
We will run two tests for each substring of $t$ we are interested in. If at least one of them shows that the substring is not an occurence of $s$, we print 0, otherwise we print 1. The first test is fairly easy. The given permutation can be decomposed into cycles. Let's replace each character with the index of its cycle (in both strings) and check if each substring of $t$ is equal to $s$ after this replacement (for example, using regular KMP algorithm). If some substring is not equal to $s$ after the replacement, then it is definitely not an occurence. The second test will help us distinguish the characters belonging to the same cycle. Let $[c_1, c_2, \dots, c_k]$ be some cycle in our permutation (elements are listed in the order they appear in the cycle, so $p_{c_i} = c_{i + 1}$). We will replace each character with a complex number in such a way that the case when they match are easily distinguishable from the case when they don't match. One of the ways to do this is to replace $c_i$ with a complex number having magnitude equal to $1$ and argument equal to $\dfrac{2 \pi i}{k}$ (if this character belongs to $s$) or to $\dfrac{\pi - 2 \pi i}{k}$ (if this character belongs to $t$). How does this replacement help us checking the occurence? If we multiply the numbers for two matching characters, we get a complex number with argument equal to $\dfrac{\pi}{k}$ or to $-\dfrac{\pi}{k}$, and its real part will be $\cos \dfrac{\pi}{k}$. In any other case, the real part of the resulting number will be strictly less than $\cos \dfrac{\pi}{k}$, and the difference will be at least $0.06$. So, if we compute the value of $\sum \limits_{i = 1}^{|s|} f(s_i) \cdot f(t_{j + i - 1})$ for the $j$-th substring of $t$ (where $f(c)$ is the number that replaced the character $c$), we can check if the real part of the result is close to the value we would get if we matched $s$ with itself (and if the difference is big enough, at least one pair of characters didn't match). The only case when this method fails is if we try to match characters from different cycles of the permutation, that's why we needed the first test. Overall, the first test can be done in $O(|s| + |t|)$ using prefix function (or any other linear substring search algorithm), and the second test can be done in $O((|s| + |t|) \log(|s| + |t|))$, if we compute the aforementioned values for each substring using FFT.
|
[
"bitmasks",
"brute force",
"fft"
] | 2,900
|
#include<bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < n; i++)
#define sz(a) ((int)(a).size())
const int LOGN = 20;
const int N = (1 << LOGN);
typedef long double ld;
typedef long long li;
const ld PI = acos(-1.0);
struct comp
{
ld x, y;
comp(ld x = .0, ld y = .0) : x(x), y(y) {}
inline comp conj() { return comp(x, -y); }
};
inline comp operator +(const comp &a, const comp &b)
{
return comp(a.x + b.x, a.y + b.y);
}
inline comp operator -(const comp &a, const comp &b)
{
return comp(a.x - b.x, a.y - b.y);
}
inline comp operator *(const comp &a, const comp &b)
{
return comp(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
inline comp operator /(const comp &a, const ld &b)
{
return comp(a.x / b, a.y / b);
}
vector<comp> w[LOGN];
vector<int> rv[LOGN];
void precalc()
{
for(int st = 0; st < LOGN; st++)
{
w[st].assign(1 << st, comp());
for(int k = 0; k < (1 << st); k++)
{
double ang = PI / (1 << st) * k;
w[st][k] = comp(cos(ang), sin(ang));
}
rv[st].assign(1 << st, 0);
if(st == 0)
{
rv[st][0] = 0;
continue;
}
int h = (1 << (st - 1));
for(int k = 0; k < (1 << st); k++)
rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);
}
}
inline void fft(comp a[N], int n, int ln, bool inv)
{
for(int i = 0; i < n; i++)
{
int ni = rv[ln][i];
if(i < ni)
swap(a[i], a[ni]);
}
for(int st = 0; (1 << st) < n; st++)
{
int len = (1 << st);
for(int k = 0; k < n; k += (len << 1))
{
for(int pos = k; pos < k + len; pos++)
{
comp l = a[pos];
comp r = a[pos + len] * (inv ? w[st][pos - k].conj() : w[st][pos - k]);
a[pos] = l + r;
a[pos + len] = l - r;
}
}
}
if(inv) for(int i = 0; i < n; i++)
a[i] = a[i] / n;
}
comp aa[N];
comp bb[N];
comp cc[N];
inline void multiply(comp a[N], int sza, comp b[N], int szb, comp c[N], int &szc)
{
int n = 1, ln = 0;
while(n < (sza + szb))
n <<= 1, ln++;
for(int i = 0; i < n; i++)
aa[i] = (i < sza ? a[i] : comp());
for(int i = 0; i < n; i++)
bb[i] = (i < szb ? b[i] : comp());
fft(aa, n, ln, false);
fft(bb, n, ln, false);
for(int i = 0; i < n; i++)
cc[i] = aa[i] * bb[i];
fft(cc, n, ln, true);
szc = n;
for(int i = 0; i < n; i++)
c[i] = cc[i];
}
comp a[N];
comp b[N];
comp c[N];
vector<int> p_function(const vector<int>& v)
{
int n = v.size();
vector<int> p(n);
for(int i = 1; i < n; i++)
{
int j = p[i - 1];
while(j > 0 && v[j] != v[i])
j = p[j - 1];
if(v[j] == v[i])
j++;
p[i] = j;
}
return p;
}
int p[26];
char buf[N];
string s, t;
int main()
{
precalc();
for(int i = 0; i < 26; i++)
{
scanf("%d", &p[i]);
p[i]--;
}
scanf("%s", buf);
s = buf;
scanf("%s", buf);
t = buf;
int n = s.size();
int m = t.size();
vector<int> color(26, 0);
vector<vector<int> > cycles;
for(int i = 0; i < 26; i++)
{
if(color[i])
continue;
vector<int> cycle;
int cc = cycles.size() + 1;
int cur = i;
while(color[cur] == 0)
{
cycle.push_back(cur);
color[cur] = cc;
cur = p[cur];
}
cycles.push_back(cycle);
}
vector<int> ans(m - n + 1);
vector<int> s1, t1;
for(int i = 0; i < n; i++)
s1.push_back(color[int(s[i] - 'a')]);
for(int i = 0; i < m; i++)
t1.push_back(color[int(t[i] - 'a')]);
vector<int> st = s1;
st.push_back(0);
for(auto x : t1)
st.push_back(x);
vector<int> pf = p_function(st);
for(int i = 0; i < m - n + 1; i++)
if(pf[2 * n + i] == n)
ans[i] = 1;
map<char, comp> m1, m2;
for(auto cur : cycles)
{
int k = cur.size();
for(int i = 0; i < k; i++)
{
ld ang1 = 2 * PI * i / k;
ld ang2 = (PI - 2 * PI * i) / k;
m1[char('a' + cur[i])] = comp(cosl(ang1), sinl(ang1));
m2[char('a' + cur[i])] = comp(cosl(ang2), sinl(ang2));
}
}
ld ideal = 0;
for(int i = 0; i < n; i++)
ideal += (m1[s[i]] * m2[s[i]]).x;
reverse(s.begin(), s.end());
for(int i = 0; i < n; i++)
a[i] = m1[s[i]];
for(int i = 0; i < m; i++)
b[i] = m2[t[i]];
int szc;
multiply(a, n, b, m, c, szc);
for(int i = 0; i < m - n + 1; i++)
if(fabsl(c[i + n - 1].x - ideal) > 0.01)
ans[i] = 0;
for(int i = 0; i < m - n + 1; i++)
printf("%d", ans[i]);
return 0;
}
|
1335
|
A
|
Candies and Two Sisters
|
There are two sisters Alice and Betty. You have $n$ candies. You want to distribute these $n$ candies between two sisters in such a way that:
- Alice will get $a$ ($a > 0$) candies;
- Betty will get $b$ ($b > 0$) candies;
- each sister will get some \textbf{integer} number of candies;
- Alice will get a greater amount of candies than Betty (i.e. $a > b$);
- all the candies will be given to one of two sisters (i.e. $a+b=n$).
Your task is to calculate the number of ways to distribute exactly $n$ candies between sisters in a way described above. Candies are indistinguishable.
Formally, find the number of ways to represent $n$ as the sum of $n=a+b$, where $a$ and $b$ are positive integers and $a>b$.
You have to answer $t$ independent test cases.
|
The answer is $\lfloor\frac{n-1}{2}\rfloor$, where $\lfloor x \rfloor$ is $x$ rounded down.
|
[
"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;
cout << (n - 1) / 2 << endl;
}
return 0;
}
|
1335
|
B
|
Construct the String
|
You are given three positive integers $n$, $a$ and $b$. You have to construct a string $s$ of length $n$ consisting of lowercase Latin letters such that \textbf{each substring} of length $a$ has \textbf{exactly} $b$ distinct letters. It is guaranteed that the answer exists.
You have to answer $t$ independent test cases.
Recall that the substring $s[l \dots r]$ is the string $s_l, s_{l+1}, \dots, s_{r}$ and its length is $r - l + 1$. In this problem you are only interested in substrings of length $a$.
|
If we represent letters with digits, then the answer can be represented as $1, 2, \dots, b, 1, 2, \dots, b, \dots$. There is no substring containing more than $b$ distinct characters and each substring of length $a$ contains exactly $b$ distinct characters because of the condition $b \le a$. Time complexity: $O(n)$.
|
[
"constructive algorithms"
] | 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 n, a, b;
cin >> n >> a >> b;
for (int i = 0; i < n; ++i) {
cout << char('a' + i % b);
}
cout << endl;
}
return 0;
}
|
1335
|
C
|
Two Teams Composing
|
You have $n$ students under your control and you have to compose \textbf{exactly two teams} consisting of some subset of your students. Each student had his own skill, the $i$-th student skill is denoted by an integer $a_i$ (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the same size. Two more constraints:
- The first team should consist of students with \textbf{distinct} skills (i.e. all skills in the first team are unique).
- The second team should consist of students with \textbf{the same} skills (i.e. all skills in the second team are equal).
Note that it is permissible that some student of the first team has the same skill as a student of the second team.
Consider some examples (skills are given):
- $[1, 2, 3]$, $[4, 4]$ is not a good pair of teams because sizes should be the same;
- $[1, 1, 2]$, $[3, 3, 3]$ is not a good pair of teams because the first team should not contain students with the same skills;
- $[1, 2, 3]$, $[3, 4, 4]$ is not a good pair of teams because the second team should contain students with the same skills;
- $[1, 2, 3]$, $[3, 3, 3]$ is a good pair of teams;
- $[5]$, $[6]$ is a good pair of teams.
Your task is to find the maximum possible size $x$ for which it is possible to compose a valid pair of teams, where each team size is $x$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.
You have to answer $t$ independent test cases.
|
Let the number of students with the skill $i$ is $cnt_i$ and the number of different skills is $diff$. Then the size of the first team can not exceed $diff$ and the size of the second team can not exceed $maxcnt = max(cnt_1, cnt_2, \dots, cnt_n)$. So the answer is not greater than the minimum of these two values. Moreover, let's take a look at the skill with a maximum value of $cnt$. Then there are two cases: all students with this skill go to the second team then the sizes of teams are at most $diff-1$ and $maxcnt$ correspondingly. Otherwise, at least one student with this skill goes to the first team and the sizes are at most $diff$ and $maxcnt - 1$ correspondingly. So the answer is $max(min(diff - 1, maxcnt), min(diff, maxcnt - 1))$. Time complexity: $O(n)$.
|
[
"binary search",
"greedy",
"implementation",
"sortings"
] | 1,100
|
#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;
vector<int> cnt(n + 1);
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
++cnt[x];
}
int mx = *max_element(cnt.begin(), cnt.end());
int diff = n + 1 - count(cnt.begin(), cnt.end(), 0);
cout << max(min(mx - 1, diff), min(mx, diff - 1)) << endl;
}
return 0;
}
|
1335
|
D
|
Anti-Sudoku
|
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.
The picture showing the correct sudoku solution:
Blocks are bordered with bold black color.
Your task is to change \textbf{at most} $9$ elements of this field (i.e. choose some $1 \le i, j \le 9$ and change the number at the position $(i, j)$ to any other number in range $[1; 9]$) to make it \textbf{anti-sudoku}. The \textbf{anti-sudoku} is the $9 \times 9$ field, in which:
- Any number in this field is in range $[1; 9]$;
- each row contains at least two equal elements;
- each column contains at least two equal elements;
- each $3 \times 3$ block (you can read what is the block in the link above) contains at least two equal elements.
It is guaranteed that the answer exists.
You have to answer $t$ independent test cases.
|
Well, if we replace all occurrences of the number $2$ with the number $1$, then the initial solution will be anti-sudoku. It is easy to see that this replacement will make exactly two copies of $1$ in every row, column, and block. There are also other correct approaches but I found this one the most pretty.
|
[
"constructive algorithms",
"implementation"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
for (int i = 0; i < 9; ++i) {
string s;
cin >> s;
for (auto &c : s) if (c == '2') c = '1';
cout << s << endl;
}
}
return 0;
}
|
1335
|
E1
|
Three Blocks Palindrome (easy version)
|
\textbf{The only difference between easy and hard versions is constraints}.
You are given a sequence $a$ consisting of $n$ positive integers.
Let's define a \textbf{three blocks palindrome} as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are \textbf{three block palindromes} but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.
Your task is to choose the maximum by length \textbf{subsequence} of $a$ that is a \textbf{three blocks palindrome}.
You have to answer $t$ independent test cases.
Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.
|
Let's precalculate for each number $c$ ($0$-indexed) the array $pref_c$ of length $n+1$, where $pref_c[i]$ is the number of occurrences of the number $c$ on the prefix of length $i$. This can be done with easy dynamic programming (just compute prefix sums). Also let $sum(c, l, r)$ be $pref_c[r + 1] - pref_c[l]$ and it's meaning is the number of occurrences of the number $c$ on the segment $[l; r]$ ($0$-indexed). Firstly, let's update the answer with $\max\limits_{c=0}^{25} pref_c[n]$ (we can always take all occurrences of the same element as the answer). Then let's iterate over all possible segments of the array. Let the current segment be $[l; r]$. Consider that all occurrences of the element in the middle block belong to $a_l, a_{l+1}, \dots, a_r$. Then we can just take the most frequent number on this segment ($cntin = \max\limits_{c=0}^{25} sum(c, l, r)$). We also have to choose the number for the first and the last blocks. It is obvious that for the number $num$ the maximum amount of such numbers we can take is $min(sum(num, 0, l - 1), sum(num, r + 1, n - 1))$. So $cntout = \max\limits_{c=0}^{25} min(sum(c, 0, l - 1), sum(c, r + 1, n - 1))$. And we can update the answer with $2cntout + cntin$. Time complexity: $O(n^2 \cdot AL)$, where $AL$ is the size of alphabet (the maximum value of $a_i$).
|
[
"binary search",
"brute force",
"data structures",
"dp",
"two pointers"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
#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)
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;
vector<int> a(n);
for (auto &it : a) cin >> it;
vector<vector<int>> cnt(26, vector<int>(n + 1));
forn(i, n) {
forn(j, 26) cnt[j][i + 1] = cnt[j][i];
++cnt[a[i] - 1][i + 1];
}
int ans = 0;
forn(i, 26) ans = max(ans, cnt[i][n - 1]);
forn(l, n) fore(r, l, n) {
int cntin = 0, cntout = 0;
forn(el, 26) {
cntin = max(cntin, cnt[el][r + 1] - cnt[el][l]);
cntout = max(cntout, min(cnt[el][l], cnt[el][n] - cnt[el][r + 1]) * 2);
}
ans = max(ans, cntin + cntout);
}
cout << ans << endl;
}
return 0;
}
|
1335
|
E2
|
Three Blocks Palindrome (hard version)
|
\textbf{The only difference between easy and hard versions is constraints}.
You are given a sequence $a$ consisting of $n$ positive integers.
Let's define a \textbf{three blocks palindrome} as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are \textbf{three block palindromes} but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.
Your task is to choose the maximum by length \textbf{subsequence} of $a$ that is a \textbf{three blocks palindrome}.
You have to answer $t$ independent test cases.
Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.
|
I'll take some definitions from the solution of the easy version, so you can read it first if you don't understand something. Let $sum(c, l, r)$ be the number of occurrences of $c$ on the segment $[l; r]$. We will try to do almost the same solution as in the easy version. The only difference is how do we iterate over all segments corresponding to the second block of the required palindrome. Consider some number which we want to use as the number for the first and third blocks. If we take $k$ occurrences in the first block then we also take $k$ occurrences in the third block. Let's take these occurrences greedily! If we take $k$ elements in the first block (and also in the third block) then it is obviously better to take $k$ leftmost and $k$ rightmost elements correspondingly. Define $pos_c[i]$ be the position of the $i$-th occurrence of the number $c$ ($0$-indexed). So, if $pos_c$ is the array of length $sum(c, 0, n - 1)$ and contains all occurrences of $c$ in order from left to right then let's iterate over its left half and fix the amount of numbers $c$ we will take in the first block (and also in the third block). Let it be $k$. Then the left border of the segment for the second block is $l = pos_c[k - 1] + 1$ and the right border is $r = pos_c[sum(c, 0, n - 1) - k] - 1$. So let $cntin = \max\limits_{c=0}^{199} sum(c, l, r)$ and $cntout = k$ and we can update the answer with $2cntout + cntin$. It is easy to see that the total number of segments we consider is $O(n)$ so the total time complexity is $O(n \cdot AL)$ (there are also solutions not depending on the size of the alphabet, at least Mo's algorithm in $O(n \sqrt{n})$, but all of them are pretty hard to implement so I won't describe them here). And I'm also interested in $O(n \log n)$ solution, so if you know it, share it with us!
|
[
"brute force",
"data structures",
"dp",
"two pointers"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); ++i)
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;
vector<int> a(n);
for (auto &it : a) cin >> it;
vector<vector<int>> cnt(200, vector<int>(n + 1));
vector<vector<int>> pos(200);
forn(i, n) {
forn(j, 200) cnt[j][i + 1] = cnt[j][i];
++cnt[a[i] - 1][i + 1];
pos[a[i] - 1].push_back(i);
}
int ans = 0;
forn(i, 200) {
ans = max(ans, sz(pos[i]));
forn(p, sz(pos[i]) / 2) {
int l = pos[i][p] + 1, r = pos[i][sz(pos[i]) - p - 1] - 1;
forn(el, 200) {
int sum = cnt[el][r + 1] - cnt[el][l];
ans = max(ans, (p + 1) * 2 + sum);
}
}
}
cout << ans << endl;
}
return 0;
}
|
1335
|
F
|
Robots on a Grid
|
There is a rectangular grid of size $n \times m$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $(i, j)$ is $c_{i, j}$. You are also given a map of directions: for each cell, there is a direction $s_{i, j}$ which is one of the four characters 'U', 'R', 'D' and 'L'.
- If $s_{i, j}$ is 'U' then there is a transition from the cell $(i, j)$ to the cell $(i - 1, j)$;
- if $s_{i, j}$ is 'R' then there is a transition from the cell $(i, j)$ to the cell $(i, j + 1)$;
- if $s_{i, j}$ is 'D' then there is a transition from the cell $(i, j)$ to the cell $(i + 1, j)$;
- if $s_{i, j}$ is 'L' then there is a transition from the cell $(i, j)$ to the cell $(i, j - 1)$.
It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.
You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied.
- Firstly, each robot \textbf{should move} every time (i.e. it cannot skip the move). \textbf{During one move each robot goes to the adjacent cell depending on the current direction}.
- Secondly, you have to place robots in such a way that \textbf{there is no move} before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells $(1, 1)$ and $(1, 2)$, but if the grid is "RLL" then you cannot place robots in cells $(1, 1)$ and $(1, 3)$ because during the first second both robots will occupy the cell $(1, 2)$.
The robots make an infinite number of moves.
Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of \textbf{black} cells occupied by robots \textbf{before all movements} is the maximum possible. \textbf{Note that you can place robots only before all movements}.
You have to answer $t$ independent test cases.
|
First of all, I want to say about $O(nm)$ solution. You can extract cycles in the graph, do some dynamic programming on trees, use some hard formulas and so on, but it is a way harder to implement than the other solution that only has an additional log, so I'll describe the one which is easier to understand and much easier to implement. Firstly, consider the problem from the other side. What is this grid? It is a functional graph (such a directed graph that each its vertex has exactly one outgoing edge). This graph seems like a set of cycles and ordered trees going into these cycles. How can it help us? Let's notice that if two robots meet after some move, then they'll go together infinitely from this moment. It means that if we try to make at least $nm$ moves from each possible cell, we will obtain some "equivalence classes" (it means that if endpoints of two cells coincide after $nm$ moves then you cannot place robots in both cells at once). So, if we could calculate such endpoints, then we can take for each possible endpoint the robot starting from the black cell (if such exists) and otherwise the robot starting from the white cell (if such exists). How can we calculate such endpoints? Let's number all cells from $0$ to $nm-1$, where the number of the cell $(i, j)$ is $i \cdot m + j$. Let the next cell after $(i, j)$ is $(ni, nj)$ (i.e. if you make a move from $(i, j)$, you go to $(ni, nj)$). Also, let's create the two-dimensional array $nxt$, where $nxt[v][deg]$ means the number of the cell in which you will be if you start in the cell number $v$ and make $2^{deg}$ moves. What is the upper bound of $deg$? It is exactly $lognm = \lceil\log_{2}(nm + 1)\rceil$. Well, we need to calculate this matrix somehow. It is obvious that if the number of the cell $(i, j)$ is $id$ and the number of the next cell $(ni, nj)$ is $nid$ then $nxt[id][0] = nid$. Then let's iterate over all degrees $deg$ from $1$ to $lognm - 1$ and for each vertex $v$ set $nxt[v][deg] = nxt[nxt[v][deg - 1]][deg - 1]$. The logic behind this expresion is very simple: if we want to jump $2^{deg}$ times from $v$ and we have all values for $2^{deg - 1}$ calculated then let's just jump $2^{deg - 1}$ times from $v$ and $2^{deg - 1}$ times from the obtained vertex. This technique is called binary lifting. Now we can jump from every cell $nm$ times in $O(\log nm)$ time: just iterate over all degrees $deg$ from $0$ to $lognm-1$ and if $nm$ has the $deg$-th bit on, just jump from the current vertex $2^{deg}$ times (set $v := nxt[v][deg]$). The rest of solution is described above. Time complexity: $O(nm \log_{2}nm)$.
|
[
"data structures",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"matrices"
] | 2,200
|
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <fstream>
#include <cassert>
#include <cstring>
#include <unordered_set>
#include <unordered_map>
#include <numeric>
#include <ctime>
#include <bitset>
#include <complex>
#include <chrono>
#include <random>
#include <functional>
using namespace std;
const int N = 1e6 + 7;
const int K = 24;
int f[N];
int dp[N];
int ndp[N];
int sel[N];
int fans[N];
int sans[N];
void solve() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0; j < m; j++) {
sel[i * m + j] = (s[j] == '0');
}
}
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0; j < m; j++) {
int to = -1;
if (s[j] == 'U') to = (i - 1) * m + j;
if (s[j] == 'D') to = (i + 1) * m + j;
if (s[j] == 'L') to = i * m + (j - 1);
if (s[j] == 'R') to = i * m + (j + 1);
f[i * m + j] = to;
}
}
n *= m;
for (int i = 0; i < n; i++) {
dp[i] = f[i];
}
for (int j = 0; j < K; j++) {
for (int i = 0; i < n; i++) {
ndp[i] = dp[dp[i]];
}
for (int i = 0; i < n; i++) {
dp[i] = ndp[i];
}
}
fill(fans, fans + n, 0);
fill(sans, sans + n, 0);
for (int i = 0; i < n; i++) {
fans[dp[i]]++;
sans[dp[i]] += sel[i];
}
int fs = 0, ss = 0;
for (int i = 0; i < n; i++) {
fs += (fans[i] > 0);
ss += (sans[i] > 0);
}
cout << fs << ' ' << ss << '\n';
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int q;
cin >> q;
while (q--) {
solve();
}
}
|
1336
|
A
|
Linova and Kingdom
|
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
There are $n$ cities and $n-1$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $1$ to $n$, and the city $1$ is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose \textbf{exactly} $k$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each \textbf{industry city} sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of \textbf{tourism cities} on his path.
In order to be a queen loved by people, Linova wants to choose $k$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
|
Lemma: In the optimum solution, if a node (except the root) is chosen to develop tourism, its parent must be chosen to develop tourism, too. Proof: Otherwise, if we choose its parent to develop tourism instead of itself, the sum of happiness will be greater. Then we can calculate how much happiness we will get if we choose a certain node to develop tourism. Suppose the depth of node $u$ is $dep_u$ (i.e. there are $dep_u$ nodes on the path $(1,u)$), the size of the subtree rooted on $u$ is $siz_u$ (i.e. there are $siz_u$ nodes $v$ that $u$ is on the path $(1,v)$). Then, if we choose $u$ to develop tourism, compared to choose it to develop industry, the total happiness will be increased by $siz_u-dep_u$: the envoy of $u$ won't be sent, we will lose $dep_u-1$ happiness; a total of $siz_u-1$ envoys of all nodes in the subtree rooted on $u$ except $u$ itself will get one more happiness. So, just use DFS to calculate all $siz_u-dep_u$, then sort them from big to small, calculate the sum of the first $n-k$ elements. You can also use std::nth_element in STL to get an $O(n)$ solution.
|
[
"dfs and similar",
"dp",
"greedy",
"sortings",
"trees"
] | 1,600
|
#include <bits/stdc++.h>
#define maxn 200005
std::vector<int>conj[maxn];
int n,k,u,v,depth[maxn]={0},size[maxn]={0},det[maxn];
long long ans=0;
int cmp(int a,int b){return a>b;}
int dfs(int u,int f){depth[u]=depth[f]+1;size[u]=1;
for (int i=0;i<conj[u].size();++i){
if ((v=conj[u][i])==f)continue;
size[u]+=dfs(v,u);
}det[u]=size[u]-depth[u];return size[u];
}
int main(){
scanf("%d%d",&n,&k);
for (int i=1;i<n;++i){
scanf("%d%d",&u,&v);conj[u].push_back(v);conj[v].push_back(u);
}dfs(1,0);
std::nth_element(det+1,det+n-k,det+n+1,cmp);
for (int i=1;i<=n-k;++i)ans+=det[i];std::cout<<ans;
return 0;
}
|
1336
|
B
|
Xenia and Colorful Gems
|
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself.
Recently Xenia has bought $n_r$ red gems, $n_g$ green gems and $n_b$ blue gems. Each of the gems has a weight.
Now, she is going to pick three gems.
Xenia loves colorful things, so she will pick exactly one gem of each color.
Xenia loves balance, so she will try to pick gems with little difference in weight.
Specifically, supposing the weights of the picked gems are $x$, $y$ and $z$, Xenia wants to find the minimum value of $(x-y)^2+(y-z)^2+(z-x)^2$. As her dear friend, can you help her?
|
First, let's assume that there exists an optimum solution in which we choose $r_x$, $g_y$ and $b_z$ satisfying $r_x \le g_y \le b_z$. Here's a lemma: When $y$ is fixed, $r_x$ is the maximum one that $r_x \le g_y$, and $b_z$ is the minimum one that $g_y \le b_z$. It's easy to prove: no matter what $z$ is, the bigger $r_x$ is, the smaller $(r_x-g_y)^2$ and $(r_x-b_z)^2$ are; for $b_z$ it's similar. So, if we know that in one of the optimum solutions, $r_x \le g_y \le b_z$, we can sort each array at first and then find $x$ and $z$ by binary search or maintaining some pointers while enumerating $y$. Back to the original problem without $r_x \le g_y \le b_z$, we can enumerate the six possible situations: $r_x \le g_y \le b_z$, $r_x \le b_z \le g_y$, $g_y \le r_x \le b_z$, $g_y \le b_z \le r_x$, $b_z \le r_x \le g_y$ and $b_z \le g_y \le r_x$. Find the optimum solution in each situation and the optimum one among them is the answer.
|
[
"binary search",
"greedy",
"math",
"sortings",
"two pointers"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int t, nr, ng, nb;
long long ans;
long long sq(int x) { return 1ll * x * x; }
void solve(vector<int> a, vector<int> b, vector<int> c) {
for (auto x : a) {
auto y = lower_bound(b.begin(), b.end(), x);
auto z = upper_bound(c.begin(), c.end(), x);
if (y == b.end() || z == c.begin()) { continue; }
z--; ans = min(ans, sq(x - *y) + sq(*y - *z) + sq(*z - x));
}
}
int main() {
for (cin >> t; t; t--) {
cin >> nr >> ng >> nb;
vector<int> r(nr), g(ng), b(nb);
for (int i = 0; i < nr; i++) { cin >> r[i]; }
for (int i = 0; i < ng; i++) { cin >> g[i]; }
for (int i = 0; i < nb; i++) { cin >> b[i]; }
sort(r.begin(), r.end());
sort(g.begin(), g.end());
sort(b.begin(), b.end());
ans = 9e18;
solve(r, g, b); solve(r, b, g);
solve(g, b, r); solve(g, r, b);
solve(b, r, g); solve(b, g, r);
cout << ans << endl;
}
return 0;
}
|
1336
|
C
|
Kaavi and Magic Spell
|
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future.
Kaavi has a string $T$ of length $m$ and all the strings with the prefix $T$ are magic spells. Kaavi also has a string $S$ of length $n$ and an empty string $A$.
During the divination, Kaavi needs to perform a sequence of operations. There are two different operations:
- Delete the first character of $S$ and add it at the \textbf{front} of $A$.
- Delete the first character of $S$ and add it at the \textbf{back} of $A$.
Kaavi can perform \textbf{no more than} $n$ operations. To finish the divination, she wants to know the number of different operation sequences to make $A$ a magic spell (i.e. with the prefix $T$). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo $998\,244\,353$.
Two operation sequences are considered different if they are different in length or there exists an $i$ that their $i$-th operation is different.
A substring is a contiguous sequence of characters within a string. A prefix of a string $S$ is a substring of $S$ that occurs at the beginning of $S$.
|
We can use DP to solve this problem. Let $f_{i,j}$ be the answer when $S[0..i-1]$ has already been used and the current $A[0..\min(i-1,m-1-j)]$ will be in the position $[j..\min(i+j-1,m-1)]$ after all operations are finished. Specially, $f_{i,m}$ means that all characters in the current $A$ won't be in the position $[j..\min(i+j-1,m-1)]$ after all operations are finished. By definition, $f_{n,0}=1$ and $f_{n, j}=0 (j\ge 1)$. The state transition: $j=0$If $i\ge m$, $A$ has already had the prefix $T$, so you can stop performing operations at any position, there are $n-i+1$ positions in total. Otherwise, only when $S[i]=T[i]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,0}$ different operation sequences in this situation. If $i\ge m$, $A$ has already had the prefix $T$, so you can stop performing operations at any position, there are $n-i+1$ positions in total. Otherwise, only when $S[i]=T[i]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,0}$ different operation sequences in this situation. $1\le j \le m-1$If $i+j\ge m$ or $S[i]=T[i+j]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,j}$ different operation sequences in this situation. If $S[i]=T[j-1]$, you can add $S[i]$ at the front of $A$, there are $f_{i+1,j-1}$ different operation sequences in this situation. If $i+j\ge m$ or $S[i]=T[i+j]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,j}$ different operation sequences in this situation. If $S[i]=T[j-1]$, you can add $S[i]$ at the front of $A$, there are $f_{i+1,j-1}$ different operation sequences in this situation. $j=m$You can always add $S[i]$ at the front/back of $A$ in this situation ($2f_{i+1,m}$ different operation sequences). However, if $S[i]=T[m-1]$, you can let $S[i]$ to match $T[m-1]$ ($f_{i+1,m-1}$ different operation sequences). So, if $S[i]=T[m-1]$, $f_{i,m}=2f_{i+1,m}+f_{i+1,m-1}$. Otherwise, $f_{i,m}=2f_{i+1,m}$. You can always add $S[i]$ at the front/back of $A$ in this situation ($2f_{i+1,m}$ different operation sequences). However, if $S[i]=T[m-1]$, you can let $S[i]$ to match $T[m-1]$ ($f_{i+1,m-1}$ different operation sequences). So, if $S[i]=T[m-1]$, $f_{i,m}=2f_{i+1,m}+f_{i+1,m-1}$. Otherwise, $f_{i,m}=2f_{i+1,m}$. The answer is $2(f_{1,m}+\sum\limits_{T[i]=S[0]}f_{1,i})$.
|
[
"dp",
"strings"
] | 2,200
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int mod = 998244353;
int main()
{
string s, t;
cin >> s >> t;
int n = s.size();
int m = t.size();
vector<vector<int> > f(n + 1, vector<int>(m + 1));
f[n][0] = 1;
for (int i = n - 1; i >= 1; --i)
{
for (int j = 0; j <= m; ++j)
{
if (j == 0)
{
if (i >= m) f[i][0] = n - i + 1;
else if (s[i] == t[i]) f[i][0] = f[i + 1][0];
}
else if (j == m)
{
f[i][m] = 2 * f[i + 1][m] % mod;
if (s[i] == t[m - 1]) f[i][m] = (f[i][m] + f[i + 1][m - 1]) % mod;
}
else
{
if (i + j >= m || s[i] == t[i + j]) f[i][j] = f[i + 1][j];
if (s[i] == t[j - 1]) f[i][j] = (f[i][j] + f[i + 1][j - 1]) % mod;
}
}
}
int ans = f[1][m];
for (int i = 0; i < m; ++i) if (t[i] == s[0]) ans = (ans + f[1][i]) % mod;
ans = ans * 2 % mod;
cout << ans;
return 0;
}
|
1336
|
D
|
Yui and Mahjong Set
|
\textbf{This is an interactive problem.}
Yui is a girl who enjoys playing Mahjong.
She has a mysterious set which consists of tiles (this set can be empty). Each tile has an integer value between $1$ and $n$, and \textbf{at most $n$ tiles} in the set have the same value. So the set can contain at most $n^2$ tiles.
You want to figure out which values are on the tiles. But Yui is shy, she prefers to play a guessing game with you.
Let's call a set consisting of \textbf{three} tiles triplet if their values are the same. For example, $\{2,\,2,\,2\}$ is a triplet, but $\{2,\,3,\,3\}$ is not.
Let's call a set consisting of \textbf{three} tiles straight if their values are consecutive integers. For example, $\{2,\,3,\,4\}$ is a straight, but $\{1,\,3,\,5\}$ is not.
At first, Yui gives you the number of triplet subsets and straight subsets of the initial set respectively. After that, you can insert a tile with an integer value between $1$ and $n$ into the set \textbf{at most $n$ times}. Every time you insert a tile, you will get the number of triplet subsets and straight subsets of the current set as well.
Note that two tiles with the same value are treated different. In other words, in the set $\{1,\,1,\,2,\,2,\,3\}$ you can find $4$ subsets $\{1,\,2,\,3\}$.
Try to guess the number of tiles in the initial set with value $i$ for all integers $i$ from $1$ to $n$.
|
Suppose $c_i$ equals to the number of tiles in the current set with value $i$ (before making a query). If you insert a tile with value $x$: The delta of triplet subsets is $\dbinom{c_x}{2}$. Once you're sure that $c_x \neq 0$ holds, you can determine the exact value of $c_x$. The delta of straight subsets is $c_{x-2}c_{x-1}+c_{x-1}c_{x+1}+c_{x+1}c_{x+2}$. Once you've known the values of $c_{1} \ldots c_{x+1}$ and you're sure that $c_{x+1} \neq 0$, you can determine the exact value of $c_{x+2}$. Let's insert tiles with following values in order: $n-1$, $n-2$, $\ldots$, $3$, $1$, $2$, $1$. We can easily get $a_1$ by the delta of triplet subsets since we insert tiles with value $1$ twice. Consider the delta of straight subsets when you insert the tile with value $1$. It equals to $a_2(a_3+1)$ for the first time and $(a_2+1)(a_3+1)$ for the second time. Use subtraction to get $a_3$, then use division to get $a_2$. (The divisor is $a_3+1$, which is non-zero) Finally, let do the following for each $x$ from $2$ to $n-2$. We've known the values of $a_{1} \ldots a_{x+1}$. Since we've inserted a tile with value $x+1$ before inserting $x$, we can use division to get $a_{x+2}$ by the delta of straight subsets and avoid dividing zero. PinkRabbitAFO gives another solution which inserts tiles with value $1$, $2$, $\ldots$, $n-1$, $1$ in order. See more details here.
|
[
"constructive algorithms",
"interactive"
] | 3,200
|
#include <cstdio>
const int MN = 105;
int N, lstv1, lstv2, v1, v2;
int dv1[MN], dv2[MN], Tag[MN], Ans[MN];
int main() {
scanf("%d", &N);
scanf("%d%d", &lstv1, &lstv2);
for (int i = 1; i < N; ++i) {
printf("+ %d\n", i), fflush(stdout);
scanf("%d%d", &v1, &v2);
dv1[i] = v1 - lstv1, dv2[i] = v2 - lstv2;
if (dv1[i] > 0)
for (int x = 2; x <= N; ++x)
if (x * (x - 1) / 2 == dv1[i]) {
Tag[i] = x; break;
}
lstv1 = v1, lstv2 = v2;
}
printf("+ 1\n"), fflush(stdout);
scanf("%d%d", &v1, &v2);
int ndv1 = v1 - lstv1, ndv2 = v2 - lstv2;
for (int x = 0; x <= N; ++x)
if (x * (x + 1) / 2 == ndv1) {
Ans[1] = x; break;
}
int delta = ndv2 - dv2[1] - 1; // delta = a[2] + a[3]
if (Tag[2] >= 2) Ans[2] = Tag[2], Ans[3] = delta - Ans[2];
else if (Tag[3] >= 2) Ans[3] = Tag[3], Ans[2] = delta - Ans[3];
else if (delta == 0) Ans[3] = Ans[2] = 0;
else if (delta == 2) Ans[3] = Ans[2] = 1;
else if (dv2[2] > 0) Ans[2] = 0, Ans[3] = 1;
else Ans[2] = 1, Ans[3] = 0;
for (int i = 3; i <= N - 2; ++i) {
if (Tag[i + 1] >= 2) {
Ans[i + 1] = Tag[i + 1];
continue;
}
if ((Ans[i - 2] + 1) * (Ans[i - 1] + 1) == dv2[i]) Ans[i + 1] = 0;
else Ans[i + 1] = 1;
}
Ans[N] = (dv2[N - 1] - (Ans[N - 3] + 1) * (Ans[N - 2] + 1)) / (Ans[N - 2] + 1);
printf("!");
for (int i = 1; i <= N; ++i) printf(" %d", Ans[i]);
puts(""), fflush(stdout);
return 0;
}
|
1336
|
E2
|
Chiori and Doll Picking (hard version)
|
This is the hard version of the problem. The only difference between easy and hard versions is the constraint of $m$. You can make hacks only if both versions are solved.
Chiori loves dolls and now she is going to decorate her bedroom!
As a doll collector, Chiori has got $n$ dolls. The $i$-th doll has a non-negative integer value $a_i$ ($a_i < 2^m$, $m$ is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are $2^n$ different picking ways.
Let $x$ be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls $x = 0$). The value of this picking way is equal to the number of $1$-bits in the binary representation of $x$. More formally, it is also equal to the number of indices $0 \leq i < m$, such that $\left\lfloor \frac{x}{2^i} \right\rfloor$ is odd.
Tell her the number of picking ways with value $i$ for each integer $i$ from $0$ to $m$. Due to the answers can be very huge, print them by modulo $998\,244\,353$.
|
Build linear basis $A$ with given numbers. Suppose: $k$ is the length of $A$. $S(A)$ is the set consisted of numbers which can be produced in $A$. $p_i$ is equal to the number of $x$, where $x \in S(A)$ and $\text{popcount}(x)=i$. $ans_i$ is equal to the number of doll picking ways with value $i$. Thus, $ans_i = p_i \cdot 2^{n-k}$. Algorithm 1 Enumerate each base of $A$ is picked or not, so you can find out the whole $S(A)$ in $O(2^k)$ and get $p_0 \ldots p_m$. Note that you should implement $\text{popcount}(x)$ in $O(1)$ to make sure the whole algorithm runs in $O(2^k)$. Algorithm 2 Let's assume the highest $1$-bits in every base are key bits, so in $A$ there are $k$ key bits and $m-k$ non-key bits. We can get a new array of bases by Gauss-Jordan Elimination, such that every key bit is $1$ in exactly one base and is $0$ in other bases. Then, let $f_{i,j,s}$ be if we consider the first $i$ bases in $A$, the number of ways that $j$ key bits are $1$ in xor-sum and the binary status of all non-key bits is $s$. Enumerate $i$-th base (suppose it is equal to $x$) is picked or not, we write the state transition: $f_{i,j,s} = f_{i-1,j,s}+f_{i-1,j-1,s \oplus x}$. At last, we add up $f_{k,j,s}$ to $p_{j+\text{popcount}(s)}$. In conclusion, we get an $O(k^2 \cdot 2^{m-k})$ algorithm. So far, the easy version can be passed if you write a solution which runs Algorithm 1 or Algorithm 2 by the value of $k$. Algorithm 3 We can regard $A$ as a $2^m$ long zero-indexation array satisfying $a_i=[i \in S(A)]$. Similarly, we define a $2^m$ long zero-indexation array $F^c$ satisfying $f^c_i=[\text{popcount}(i)=c]$. By XOR Fast Walsh-Hadamard Transform, we calculate $\text{IFWT}(\text{FWT}(A) * \text{FWT}(F^c))$ (also can be written as $A \oplus F^c$). $p_c$ is equal to the $0$-th number of resulting array. That means $p_c$ is also equal to the sum of every number in $\text{FWT}(A) * \text{FWT}(F^c)$ divide $2^m$. Lemma 1: $\text{FWT}(A)$ only contains two different values: $0$ and $2^k$. Proof: The linear space satisfies closure, which means $A \oplus A = A * 2^k$. Thus, $\text{FWT}(A) * \text{FWT}(A) = \text{FWT}(A) * 2^k$. We can proved the lemma by solving an equation. Lemma 2: The $i$-th number of $\text{FWT}(A)$ is $2^k$, if and only if $\text{popcount}(i\ \&\ x)$ is always even, where $x$ is any of $k$ bases in $A$. Proof: XOR Fast Walsh-Hadamard Transform tells us, the $i$-th number of $\text{FWT}(A)$ is equal to the sum of $(-1)^{\text{popcount}(i\ \&\ j)}$ for each $j \in S(A)$. Once we find a base $x$ such that $\text{popcount}(i\ \&\ x)$ is odd, the sum must be $0$ according to Lemma 1. Lemma 3: The indices of $\text{FWT}(A)$ which their values are $2^k$, compose an orthogonal linear basis. Proof: See Lemma 2. If $\text{popcount}(i\ \&\ x)$ is even, $\text{popcount}(j\ \&\ x)$ is even, obviously $\text{popcount}((i \oplus j)\ \&\ x)$ is even. Lemma 4: Suppose $B$ is the orthogonal linear basis. The length of $B$ is $m-k$. Proof: We know that $A=\text{IFWT}(B*2^k)$, so $a_0 = 1 = \dfrac{1}{2^m}\sum\limits_{i=0}^{2^m-1} b_i \cdot 2^k$. From this, we then find that $|S(B)|$ should be $2^{m-k}$, which means the length of $B$ is $m-k$. Let the key bits in $A$ are non-key bits in $B$ and the non-key bits in $A$ are key bits in $B$. Now I'll show you how to get the $m-k$ bases in $B$. Divide key bits for $A$ and put them to the left. Similarly, we put the key bits in $B$ to the right. Let's make those $1$ key bits form a diagonal. Look at the following picture. Do you notice that the non-key bit matrices (green areas) are symmetrical along the diagonal? The proof is intuitive. $\text{popcount}(x\ \&\ y)$ should be even according to Lemma 2, where $x$ is any of bases in $A$ and $y$ is any of bases in $B$. Since we've divided key bits for two linear basis, $\text{popcount}(x\ \&\ y)$ is not more than $2$. Once two symmetrical non-key bits are $0$, $1$ respectively, there will exist $x$, $y$ satisfying $\text{popcount}(x\ \&\ y) = 1$. Otherwise, $\text{popcount}(x\ \&\ y)$ is always $0$ or $2$. In order to get $B$, you can also divide $A$ into $k$ small linear basis, construct their orthogonal linear basis and intersect them. It is harder to implement. Lemma 5: The $i$-th number of $\text{FWT}(F^c)$ only depends on $\text{popcount}(i)$. Proof: The $i$-th number of $F^c$ only depends on $\text{popcount}(i)$, so it still holds after Fast Walsh-Hadamard Transform. Let $w_d^c$ be the $(2^d-1)$-th number of $\text{FWT}(F^c)$. Again, Fast Walsh-Hadamard Transform tells us: $w_d^c = \sum\limits_{i=0}^{2^m-1} [\text{popcount}(i)=c](-1)^{\text{popcount}(i\ \&\ (2^d-1))}$ Note that $\text{popcount}(2^d-1)=d$. Let's enumerate $j = \text{popcount}(i\ \&\ (2^d-1))$. There are $\dbinom{d}{j}$ different intersections, each one has $\dbinom{m-d}{c-j}$ ways to generate the remaining part of $i$. So: $w_d^c = \sum\limits_{j=0}^{d} (-1)^j \dbinom{d}{j}\dbinom{m-d}{c-j}$ It takes $O(m^3)$ to calculate all necessary combinatorial numbers and $w_d^c$. Finally, let's consider the sum of every number in $\text{FWT}(A) * \text{FWT}(F^c)$. Suppose $q_i$ is equal to the number of $x$, where $x \in S(B)$ and $\text{popcount}(x)=i$. We can easily get: $p_c = \dfrac{1}{2^m}\sum\limits_{d=0}^{m} 2^k q_d w_d^c = \dfrac{1}{2^{m-k}}\sum\limits_{d=0}^{m} q_d w_d^c$ Just like Algorithm 1. We can enumerate each base of $B$ is picked or not, find out the whole $S(B)$ in $O(2^{m-k})$, get $q_0 \ldots q_m$ and calculate $p_0 \ldots p_m$ at last. Since one of $A$, $B$ has a length of not more than $m/2$, we just need to enumerate bases of the smaller one in order to pass the hard version in $O(2^{m/2} + m^3 + n)$. Solve the same problem with $m \le 63$.
|
[
"bitmasks",
"brute force",
"combinatorics",
"math"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353, inv2 = 499122177;
const int M = 64;
int n, m, k, p[M], c[M][M];
long long a[M], b[M], f[M];
void dfs(int i, long long x) {
if (i == k) { p[__builtin_popcountll(x)]++; return; }
dfs(i + 1, x); dfs(i + 1, x ^ a[i]);
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
long long x; cin >> x;
for (int j = m; j >= 0; j--) {
if (x >> j & 1) {
if (!f[j]) { f[j] = x; break; }
x ^= f[j];
}
}
}
for (int i = 0; i < m; i++) {
if (f[i]) {
for (int j = 0; j < i; j++) {
if (f[i] >> j & 1) { f[i] ^= f[j]; }
}
for (int j = 0; j < m; j++) {
if (!f[j]) { a[k] = a[k] * 2 + (f[i] >> j & 1); }
}
a[k] |= 1ll << m - 1 - k; k++;
}
}
if (k <= 26) {
dfs(0, 0);
for (int i = 0; i <= m; i++) {
int ans = p[i];
for (int j = 0; j < n - k; j++) { ans = ans * 2 % mod; }
cout << ans << " ";
}
} else {
k = m - k; swap(a, b);
for (int i = 0; i < k; i++) {
for (int j = 0; j < m - k; j++) {
if (b[j] >> i & 1) { a[i] |= 1ll << j; }
}
a[i] |= 1ll << m - 1 - i;
}
dfs(0, 0);
for (int i = 0; i <= m; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++) { c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; }
}
for (int i = 0; i <= m; i++) {
int ans = 0;
for (int j = 0; j <= m; j++) {
int coef = 0;
for (int k = 0; k <= i; k++) {
coef = (coef + (k & 1 ? -1ll : 1ll) * c[j][k] * c[m - j][i - k] % mod + mod) % mod;
}
ans = (ans + 1ll * coef * p[j]) % mod;
}
for (int j = 0; j < k; j++) { ans = 1ll * ans * inv2 % mod; }
for (int j = 0; j < n - m + k; j++) { ans = ans * 2 % mod; }
cout << ans << " ";
}
}
return 0;
}
|
1336
|
F
|
Journey
|
In the wilds far beyond lies the Land of Sacredness, which can be viewed as a tree — connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$.
There are $m$ travelers attracted by its prosperity and beauty. Thereupon, they set off their journey on this land. The $i$-th traveler will travel along the shortest path from $s_i$ to $t_i$. In doing so, they will go through all edges in the shortest path from $s_i$ to $t_i$, which is unique in the tree.
During their journey, the travelers will acquaint themselves with the others. Some may even become friends. To be specific, the $i$-th traveler and the $j$-th traveler will become friends if and only if there are \textbf{at least} $k$ edges that both the $i$-th traveler and the $j$-th traveler will go through.
Your task is to find out the number of pairs of travelers $(i, j)$ satisfying the following conditions:
- $1 \leq i < j \leq m$.
- the $i$-th traveler and the $j$-th traveler will become friends.
|
Idea: EternalAlexander First, let's choose an arbitrary root for the tree. Then for all pairs of paths, their LCA (lowest common ancestor) can be either different or the same. Then, let's calculate the answer of pairs with different LCAs. In this case, if the intersection is not empty, it will be a vertical path as in the graph below. Here path $G-H$ and path $E-F$ intersects at path $B-G$. We can process all paths in decreasing order of the depth of their LCA. When processing a path $p$ we calculate the number of paths $q$, where $q$ is processed before $p$, and the edge-intersection of $p$ and $q$ is at least $k$. To do this we can plus one to the subtree of the nodes on the path $k$ edges away from the LCA (node $C$ and $D$ for path $G-H$ in the graph above), then we can query the value at the endpoints of the path (node $E$ and $F$ for path $E-F$). We can maintain this easily with BIT (binary indexed tree, or Fenwick tree). Next, we calculate pairs with the same LCA. This case is harder. For each node $u$ we calculate the number of pairs with the LCA $u$. For a pair of path $(x_1,y_1)$ and $(x_2, y_2)$, there are still two cases we need to handle. Let $dfn_x$ be the index of $x$ in the DFS order. For a path $(x,y)$ we assume that $dfn_x < dfn_y$ (otherwise you can just swap them) In the first case ( the right one in the graph above, where $(x_1,y_1) = (B,E), (x_2,y_2) = (C,F)$ ), the intersection of $(x_1,y_1)$ and $(x_2,y_2)$ is the path that goes from $\operatorname{LCA}(x_1,x_2)$ to $\operatorname{LCA}(y_1,y_2)$ (path $A - D$) In this case the intersection may cross over node $u$. For all paths $(x,y)$ with the LCA $u$. We can build a virtual-tree over all $x$ of the paths, and on node $x$ we store the value of $y$. Let's do a dfs on the virtual-tree. On each node $a$ we calculate pairs $(x_1,y_1)$,$(x_2,y_2)$ that $\operatorname{LCA}(x_1,x_2) = a$. For $x_1$ , let's go from $a$ to $y_1$ for $k$ edges, assume the node we reached is $b$, all legal $y_2$ should be in the subtree of $b$. We can use a segment tree on the DFS-order to maintain all $y$s in the subtree and merge them with the small-to-large trick, meanwhile, iterate over all $x_1$ in the smaller segment tree, count the valid $y_2$'s in the larger segment tree. In fact, you can use HLD (heavy-light decomposition) instead of virtual-tree, which seems to be easier to implement. Now note that the solution above is based on the fact that the intersection of $(x_1,y_1)$ and $(x_2,y_2)$ is the path that goes from $\operatorname{LCA}(x_1,x_2)$ to $\operatorname{LCA}(y_1,y_2)$. But it is not always true, so here we have another case to handle. In this case, (the left one in the graph above), the intersection is definitely a vertical path that goes from $u$ to $\operatorname{LCA(y_1,x_2)}$. This can be solved similarly to the case of different LCAs. The overall complexity of this solution is $O(m \log^2 m + n\log n)$.
|
[
"data structures",
"divide and conquer",
"graphs",
"trees"
] | 3,500
|
#include <bits/stdc++.h>
#define maxn 200005
int n,m,k,u[maxn],v[maxn],ch[maxn<<6][2]={0},sum[maxn<<6]={0},pt[maxn],head[maxn]={0},tail=0,cnt=0,root[maxn]={0},
anc[maxn][19]={0},son[maxn]={0},depth[maxn]={0},dfn[maxn],size[maxn],idx=0;
long long ans=0;
std::vector<int>in[maxn],vec[maxn];
struct edge {
int v,next;
}edges[maxn<<1];
void add_edge(int u,int v){
edges[++tail].v=v;
edges[tail].next=head[u];
head[u]=tail;
}
namespace BIT {
int sum[maxn<<2]={0};
void add(int p,int x) {if (p==0) return;while (p<=n) {sum[p]+=x;p+=p&-p;}}
int query(int p) {int ans=0;while (p>0) {ans+=sum[p];p-=p&-p;}return ans;}
void Add(int l,int r){add(l,1);add(r+1,-1);}
}
void update(int x){sum[x]=sum[ch[x][0]]+sum[ch[x][1]];}
int insert(int rt,int l,int r,int p){
if (!rt) rt=++cnt;
if (l==r) {sum[rt]++;return rt;}
int mid=(l+r)>>1;
if (p<=mid) ch[rt][0]=insert(ch[rt][0],l,mid,p);
else ch[rt][1]=insert(ch[rt][1],mid+1,r,p);
update(rt);
return rt;
} int merge(int u,int v){
if (!u||!v)return u+v;
ch[u][0]=merge(ch[u][0],ch[v][0]);
ch[u][1]=merge(ch[u][1],ch[v][1]);
sum[u]=sum[u]+sum[v];return u;
} int query(int rt,int L,int R,int l,int r){
if (l>R||r<L)return 0;
if (l<=L&&R<=r){return sum[rt];}
return query(ch[rt][0],L,(L+R)>>1,l,r)+query(ch[rt][1],((L+R)>>1)+1,R,l,r);
}
void dfs1(int u,int f){
anc[u][0]=f;depth[u]=depth[f]+1;size[u]=1;
for (int i=1;i<=18;++i)anc[u][i]=anc[anc[u][i-1]][i-1];
for (int i=head[u];i;i=edges[i].next){
int v=edges[i].v;
if (v==f) continue;
dfs1(v,u);size[u]+=size[v];
if (size[v]>size[son[u]])son[u]=v;
}
} void dfsn(int u){
dfn[u]=++idx;
for (int i=head[u];i;i=edges[i].next){
int v=edges[i].v;
if (v==son[u]||v==anc[u][0])continue;
dfsn(v);
}if (son[u]) dfsn(son[u]);
}
int lift(int u,int x){
for (int i=18;i>=0;i--)if (x>=(1<<i)) {u=anc[u][i];x-=(1<<i);}
return u;
}
int lca(int u,int v){
if (depth[u]<depth[v])std::swap(u,v);
for (int i=18;i>=0;i--)if (depth[anc[u][i]]>=depth[v])u=anc[u][i];
if (u==v)return u;
for (int i=18;i>=0;i--)if (anc[u][i]!=anc[v][i]){u=anc[u][i];v=anc[v][i];}
return anc[u][0];
}
void dfs3(int x,int rt){
pt[x]=x;root[x]=0;
for (int i=0;i<in[x].size();++i) {
int d=in[x][i];
int rd=std::max(0,k-(depth[u[d]]-depth[rt]));
if (depth[v[d]]-depth[rt]>=rd){
int l=lift(v[d],depth[v[d]]-depth[rt]-rd);
ans+=query(root[x],1,n,dfn[l],dfn[l]+size[l]-1);
}root[x]=insert(root[x],1,n,dfn[v[d]]);
}for (int i=head[x];i;i=edges[i].next){
int t=edges[i].v;
if (t==anc[x][0]||(rt==x&&t==son[x])) continue;
dfs3(t,rt);
if (in[pt[x]].size()<in[pt[t]].size()){
std::swap(pt[x],pt[t]);
std::swap(root[x],root[t]);
}while (!in[pt[t]].empty()){
int d=in[pt[t]][in[pt[t]].size()-1];in[pt[t]].pop_back();
int rd=std::max(0,k-(depth[x]-depth[rt]));
if (depth[v[d]]-depth[rt]>=rd) {
int l=lift(v[d],(depth[v[d]]-depth[rt]-rd));
ans+=query(root[x],1,n,dfn[l],dfn[l]+size[l]-1);
}in[pt[x]].push_back(d);
}root[x]=merge(root[x],root[t]);
}
}
void dfs2(int x){
int len=vec[x].size();
for (int i=head[x];i;i=edges[i].next)if (edges[i].v!=anc[x][0])dfs2(edges[i].v);
for (int i=0;i<len;++i)ans+=BIT::query(dfn[v[vec[x][i]]]);
for (int i=0;i<len;++i){
int j=vec[x][i];
if (depth[v[j]]-depth[x]>=k) {
int l=lift(v[j],depth[v[j]]-depth[x]-k);
BIT::Add(dfn[l],dfn[l]+size[l]-1);
}
}for (int i=0;i<len;++i){ans+=BIT::query(dfn[u[vec[x][i]]]);in[u[vec[x][i]]].push_back(vec[x][i]);}
dfs3(x,x);
while (!in[pt[x]].empty())in[pt[x]].pop_back();
for (int i=0;i<len;++i){
int j=vec[x][i];
if (depth[u[j]]-depth[x]>=k) {
int l=lift(u[j],depth[u[j]]-depth[x]-k);
BIT::Add(dfn[l],dfn[l]+size[l]-1);
}
}
}
int main(){
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<n;++i){
int u,v;
scanf("%d%d",&u,&v);
add_edge(u,v);
add_edge(v,u);
}dfs1(1,0);dfsn(1);
for (int i=1;i<=m;++i){
scanf("%d%d",&u[i],&v[i]);
if (dfn[u[i]]>dfn[v[i]]) std::swap(u[i],v[i]);
int l=lca(u[i],v[i]);
vec[l].push_back(i);
} dfs2(1);
std::cout<<ans;
return 0;
}
|
1337
|
A
|
Ichihime and Triangle
|
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
You are given four positive integers $a$, $b$, $c$, $d$, such that $a \leq b \leq c \leq d$.
Your task is to find three integers $x$, $y$, $z$, satisfying the following conditions:
- $a \leq x \leq b$.
- $b \leq y \leq c$.
- $c \leq z \leq d$.
- There exists a triangle with a positive non-zero area and the lengths of its three sides are $x$, $y$, and $z$.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
|
There are many possible solutions, one of them is to always output $b$, $c$, $c$. You can easily prove that $b$, $c$, $c$ always satisfies the requirements.
|
[
"constructive algorithms",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int t, a, b, c, d;
int main() {
for (cin >> t; t; t--) {
cin >> a >> b >> c >> d;
cout << b << " " << c << " " << c << endl;
}
return 0;
}
|
1337
|
B
|
Kana and Dragon Quest game
|
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
The dragon has a hit point of $x$ initially. When its hit point goes to $0$ or under $0$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.
- Void Absorption Assume that the dragon's current hit point is $h$, after casting this spell its hit point will become $\left\lfloor \frac{h}{2} \right\rfloor + 10$. Here $\left\lfloor \frac{h}{2} \right\rfloor$ denotes $h$ divided by two, rounded down.
- Lightning Strike This spell will decrease the dragon's hit point by $10$. Assume that the dragon's current hit point is $h$, after casting this spell its hit point will be lowered to $h-10$.
Due to some reasons Kana can only cast \textbf{no more than} $n$ Void Absorptions and $m$ Lightning Strikes. She can cast the spells in any order and \textbf{doesn't have to} cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.
|
First, it's better not to cast Void Absorptions after a Lightning Strike. Otherwise, there will be a Void Absorption right after a Lightning Strike. Supposing the hit point was $x$ before casting these two spells, if you cast Lightning Strike first, after these two spells the hit point will be $\left\lfloor \frac{x-10}{2} \right\rfloor +10 = \left\lfloor \frac{x}{2} \right\rfloor + 5$, but if you cast Void Absorption first, after these two spells the hit point will be $\left\lfloor \frac{x}{2} \right\rfloor$, which is smaller. So the solution is to cast Void Absorptions until the dragon's hit point won't decrease with more casts or you can't cast more Void Absorptions, then cast all Lightning Strikes you have. We can also use DP to solve this problem. Let $f_{i,j,k} = 0/1$ be possibility of defeating the dragon when the dragon's hit point is at $i$, you can cast $j$ more Void Absorptions and $k$ more Lightning Strikes. This is a slow solution but is enough to get accepted. You may have to use boolean arrays instead of integer arrays to save memory.
|
[
"greedy",
"implementation",
"math"
] | 900
|
#include <bits/stdc++.h>
int x,n,m,t;
void solve(){
scanf("%d%d%d",&x,&n,&m);
while (x>0&&n&&x/2+10<x){n--;x=x/2+10;}
if (x<=m*10)printf("YES\n");
else printf("NO\n");
}
int main(){
scanf("%d",&t);
while(t--)solve();
return 0;
}
|
1338
|
A
|
Powered Addition
|
You have an array $a$ of length $n$. For every positive integer $x$ you are going to perform the following operation during the $x$-th second:
- Select some distinct indices $i_{1}, i_{2}, \ldots, i_{k}$ which are between $1$ and $n$ inclusive, and add $2^{x-1}$ to each corresponding position of $a$. Formally, $a_{i_{j}} := a_{i_{j}} + 2^{x-1}$ for $j = 1, 2, \ldots, k$. \textbf{Note that you are allowed to not select any indices at all.}
You have to make $a$ nondecreasing as fast as possible. Find the smallest number $T$ such that you can make the array nondecreasing after at most $T$ seconds.
Array $a$ is nondecreasing if and only if $a_{1} \le a_{2} \le \ldots \le a_{n}$.
You have to answer $t$ independent test cases.
|
First, let's define $b$ as ideal destination of $a$, when we used operations. Observation 1. Whatever you select any $b$, there is only one way to make it, because there is no more than single way to make specific amount of addition. That means we just have to select optimal destination of $a$. For example, if you want to make $a_{1}$ from 10 to 21, then you must do $10 \to 11 \to 13 \to 21$. There is no other way to make $10$ to $21$ using given operations. So now we have to minimize $max(b_{1} - a_{1}, b_{2} - a_{2}, \ldots, b_{n} - a_{n})$, as smaller differences leads to use shorter time to make $a$ nondecreasing. Observation 2. $b$ is optimal when $b_{i}$ is the maximum value among $b_{1}, b_{2}, \ldots, b_{i-1}$ and $a_{i}$. Because for each position $i$, we have to make $b_{i} - a_{i}$ as smallest possible. Since $b_{i}$ should be not smaller than previous $b$ values and also $a_{i}$, we derived such formula. So from position $1, 2, \ldots, n$, greedily find a $b_{i}$, and check how many seconds needed to convert $a_{i}$ to $b_{i}$. The answer is maximum needed seconds among all positions. Time complexity is $O(n)$, but you can do $O(n \log n)$ with "std::set" or whatever.
|
[
"greedy",
"math"
] | 1,500
| null |
1338
|
B
|
Edge Weight Assignment
|
You have unweighted tree of $n$ vertices. You have to assign a \textbf{positive} weight to each edge so that the following condition would hold:
- For every two different leaves $v_{1}$ and $v_{2}$ of this tree, bitwise XOR of weights of all edges on the simple path between $v_{1}$ and $v_{2}$ has to be equal to $0$.
Note that you can put \textbf{very large} positive integers (like $10^{(10^{10})}$).
It's guaranteed that such assignment always exists under given constraints. Now let's define $f$ as \textbf{the number of distinct weights} in assignment.
\begin{center}
In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $0$. $f$ value is $2$ here, because there are $2$ distinct edge weights($4$ and $5$).In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $1$ and vertex $6$ ($3, 4, 5, 4$) is not $0$.
\end{center}
What are the minimum and the maximum possible values of $f$ for the given tree? Find and print both.
|
Let's make an easy and good construction which can solve actual problem. Now reroot this tree at any leaf like picture below; Our goal in this construction is, we are trying to make $xor(path(l_{1}, lca(l_{1}, l_{2}))) = xor(path(l_{2}, lca(l_{1}, l_{2}))) = xor(path(root, lca(l_{1}, l_{2})))$ for all two leaves $l_{1}$ and $l_{2}$ to satisfy $xor(path(l_{1}, l_{2})) = 0$. First, let's solve about minimum $f$ value. Observation 1. You can prove that minimum value of $f$ is at most $3$, by following construction; Since we pick any leaf as root, root is not at the top in this picture. Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not. So answer for minimum value is at most $3$. Observation 2. If there is any construction such that $f = 2$, then it is always possible to have construction of $f = 1$. Because if $f = 2$ then there should be even number of edges for each weight, and you can simply change all weights them to single value without violating validity of edge weight assignment. If you want to check validity of $f = 1$ assignment, then you can simply check if all leaves have same parity of distance from root. Because distances between all nodes should be even. Now let's solve about maximum value. Observation 3. You can solve maximum value of $f$ by following construction; So for each non-root vertex $i$, assign weight to edge between $i$ and $p_{i}$ by followings ($p_{i}$ is parent of vertex $i$); If $i$ is not leaf, then assign $2^{i}$ as weight. Otherwise, assign $xor(path(root, p_{i}))$ as weight. This will differentize all edges' weights except for multiple leaves's edges which are connected to single vertex, because every non-leaf vertex have different weights of edge to its parent. So the answer for maximum value is $e - l + m$, where $e$ is number of edges in this tree. $l$ is number of leaves in this tree. $m$ is number of non-leaves which has at least one leaf as its neighbor. Time complexity is $O(n)$. ------ (Update) There is an another way to approach, provided by Darooha. If you label vertices instead of edges where all leaves have same label and none of neighbors have same label, then you can consider edge weight as xor of two vertices' labels, so this is basically equivalent to original problem. Now for minimum, you can see that labelling $0$ to leaves, and $1, 2$ to non-leaves are enough, so you can prove minimum value of $f$ is at most $3$. In same manner, you can try parity checking to check if $f$ value can be $1$ or not. For maximum, assign $0$ to all leaves and assign all different values($2^{1}, 2^{2}, \ldots$) to non-leaf vertices, then you can see all edge weights(except leaves connected to same vertex) are different.
|
[
"bitmasks",
"constructive algorithms",
"dfs and similar",
"greedy",
"math",
"trees"
] | 1,800
| null |
1338
|
C
|
Perfect Triples
|
Consider the infinite sequence $s$ of positive integers, created by repeating the following steps:
- Find the lexicographically smallest triple of positive integers $(a, b, c)$ such that
- $a \oplus b \oplus c = 0$, where $\oplus$ denotes the bitwise XOR operation.
- $a$, $b$, $c$ are not in $s$.
Here triple of integers $(a_1, b_1, c_1)$ is considered to be lexicographically smaller than triple $(a_2, b_2, c_2)$ if sequence $[a_1, b_1, c_1]$ is lexicographically smaller than sequence $[a_2, b_2, c_2]$.
- Append $a$, $b$, $c$ to $s$ in this order.
- Go back to the first step.
You have integer $n$. Find the $n$-th element of $s$.
You have to answer $t$ independent test cases.
A sequence $a$ is lexicographically smaller than a sequence $b$ if in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.
|
Let's try mathematical induction. First, suppose you have fully used numbers only between $1$ and $4^{n} - 1$ inclusive. Now we are going to use all numbers between $4^{n}$ and $4^{n+1} - 1$ inclusive by following methods. Following picture is description of $a$, $b$ and $c$ in bitwise manner; First row means we have already used all numbers until $4^{n} - 1$. Other $3$ rows mean $a$, $b$ and $c$. Keep in mind that $a$, $b$, and $c$ are the lexicographically smallest triple, so $a \oplus b = c$ and $a < b < c$ should be satisfied at the same time. Observation 1. $a_{2n} = 1$, $a_{2n+1} = 0$, $b_{2n} = 0$, $b_{2n+1} = 1$, $c_{2n} = c_{2n+1} = 1$. Otherwise, $a < b < c$ condition won't be satisfied, because top two digits of $a$, $b$, $c$ are either $01$, $10$, and $11$. Then we have more freedom in lower digits, because since the highest $2$ digits are all different, then we can fill lower digits of three numbers independently. Now look at picture below; This table shows you how to fill each $2$ digits of $a$, $b$ and $c$. Observation 2. For each $2$ digits, $a$, $b$ and $c$ should have form like this. Of course, you can use mathematical induction again here; Try to prove this in only $2$ digits at the first, then expand this lemma to $4$ digits, $6$ digits, ..., $2n$ digits. Now you know the pattern of digits of $a$, $b$, and $c$. Apply this pattern for each test case. Time complexity is $O(\log n)$.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"divide and conquer",
"math"
] | 2,200
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.