Thanks for participating. I apologize for the unexpectedly hard B. Apart from that, I hope you liked the problems and enjoyed the round!
I would like to thank Proof_by_QED, Forge, and awesomeguy856 for pointing out an elegant $$$\mathcal{O}(n)$$$ solution for problem G.
I would also like to thank temporary1 for helping me write the editorial for problem F and Forge and reirugan for proofreading the editorial.
| Predictor | A | B | C | D | E | F | G |
|---|---|---|---|---|---|---|---|
| wakanda-forever | $$$800$$$ | $$$1000$$$ | $$$1000$$$ | $$$1200$$$ | $$$1500$$$ | $$$1800$$$ | $$$2100$$$ |
| expertaq | $$$800$$$ | $$$1000$$$ | $$$1100$$$ | $$$1200$$$ | $$$1600$$$ | $$$1700$$$ | $$$2000$$$ |
| reirugan | $$$800$$$ | $$$900$$$ | $$$1000$$$ | $$$1200$$$ | $$$1500$$$ | $$$1700$$$ | $$$1900$$$ |
| yse | $$$800$$$ | $$$800$$$ | $$$800$$$ | $$$1100$$$ | $$$1500$$$ | $$$1700$$$ | $$$1900$$$ |
| Argentum47 | $$$800$$$ | $$$900$$$ | $$$1000$$$ | $$$1200$$$ | $$$1700$$$ | $$$1700$$$ | $$$2100$$$ |
| simplelife | $$$800$$$ | $$$800$$$ | $$$900$$$ | $$$1100$$$ | $$$1500$$$ | $$$1900$$$ | $$$2200$$$ |
| omsincoconut | $$$800$$$ | $$$1200$$$ | $$$1100$$$ | $$$1300$$$ | $$$1800$$$ | $$$1900$$$ | $$$2300$$$ |
| kevinxiehk | $$$800$$$ | $$$1000$$$ | $$$1000$$$ | $$$1200$$$ | $$$1700$$$ | $$$1900$$$ | $$$2200$$$ |
| Edeeva | $$$800$$$ | $$$1000$$$ | $$$1000$$$ | $$$1300$$$ | $$$1600$$$ | $$$1800$$$ | $$$2200$$$ |
| Forge | $$$800$$$ | $$$1000$$$ | $$$1100$$$ | $$$1400$$$ | $$$1700$$$ | $$$1900$$$ | $$$2100$$$ |
| _istil | $$$800$$$ | $$$900$$$ | $$$1100$$$ | $$$1200$$$ | $$$1600$$$ | $$$1800$$$ | $$$2100$$$ |
| Jrke | $$$800$$$ | $$$900$$$ | $$$1100$$$ | $$$1400$$$ | $$$1700$$$ | $$$1800$$$ | $$$2100$$$ |
| temporary1 | $$$800$$$ | $$$900$$$ | $$$1000$$$ | $$$1400$$$ | $$$1600$$$ | $$$1800$$$ | $$$2000$$$ |
| skellyboi05 | $$$800$$$ | $$$900$$$ | $$$1000$$$ | $$$1300$$$ | $$$1600$$$ | $$$1700$$$ | ----- |
| nik_exists | $$$800$$$ | $$$1000$$$ | $$$900$$$ | $$$1200$$$ | $$$1600$$$ | $$$1700$$$ | ----- |
| Proof_by_QED | $$$800$$$ | $$$900$$$ | $$$900$$$ | $$$1100$$$ | $$$1700$$$ | $$$1500$$$ | $$$1900$$$ |
| Lilypad | $$$800$$$ | $$$900$$$ | $$$1200$$$ | $$$1200$$$ | $$$1700$$$ | $$$1900$$$ | $$$2100$$$ |
2241A - Divide and Conquer
The operation allows us to choose a divisor $$$z$$$ of $$$x$$$ and update $$$x := \frac{x}{z}$$$.
Since $$$z$$$ is a divisor of $$$x$$$, the resulting value $$$\frac{x}{z}$$$ is strictly an integer and is also a divisor of $$$x$$$. Because we can freely choose any valid $$$z$$$, a single operation effectively allows us to replace $$$x$$$ with any of its divisors.
Applying this operation multiple times does not yield any additional numbers, because a divisor of a divisor is still just a divisor of the original $$$x$$$. Therefore, the set of all possible numbers reachable from $$$x$$$ is strictly limited to its divisors.
Therefore, to solve the problem:
- If $$$y$$$ is a divisor of $$$x$$$ (i.e., $$$x \bmod y = 0$$$), we output
YES. We can reach $$$y$$$ in at most $$$1$$$ operation by choosing $$$z = \frac{x}{y}$$$. - If $$$y$$$ is not a divisor of $$$x$$$, we output
NO, as it is impossible to reach.
Time Complexity: $$$\mathcal{O}(1)$$$.
#include<bits/stdc++.h>
using namespace std;
int main(){
int tt;
cin >> tt;
while(tt--){
int x, y;
cin >> x >> y;
cout << (x % y == 0 ? "YES" : "NO") << '\n';
}
return 0;
}
2241B - Good times Good times
Let $$$d$$$ be the number of digits of $$$x$$$, and choose $$$y = 10^d + 1$$$. The number $$$y$$$ contains only the digits $$$0$$$ and $$$1$$$, so $$$y$$$ is good. Also,
Since $$$x \lt 10^d$$$, multiplying by $$$10^d$$$ simply shifts $$$x$$$ by $$$d$$$ positions. Therefore, $$$x \cdot y$$$ is exactly the decimal concatenation of $$$x$$$ with itself. Hence, the set of digits appearing in $$$x \cdot y$$$ is the same as in $$$x$$$. Since $$$x$$$ is good, $$$x \cdot y$$$ is good as well.
Thus, for every test case, one of the possible answers is simply
The construction always satisfies $$$2 \le y \le 10^9$$$.
Time Complexity: $$$\mathcal{O}(\log_{10}(x))$$$.
#include<bits/stdc++.h>
using namespace std;
int main(){
int tt;
cin >> tt;
while(tt--){
int x;
cin >> x;
int y = 1;
while(x > 0){
y *= 10;
x /= 10;
}
cout << y + 1 << '\n';
}
return 0;
}
2241C - RemovevomeR
Let $$$c$$$ be the number of positions $$$i$$$ such that $$$s_i \ne s_{i+1}$$$.
If $$$c=0$$$, all characters are equal. The whole string is always a palindrome, so we can repeatedly delete characters until only one remains.
If $$$c=1$$$, the string consists of exactly two contiguous blocks of equal characters. Any palindrome of length at least $$$2$$$ must be contained entirely inside one of these blocks, so every operation only shortens a block and can never remove it completely. Therefore, both blocks remain nonempty, and the minimum possible length is $$$2$$$.
If $$$c\ge 2$$$, then the string has at least three blocks. First, we can shrink every block to length $$$1$$$, because any block of equal characters is itself a palindrome of length at least $$$2$$$ as long as its length is at least $$$2$$$. So we may assume the string becomes alternating.
Now consider an alternating string of length at least $$$3$$$. Its last three characters are always of the form $$$010$$$ or $$$101$$$; hence, they form a palindrome. Deleting the last character of this palindrome shortens the string by $$$1$$$, and the remaining string is still alternating. Repeating this step, we can reduce the string to length $$$3$$$. Then the whole string is a palindrome, and deleting its middle character gives two equal characters, which can be reduced to length $$$1$$$ in one more move.
Hence, the answer is $$$2$$$ iff $$$c=1$$$, and $$$1$$$ otherwise.
Time Complexity: $$$\mathcal{O}(n)$$$.
#include<bits/stdc++.h>
using namespace std;
int main(){
int tt;
cin >> tt;
while(tt--){
int n;
string s;
cin >> n >> s;
int count = 0;
for(int i = 0; i < n - 1; i++) if(s[i] != s[i + 1]) count++;
cout << (count == 1 ? 2 : 1) << '\n';
}
return 0;
}
2241D - An Alternative Way
Let
The key is to look at prefix sums. One operation on segment $$$[l,r]$$$ adds the pattern $$$+1,-1,+1,-1,\dots$$$ starting from the left end. Therefore, the prefix sum of the modified array changes by $$$1$$$ on some prefixes and by $$$0$$$ on the others, so no prefix sum can ever decrease.
Now take the special segment $$$[i,i+1]$$$. It adds $$$+1$$$ to $$$a_i$$$ and $$$-1$$$ to $$$a_{i+1}$$$, so only the $$$i$$$-th prefix sum increases by $$$1$$$, while all other prefix sums stay unchanged. Also, $$$[n,n]$$$ increases only the $$$n$$$-th prefix sum by $$$1$$$.
So every prefix sum can be increased independently and never decreased. Hence, the transformation is possible iff
Time Complexity: $$$\mathcal{O}(n)$$$.
An alternative way to solve the problem is to first understand which operations are actually useful.
Consider an operation on a subarray of length greater than $$$2$$$. Its effect is exactly the sum of the operations on consecutive subarrays of length $$$2$$$ inside it (partitioning the subarray into consecutive pairs; if its length is odd, the last element is treated as a subarray of length $$$1$$$). Therefore, every operation on a longer subarray can be decomposed into operations on length-$$$2$$$ subarrays, so it is sufficient to consider only these.
Now there are only two useful operations:
- applying the operation on $$$[i,i]$$$, which increases $$$a_i$$$ by $$$1$$$;
- applying the operation on $$$[i-1,i]$$$, which decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_{i-1}$$$ by $$$1$$$.
We process the array from right to left. Suppose we are currently at position $$$i$$$.
- If $$$a_i \lt b_i$$$, we simply apply the first operation $$$b_i-a_i$$$ times, increasing only $$$a_i$$$ until it becomes $$$b_i$$$.
- If $$$a_i \gt b_i$$$, we apply the second operation $$$a_i-b_i$$$ times. Each application decreases $$$a_i$$$ by $$$1$$$ while increasing $$$a_{i-1}$$$ by $$$1$$$, so after these operations we have $$$a_i=b_i$$$. Any excess is pushed one position to the left.
Notice that after finishing position $$$i$$$, no later operation can change it again. Hence, every position except the first can always be fixed independently. After processing all positions from $$$n$$$ down to $$$2$$$, the only remaining value is $$$a_1$$$. Since every operation can only increase $$$a_1$$$, the transformation is possible if and only if
Thus, the algorithm is simply to process the array backwards as described above and finally check whether $$$a_1\le b_1$$$.
Time Complexity: $$$\mathcal{O}(n)$$$.
#include<bits/stdc++.h>
using namespace std;
int main(){
int tt;
cin >> tt;
while(tt--){
int n;
cin >> n;
vector<long long> a(n), b(n);
for(int i = 0; i < n; i++) cin >> a[i];
for(int i = 0; i < n; i++) cin >> b[i];
for(int i = 1; i < n; i++) a[i] += a[i - 1];
for(int i = 1; i < n; i++) b[i] += b[i - 1];
bool is = 1;
for(int i = 0; i < n; i++) if(a[i] > b[i]) is = 0;
if(is) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}
2241E - Fair and Square
For any two vertices $$$x$$$ and $$$y$$$, let us denote $$$P(x, y)$$$ as the simple path from $$$x$$$ to $$$y$$$.
Now, let us fix an unordered triplet of vertices $$${u,v,w}$$$. We claim that there is exactly one vertex (say $$$c$$$) that belongs to all three paths $$$P(u,v)$$$, $$$P(v,w)$$$, and $$$P(w,u)$$$, and every other vertex is counted $$$0$$$ or $$$2$$$ times.
If one of the three vertices, say $$$w$$$, lies on the path $$$P(u,v)$$$, then clearly $$$w$$$ belongs to all three paths, because the path from $$$u$$$ to $$$w$$$ and the path from $$$v$$$ to $$$w$$$ both pass through $$$w$$$.
Otherwise, $$$w$$$ does not lie on $$$P(u,v)$$$. Start from $$$w$$$ and walk towards the path $$$P(u,v)$$$. Since the graph is a tree, there is a unique first vertex $$$c$$$ where we meet $$$P(u,v)$$$. Every path from $$$w$$$ to any vertex of $$$P(u,v)$$$ must pass through $$$c$$$, so in particular both $$$P(w,u)$$$ and $$$P(w,v)$$$ pass through $$$c$$$. Also, $$$c \in P(u,v)$$$ by definition, so $$$c$$$ lies on all three paths.
Now take any vertex $$$x$$$ that lies on all three paths. Since $$$x \in P(u,v)$$$ and $$$x \in P(w,u)$$$, the path from $$$w$$$ to $$$x$$$ must enter $$$P(u,v)$$$ at $$$x$$$. But the first entry point from $$$w$$$ into $$$P(u,v)$$$ is exactly $$$c$$$; hence $$$x=c$$$. So the common vertex is unique.
Now take any other vertex $$$x\ne c$$$. Remove $$$x$$$ from the tree. Then the tree splits into components.
If $$$u,v,w$$$ all lie in the same component, then no pairwise path uses $$$x$$$, so $$$x$$$ is counted $$$0$$$ times. If they lie in exactly two components, then exactly two of the three pairs are separated by $$$x$$$, so $$$x$$$ is counted $$$2$$$ times. If they lie in three components, then $$$x$$$ would lie on all three pairwise paths, which would make $$$x$$$ the unique common vertex, contradicting $$$x\ne c$$$.
Therefore, for the product
every vertex contributes an even exponent except $$$c$$$, whose exponent is $$$3$$$. Hence, the product is a perfect square iff $$$a_c$$$ is a perfect square.
So now we only need to count, for every vertex $$$x$$$ with $$$a_x$$$ a perfect square, how many triplets have $$$x$$$ as the unique common vertex. Remove $$$x$$$, and let the component sizes be $$$s_1,s_2,\dots,s_k$$$.
A valid triplet is of two types:
- $$$x$$$ is one of the chosen vertices. Then the other two vertices must come from two different components, so the count is
- $$$x$$$ is not chosen. Then the three chosen vertices must come from three different components, so the count is
Both values can be computed in one scan over the components:
and for each component size $$$s$$$:
Then the contribution of $$$x$$$ is $$$\text{pairs}+\text{triples}$$$.
To get the component sizes for every $$$x$$$, root the tree once and store subtree sizes. For a vertex $$$x$$$, its components after deletion are all child subtrees of $$$x$$$, plus the parent-side component of size $$$n-\mathrm{sz}[x]$$$ if it exists.
So the solution is:
- root the tree and compute subtree sizes;
- for every vertex $$$x$$$, build the sizes of components of $$$T-x$$$;
- if $$$a_x$$$ is a perfect square, add $$$\text{pairs}+\text{triples}$$$ to the answer.
Time Complexity: $$$\mathcal{O}(n)$$$.
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
int tt = 1;
cin >> tt;
while(tt--){
ll n;
cin >> n;
vector<ll> a(n);
for(ll i = 0; i < n; i++) cin >> a[i];
vector<vector<ll>> v(n);
for(ll i = 1; i < n; i++){
ll x, y;
cin >> x >> y;
x--;
y--;
v[x].push_back(y);
v[y].push_back(x);
}
ll ans = 0;
vector<ll> ss(n, 1);
function<void(ll, ll)> dfs = [&](ll u, ll par){
vector<ll> val;
for(auto& z : v[u]) if(z != par){
dfs(z, u);
val.push_back(ss[z]);
ss[u] += ss[z];
}
val.push_back(n - ss[u]);
assert(accumulate(val.begin(), val.end(), 0ll) == n - 1);
if((ll)sqrtl(a[u]) * (ll)sqrtl(a[u]) < a[u]) return;
ll sum = 0;
ll pairs = 0;
ll triplets = 0;
for(auto& z : val){
triplets += pairs * z;
pairs += sum * z;
sum += z;
}
ans += pairs;
ans += triplets;
};
dfs(0, -1);
cout << ans << '\n';
}
return 0;
}
2241F - A Bit Odd
One common way to solve these kinds of games is to first identify the losing states and then generalize their structure.
Let's first consider the states where the current player has no valid moves. An obvious example is a binary string consisting entirely of 0s or entirely of 1s. Since a player may delete any subsequence with an odd number of inversions, there is a lot of freedom in choosing a move. So instead of analyzing every possible move, let us ask a simpler question: When can Alice win immediately by deleting all 0s or all 1s?
Suppose Alice wants to delete all 1s. Then the chosen subsequence must have an odd number of inversions. This is possible iff it contains at least one 0 that is preceded by an odd number of 1s in the original string. Similarly, if Alice wants to delete all 0s, then the chosen subsequence must contain at least one 1 that is followed by an odd number of 0s. Both conditions can be checked in $$$\mathcal{O}(n)$$$ using prefix (or suffix) parity.
Now let us consider the strings that satisfy neither of these conditions. Such strings must have the form
where each $$$X_i$$$ is either 00 or 11. The leading 0 and trailing 1 are optional. Since these endpoint characters can never affect any inversion parity, we may simply ignore them. We claim that every string of this form is a losing state.
Suppose Alice deletes a subsequence $$$S_1$$$, leaving the subsequence $$$S_2$$$.
Consider any block $$$X_i$$$.
- If both characters of $$$X_i$$$ end up in the same subsequence, then $$$X_i$$$ contributes an even number of inversions to that subsequence, so it does not affect the parity.
- Otherwise, the two characters are split between $$$S_1$$$ and $$$S_2$$$. In this case, each subsequence receives exactly one copy of the same character, so the contribution of this block to the inversion parity is identical in both subsequences.
Therefore, after ignoring every block whose two characters stay together, the remaining parts of $$$S_1$$$ and $$$S_2$$$ are identical. Hence
Since Alice's move is valid, $$$\operatorname{inv}(S_1)$$$ is odd. Therefore, $$$\operatorname{inv}(S_2)$$$ is also odd, so Bob can simply delete the entire remaining string on his turn and win immediately.
Hence, every string of the above form is a losing state.
Therefore, Alice wins iff the initial string does not have the above form. Checking this structure is straightforward.
Time Complexity: $$$\mathcal{O}(n)$$$.
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tt = 1;
cin >> tt;
while(tt--){
ll n;
cin >> n;
string s;
cin >> s;
bool is = 1;
int left = 0, right = n - 1;
while(left < n && s[left] == '0') left++;
while(right >= 0 && s[right] == '1') right--;
if(left > right){
cout << "Bob\n";
continue;
}
int count = 1;
for(int i = left; i < right; i++){
if(s[i + 1] == s[i]) count++;
else{
if(count % 2 == 1) is = 0;
count = 1;
}
}
if(count % 2 == 1) is = 0;
cout << (is ? "Bob\n" : "Alice\n");
}
return 0;
}
2241G - Summmon
Let us look at what one operation really means.
Suppose we are working with a subarray $$$[l,r]$$$, and let $$$x=a_l$$$. The first element is special because it never changes: every operation only uses earlier values to modify later positions, so the leftmost value stays fixed forever.
Now the only thing that matters is how much freedom we have for the next elements. This is where $$$\text{gcd}$$$ enters naturally. If the current prefix has $$$\text{gcd}$$$ equal to $$$g$$$, then we claim that the next element can be changed by any multiple of $$$g$$$.
Let the array be $$$b$$$, and we are focusing on a prefix $$$b_1, b_2, \dots, b_{k-1}$$$ to modify the next element $$$b_k$$$.
The allowed operation is strictly adjacent: $$$b_{j+1} := b_{j+1} \pm b_j$$$. At first glance, it seems we can only directly add $$$b_{k-1}$$$ to $$$b_k$$$. How do we add an earlier element, like $$$b_1$$$, directly to $$$b_k$$$ without permanently destroying the intermediate elements?
We can "pass" values through intermediate elements. Let's look at adding $$$b_1$$$ to $$$b_3$$$ without permanently changing $$$b_2$$$:
- Add $$$b_1$$$ to $$$b_2 \implies b_2$$$ becomes $$$b_2 + b_1$$$
- Add $$$b_2$$$ to $$$b_3 \implies b_3$$$ becomes $$$b_3 + b_2 + b_1$$$
- Subtract $$$b_1$$$ from $$$b_2 \implies b_2$$$ is restored to its original value $$$b_2$$$
- Subtract $$$b_2$$$ from $$$b_3 \implies b_3$$$ becomes $$$(b_3 + b_2 + b_1) - b_2 = b_3 + b_1$$$
Through this sequence, $$$b_2$$$ is perfectly restored to its original state, but $$$b_3$$$ has cleanly absorbed exactly one $$$+b_1$$$.
By chaining this trick across any distance, we can propagate any prefix element $$$b_i$$$ to $$$b_k$$$. We can repeat these sequences to add or subtract $$$b_i$$$ as many times as we want. Because these operations can be done independently for each element in the prefix, the total change we can apply to $$$b_k$$$ is precisely the set of all integer linear combinations:
where $$$c_i \in \mathbb{Z}$$$.
Let $$$C$$$ be the set of all integer linear combinations of the prefix elements $$$b_1, \dots, b_{k-1}$$$, and let $$$g = \gcd(b_1, \dots, b_{k-1})$$$. Let $$$M$$$ be the set of all integer multiples of $$$g$$$. We need to prove that $$$C = M$$$ by showing they are subsets of each other.
1. Every linear combination is a multiple of $$$g$$$ ($$$C \subseteq M$$$)
By the definition of the greatest common divisor, $$$g$$$ divides every element $$$b_i$$$. Thus, there exist integers $$$q_i$$$ such that $$$b_i = q_i g$$$. Take any arbitrary linear combination $$$x \in C$$$:
Substitute $$$b_i = q_i g$$$ into the equation:
Since the product and sum of integers $$$c_i$$$ and $$$q_i$$$ form an integer, $$$x$$$ is an exact integer multiple of $$$g$$$. Therefore, $$$C \subseteq M$$$.
2. Every multiple of $$$g$$$ is a reachable linear combination ($$$M \subseteq C$$$)
By Bézout's Identity, there exist integers $$$u_i$$$ such that their linear combination exactly equals the greatest common divisor:
Take any arbitrary multiple $$$y \in M$$$, meaning $$$y = m g$$$ for some integer $$$m$$$. Substitute $$$g$$$ using Bézout's Identity:
Since $$$m$$$ and $$$u_i$$$ are integers, their product $$$(m u_i)$$$ is also an integer. This proves $$$y$$$ is a valid linear combination of the prefix elements. Therefore, $$$M \subseteq C$$$.
Since $$$C \subseteq M$$$ and $$$M \subseteq C$$$, it strictly follows that $$$C = M$$$. The set of all reachable changes is exactly the set of all multiples of the prefix's $$$\gcd$$$.
Now let us focus on subarrays starting at index $$$l$$$.
As long as every element to the right of $$$a_l$$$ is divisible by $$$a_l$$$, the $$$\text{gcd}$$$ of the processed prefix remains exactly $$$a_l$$$ — because all seen values are multiples of $$$a_l$$$, and $$$a_l$$$ itself is present. So every such element can be moved by multiples of $$$a_l$$$, which means each of them can be made equal to $$$a_l$$$. Therefore, if the subarray never contains an element not divisible by $$$a_l$$$, then the whole subarray can be made constant, and the value of $$$f$$$ is $$$0$$$.
Now define $$$\text{next[l]}$$$ as the first position $$$t \gt l$$$ such that $$$a_t$$$ is not divisible by $$$a_l$$$. If no such position exists, set $$$\text{next[l]=n+1}$$$.
If such a position exists, we write
Since $$$t$$$ is the first such position, the $$$\text{gcd}$$$ of everything before it is still $$$a_l$$$, so the value at position $$$t$$$ can only move inside its residue class modulo $$$a_l$$$. Hence, the closest it can get to $$$a_l$$$ is
So the spread of the subarray can never go below $$$d$$$.
The key observation is that the first non-divisible element already fixes the answer. The lower bound $$$d$$$ obtained from this element is tight, and no later element can increase it. Therefore, once this position appears, every longer subarray starting at $$$l$$$ has the same answer $$$d$$$.
Look at the position $$$t + 1$$$. The prefix $$$\text{gcd}$$$ at this position will be $$$g = \text{gcd}(a_l, a_t)$$$. Since $$$g$$$ divides both $$$a_l$$$ and $$$a_t$$$, it also divides $$$a_t \bmod a_l$$$ and $$$a_l - a_t \bmod a_l$$$. Therefore, $$$g \mid d$$$.
From this point onward, every later element can be modified using multiples of a $$$\text{gcd}$$$, which is at most $$$g$$$. Therefore, every later element can be adjusted in steps whose size divides $$$d$$$.
Now, fix the value at position $$$t$$$ so that its distance from $$$a_l$$$ is exactly $$$d$$$. Since every future modification is performed using multiples of divisors of $$$d$$$, every later element can be moved into the interval of length $$$d$$$ determined by these two values. Consequently, no later position can force the spread to become larger than $$$d$$$.
Therefore, the first non-divisible element completely determines the answer: once position $$$t$$$ appears, every longer subarray contributes the same value $$$d$$$ to the final answer.
Hence, for a fixed $$$l$$$:
- for every $$$r \lt \text{next}[l]$$$, we have $$$f([a_l,\dots,a_r])=0$$$;
- for every $$$r\ge \text{next}[l]$$$, we have
So, once $$$\text{next[l]}$$$ is found, all longer subarrays starting at $$$l$$$ contribute the same value. That makes counting easy. The number of subarrays starting at $$$l$$$ that contain this position is $$$n-t+1$$$. So the contribution from index $$$l$$$ is
Now we only need to find $$$\text{next[l]}$$$ for every $$$l$$$. This can be done with a monotonic stack while scanning from left to right. The stack stores indices whose first non-divisible element has not been found yet. In detail, when we are at position $$$i$$$, if
then we have $$$i = \text{next[top]}$$$. Why? Because if any earlier position had already broken divisibility for that index, it would already have been removed from the stack. So we can finalize its contribution immediately and pop it. This way, each index is pushed once and popped once, so the whole procedure is linear.
Time Complexity: $$$\mathcal{O}(n)$$$.
Note that one can also find $$$\text{next[l]}$$$ for every index $$$l$$$ by performing binary search using a sparse table to store $$$\text{gcd}$$$, leading to an $$$\mathcal{O}(n \cdot \log n \cdot \log a)$$$ solution. These implementations are also intended to pass.
#include<bits/stdc++.h>
using namespace std;
#define ll long long
typedef __int128 int128;
std::ostream& operator<<(std::ostream& os, int128 t) {
if (t == 0) return os << "0";
if (t < 0) {
os << "-";
t = -t;
}
int a[50], i = 0;
while (t > 0) {
a[i++] = t % 10;
t /= 10;
}
for (int j = i - 1; j >= 0; j--) {
os << (char)(a[j] + '0');
}
return os;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tt = 1;
cin >> tt;
while(tt--){
ll n;
cin >> n;
vector<ll> a(n);
for(auto& z : a) cin >> z;
int128 ans = 0;
stack<ll> s;
for(int i = 0; i < n; i++){
while(!s.empty() && a[i] % a[s.top()] > 0){
ans += (int128)1 * (n - i) * min(a[i] % a[s.top()], a[s.top()] - a[i] % a[s.top()]);
s.pop();
}
s.push(i);
}
cout << ans << '\n';
}
return 0;
}








very bad at game problems what to do?
practice
Give my man a hug , he needs it.
it takes a lot of guts to go through with a solution like this , so kudos there.
Respect for doing that still
WHAT IS THIS MONSTROSITY OF SOLUTION
What monstrosity is that bro
explain
I do not dare to ask what each state is.
did it pass?
what each state is?
"eVeRytHiNg iS dP bRo", final boss.
dp final boss
You are insane at DP
Play games
Thanks for this beautiful round and amazing problems :)
Problem E is very elegant
can u Please explain me problem E
Sure man.
Consider the example graph pictured in the problem statement, with triplet $$$\{2, 5, 8\}$$$.
Let's start doing the math to check its goodness:
$$$p(2,5) = 2 * 6 * 4 * 5$$$
$$$p(5,8) = 5 * 4 * 3 * 8$$$
$$$p(2,8) = 2 * 6 * 4 * 3 * 8$$$
Thus,
$$$p(2,5) * p(5,8) * p(2,8) = 2 * 6 * 4 * 5 * 5 * 4 * 3 * 8 * 2 * 6 * 4 * 3 * 8$$$
Okay, this is all trivial substitution. The point is that since the whole calculation is just one big product, we can move factors around. Grouping repeating nodes together, we get this:
$$$p(2,5) * p(5,8) * p(2,8) = 2^2 * 6^2 * 5^2 * 3^2 * 8^2 * 4^3$$$
Curiously, every node is squared, except for the middle node, which happens to be the only node that each of the three paths traverses. In fact, it can be proven (the proof is in the beginning of the editorial) that for any triplet, the product will include every node twice, except for some middle node, which will be included thrice.
Therefore, since the product of paths will be equal to $$$a^2b^2{\ldots}c^2 * m^3$$$, then the whole product is a perfect square if and only if $$$m^3$$$ is a perfect square.
A number is a perfect square if and only if all of its prime factors have even exponents. Cubing $$$m$$$ multiplies all prime factor exponents by 3, which preserves their parities. Therefore, $$$m^3$$$ is a perfect square if and only if every prime factor exponent in $$$m$$$ is even, and in that case, $$$m$$$ is a perfect square.
Therefore, to count the number of good triplets, all we have to do is count the number of ways we can have a middle node that is a perfect square!
To check whether a node is a perfect square, we can precompute every perfect square up to the maximum node value, since $$$10^6$$$ is easily small enough for a lookup table:
It is established that if we fix a perfect square as the middle node (that is, the single node that is traveled through thrice), then any triplet formed under this constraint will be good, regardless of any other details of the triplet's shape or the values of any of the other nodes.
There are two ways to fix a middle node.
Case 1: the middle node is included in the triplet
Imagine that we root the tree at our middle node, and each child of this root forms a subtree. Then all we have to do is count the number of ways to complete the triplet such that the two other nodes come from different subtrees. This is because if the two nodes came from the same subtree, then they wouldn't have to travel through the middle node at all.
Each node in one subtree can be paired with any node in another subtree, so for each node we count the number of nodes in other subtrees, or more efficiently, for each subtree, we count the size of that subtree times the sum of the sizes of the other subtrees.
That is, if there are $$$s$$$ subtrees, and $$$size[i]$$$ is the size of subtree $$$i$$$ for $$$0 \lt = i \lt s$$$, then a node in subtree $$$i$$$ can pair with $$$(\sum_{j=0}^{s - 1} size[j]) - size[i]$$$ other nodes, so subtree $$$i$$$ contributes this to the number of case 1 triplets:
$$$size[i] * ((\sum_{j=0}^{s - 1} size[j]) - size[i])$$$
And $$$\sum_{j=0}^{s - 1} size[j]$$$ happens to include every node except the root, so it is equal to the total tree size minus $$$1$$$:
$$$size[i] * (treesize - 1 - size[i])$$$
But wait! If we compute this number, we will count duplicate triplets, as we will count both $$$\{a,m,b\}$$$ and $$$\{b,m,a\}$$$. Luckily for us, we can get the number of unique case 1 triplets by just dividing the total number of pairs by $$$2$$$.
Finally we are closing in on the answer, right? Not so fast! This calculation assumes that we have rooted the tree at a perfect square, but what if every node was a perfect square? Then we would have to reroot the tree at $$$n$$$ nodes, with each reroot costing $$$O(n)$$$ operations. In total, this would be an $$$O(n^2)$$$ solution, which is toast for $$$n = 2 * 10^5$$$.
In fact, we don't need to reroot the tree. Let the nodes form one tree, rooted at any node, that I will call the "original" tree to avoid confusion. Recall that $$$size[i]$$$ is the size of child $$$i$$$'s subtree in an imaginary rerooted graph. We can calculate the size of every subtree in the original tree with DFS. Now, for any fixed middle node $$$m$$$, we know $$$size[i]$$$ for each one of its original children, and we are only missing $$$size[i]$$$ for $$$m$$$'s original parent. As it turns out, the missing $$$size[i]$$$ is equal to the total original tree size minus the size of $$$m$$$'s original subtree.
Now we can calculate the total number of good triplets for case 1:
Case 2: the middle node is not included in the triplet
In this case, each node in the triplet must be in a different subtree (I am back to talking about subtrees in the imaginary rerooted graph). If every node were in the same subtree, then no paths would include the middle node at all. If two nodes were in the same subtree, then their path would stay inside that subtree, so the current node would not be traversed by all three paths (and therefore would not be a middle node). So we need to count the number of ways to choose three nodes in different subtrees.
Each node can join a pair of two nodes in other subtrees, and we can count the number of such pairs similarly to how we counted pairs in case 1. If there are $$$doubles$$$ total pairs of nodes in separate subtrees, and, as we found before, there are $$$size[i] * (treesize - 1 - size[i])$$$ pairs of nodes that include subtree $$$i$$$, then there are simply $$$doubles - size[i] * (treesize - 1 - size[i])$$$ pairs that don't include subtree $$$i$$$, and that is what each node contributes to the case 2 count.
But wait again! We are again counting duplicates, and this time we will count once for each possible choice of starting node (we aren't counting $$$\{x,y,z\}$$$ and $$$\{x,z,y\}$$$ separately, however, since we have already divided $$$doubles$$$ by $$$2$$$, so, assuming we fix the first node in the triplet, we will accurately count the number of ways to fill in the last two regardless of order). So we need to divide our total case 2 count by $$$3$$$.
Let's tie everything together. First, we precompute perfect squares in $$$O(a_{\max})$$$, and precompute the size of each original subtree with DFS in $$$O(n)$$$. Then, we DFS through every node again in $$$O(n)$$$, checking to see if it is a perfect square. If it is, we count the number of case 1 triplets and the number of case 2 triplets, which amortizes to $$$O(n)$$$ similarly to DFS traversal, producing a total time complexity of $$$O(a_{\max} + n)$$$.
Here is my accepted submission, which resembles the snippets in this explanation but has different variable names: 380968282.
Thank u for your clear explanation! It helps me a lot:D
Problem B was even harder than problem D. Finding the idea that you have to multiply x by 10...01 was crazy difficult. Great contest!
I accidentally found this while brute-forcing all possible values of y that could be valid. Then I realized there was a pattern. Lol.
so true bro
Same here. Brute-forces opened my eyes. B took more time than F, haha.
Yes you could have only got that if you knew the idea already. here is my solution where i used recursion to so that i was able to skip the numbers that had more than 2 numbers in it.
My submission
not the best/shortest code that i could have written, lot of unnecessary lines but it does the job
funFact: the name of the problem has a hint to the answer... the name hints x*y...
Imagine the solution to the question was right there in the problem's name. Oh God, why am I still alive? :(
for me i solved B in 10 minutes but had to read the editorial for problem D
Hello guys,
I've solved many standard DSA problems, but I'm struggling with problems that require identifying patterns.
Even when I solve a Codeforces problem, my solution usually looks much messier compared to other people's solutions. I'd really appreciate some guidance.
Do you guys have any set of problems or resources that can help me improve my pattern recognition? I'm ready to work super hard, but I don't have proper guidance or know which resources to follow.
Any advice would be greatly appreciated. Thank you!
brother , solve 800-1100 rated problems and it will boost your obsv
thank you for your advice broo
TLE eliminator cp-31
thank you sir.
One of the greatest contest I have ever seen.
Hats off to the writer .
Great efforts...
Not me getting absolutely demolished by B today, man I suck at these type of problems so bad, I found C and D easier than B. Though the contest had pretty good questions in my opinion.
nice pfp you got there
A<C<D<B I thought time limit per test meant time limit for each small test in a pretest/test so i spent a whole hour trying to bruteforce B lol, goodbye pupil
F < E
In G theoretical maximum is 2e5*(2e5-1)/2*1e9, it's okay for ull, but bad for ll. I have test for that, and hacks now are incorrect.
A little bit correction: The maximum answer for each range is $$$5 * 10^{8}$$$, so theoretical maximum answer for this problem here is actually $$$10^{19}$$$ instead of $$$2 * 10^{19}$$$. Still we would need an unsigned 64-bit integer.
Thanks for this beautiful round and problems ! It was very fun
Agree. Thank authors for problems. Especially liked E.
It was so interesting and brainstorming
Chronology.
1) Solved A.
2) Read B, tried around 8-10 minutes, couldn't find any pattern. Wrote two for-loops and isGood(x) to brute the solution. Skipped cos couldn't find pattern from Brute.
3) Read C, solved.
4) Went back to B, read again. Couldn't find pattern again. (Spent around 2 minutes ).
5) Read D, solved it.
6) Went back to B AGAIN. still couldn't find pattern. ( spent more than 5 minutes, because I thought "so many people solved B, so it must be simple!!"). Again wasted those 5 minutes.
7) Read E ,solved it.
8) Again went back to B, (This time, again spent 5-7 minutes, and still coudn't solve it ).
9) Read F, solved it with two attempts.
10) Tried B AGAIN. Couldn't solve it AGAIN.
11) Read G, and realised so less accepted solutions for G. So moved back to B.
12) Finally wrote full fledge brute() for B. and found pattern when printed all possible good numbers for 'x' where (100 <= x <= 1000). ( Found common number 1001. found pattern ).
Honestly, If we know B, its easy. But if we don't , bruting our way through pattern is difficult :( .
B was the real final boss of the contest.
What do you mean, only took me 5 minutes to get B. But yes, I'm learning from your strat of printing the answers via brute force. But stood absolutely no chance against E or F.
LOL, i just figured it out in like 3 minutes :D ($$$1 \leq x \lt 10^8$$$ not $$$\le 10^8$$$ saved me when it was queuing)
Can you share the code and how you found pattern for problem B using bruteforce?
I also tried printing using bruteforce but can't find any pattern using it.
My code:
Print for 100 to 999 and u will see, common number.
idk why but problem B seemed to be the easiest for me even tho i only managed to solve A , i read problem D and immediatly skipped it when i saw the graph , but good contest so far(it may be my best) .
Any tips for improvement ?
Problem G solution is wrong, Answer exceeds the long long range.380842381
Me overcomplicating 2241B - Good times Good times while 10^digits + 1 was patiently waiting in the corner
Got A-D in 40 mins and basically finished the contest. I negged on D three times because I'm a noob, I wrote a[0] = b[0], but in reality all cases where a[0] <= b[0] worked. Finally hitting pupil! Yay!!!
B is honestly easier if you do math contests. If you do math contests, you would know about the multiply by 101 and 1001 tricks, which would make it easier.
I could not get it in the starting. But when i write x twice and divided this number by x again then I see the pattern. Like for x = 73. My y is 7373 / 73.
Problem G remember to use
unsigned long longbecause there's a hack that can construct a answer to $$$9955440513000000000$$$(LLONG_MAX$$$9223372036854775807$$$ is lower than this).it's crazy how in the implementation of the solution the author used long long not unsigned long long.
I guess that the author didn't expect it so I guess it is reasonably to say that they should have added a constraint that the answer do not exceeds LLONG_MAX as if not maybe almost all accepted solution will be hacked.
for F Alice can win as long as there's a single element that causes odd inversions (odd 1's in front of 0 or odd 0's after 1)
Yep. This is obviously for overall even inversions.
The proof that (for every array with even prefix counts of 1s and 0s) also follows that both parities will be same. Since Alice has to choose odd, Bob gets the game-ending odd move
please spoiler!
Thanks for this elegant contest
My n^(3/2) solution to E:
...
Best block decomposition user!
If you are Chinese,you may have done a lot of problems from Ynoi
this is NOT block decomposition bro :sob:
Oh sorry I didn't see your code.
b was harder than c and d .
Great contest. Couldn't figure out a trick for counting subtrees' sizes for the problem E, so switched to F and managed to solve it at the very last moment. The funny thing about E is it's sort of a regex problem.
I'm glad so many newbies paid tribute to me by putting
wfat the end of their variables ❤Truly heartwarming ❤
我还以为b题是dfs,打表才发现是找规律
No Chinese use English
why?Is there any rules that I don't kown?My English is poor.
No, but I suggest you do so.
.
x < 1e8 and not <= 1e8 in B saved me big time
Attempting a contest after long time, guys help me debug my solution for D, any help is appreciated. https://codeliveshare.com/ide/hXAw317iGb
why rating is not getting updated
My post contest discussion stream here and hints here
I thought that in B x <= 1e8 (including 1e8), so I added a condition that checks if x == 1e8 then y = 2 (or any number that only has one unique digit). Afterwards found out that wasn't necessary
cool E, learned new things. thanks a lot :)
The first contest that I have practiced after I came back form CP. It's tooooooooooo difficult for me.
same here
The contest was reeeally fun but I'm kinda concerned about CodeForces not being able to catch the cheaters..
Like, many of the top 20 people were newbies until now (consistently having 8K+ ranks and not being able to cross the 1200 mark) but somehow they were able to solve all the problems soooo quickly? T^T
Ain't it kinda sus?
B looks very easy, but it was the scariest one
After sitting with the B for a solid 30 minutes, I realised the 10^d + 1 pattern. Wrote the code. Got WA on test case 2. Turns out, though my logic was correct, I made a mistake in counting the number of digits. Facepalm
Anyway, decided to input the x as string. And used the x.size() to count the digits
380764045
Very nice problem none the less
Quickest rating update in a Div. 3! I actually clutched up!
Why are you scamming gamblers like me, who had bet that you wouldn't be Expert before July 1st?
umm is this polymarket?
Manifold Markets
Technically it's NO if you actually read the "Timing" section
wrusb bet all on No btw.
I was randomly solving this problem today and noticed it felt very similar to Problem B from this contest. It turns out they have the same author... 🦁
In B i tried to make preprossesing for all nums from 2 to 1e4
check is they good and push them to vector then i use this vector and loop on it to find a good y that give me good x*y
OMG such a nice round. too bad i missed the contest because i went to play badminton instead smh.. gotta keep an eye on the timings.
Bruh, I literally thought of the solution for problem B, but I disregarded that as soon as it came to my mind thinking that y is 10^9 max, and 10^d will exceed that.
Man I should have given it more thought.
Oh why I didn't think of this solution for question B?
very nice contest.
how can i practice to solve these problems?i just did problem A
was it intentional in g to make the answer out of bound of the long long range
I've only managed to solve one problem. How can I improve?
If anyone needs a translation of http://e-maxx.ru/upload/e-maxx_algo.pdf from Russian into English, here you go https://cuty.io/emaxxalgoen.
why does number of G solvers decreases?...
Not sure, but I guess either cheaters being removed, or people getting hacked because the result does not fit in 64 bits.
Can anyone Explain E in more Detail
You might find my commented solution useful: 381184874
If that doesn't clear things up, at least mention which part you don't understand.
Thanks Brooo! Super Broo
thanks this was really clean
for any (u,v,w) there exist only 1 vertex x such x in all 3 simple path's (u,v),(u,w),(v,w). basically you can proof that p(u,v)*p(u,w)*p(v,w)=n²*x where n natural. So (u,v,w) good if x = k². So for every such an x, you need to calc amount of that triples. That's 0 if x has one son, y1*y2 if x has 2 sons, (s(y)²-s(y²))/2+(s(y)³-3s(y²)s(y)+2s(y³))/6 if x has >=3 sons, where y is arr of number of descendants of the sons, s(yⁿ) = sum(yiⁿ) for every i.
can anyone explain me approach of second problem?