Join the codeforces group and checkout the contest.
Here, you can see the PDF version of the editorial.
| № | Пользователь | Рейтинг |
|---|---|---|
| 1 | Benq | 3676 |
| 2 | jiangly | 3670 |
| 3 | Kevin114514 | 3657 |
| 4 | maroonrk | 3355 |
| 5 | Um_nik | 3353 |
| 6 | squareOf105 | 3346 |
| 7 | tourist | 3343 |
| 8 | strapple | 3324 |
| 9 | heuristica | 3322 |
| 10 | jiangbowen | 3291 |
| Страны | Города | Организации | Всё → |
| № | Пользователь | Вклад |
|---|---|---|
| 1 | Qingyu | 158 |
| 2 | nik_exists | 150 |
| 2 | maspy | 150 |
| 4 | AmShZ | 143 |
| 5 | Um_nik | 141 |
| 6 | Errichto | 139 |
| 7 | adamant | 137 |
| 8 | BledDest | 133 |
| 8 | maroonrk | 133 |
| 10 | qwexd | 129 |
Join the codeforces group and checkout the contest.
Here, you can see the PDF version of the editorial.
Note 1: This is not the official editorial. I prepared these solutions while testing the problems as a tester before the contest.
Note 2: The video tutorial is for those who prefer learning from videos and want to see implementation tips alongside the problem explanations.
Watch the full video: Video Link
Check out my submissions: A, B, C, D, E, F, G.
Please let me know how you prefer this kind of problem-solving video.
We are excited to announce that the final round of the Rayan Programming Contest will be held onsite in Tehran, from November 25–29, 2025!
All participants ranked 1-1000 in the Rayan Selection Round are invited to complete the registration form by August 25, 2025 August 27, 2025. The final list of invited participants—selected based on rank and geographical diversity—will be announced shortly thereafter.
Beyond the chance to win top-tier prizes worth $40,000 USD, finalists will enjoy a unique opportunity to experience the timeless beauty and rich heritage of ancient Persia, with special highlights from the vibrant city of Tehran.

Hotel accommodation, local transportation, and meals are provided to all finalists. Moreover, a partial travel fund of 200 USD will be provided to all foreign participants (except prize winners).
Furthermore, T-shirts for the top 50 participants of selection round as well as 50 more for randomly chosen participants ranked 51-1000 will be sent to those who complete the registration form. 👕
We look forward to seeing you on-site! 🎉
UPDATE (August 23): The registration summary so far is available here. The final selection process is described in this post.
UPDATE (August 26): Because of codeforces unavailability last night, the registration deadline has been extended to August 27.
UPDATE (August 29): The list of finalists for the Rayan 2025 World Finals has been announced.
Competitive programmers, get ready! The Go for Gold Long Challenge is back, bringing another thrilling opportunity to test your problem-solving skills and climb the leaderboard on Codeforces!
We are excited to present yet another round of engaging and challenging problems for the community. Whether you're a seasoned competitor or just starting out, this contest is designed to offer a balanced mix of difficulty levels to help everyone push their limits.
The format of the Long Challenge is IOI-style, which includes subtasks in problems, so that everyone can try all of them.
Please join the codeforces group and register for the contest.
All problems are prepared and tested by DeadlyCritic, ili, amiraskarieh2003.
You can join our Discord server for any questions.
We invite you to propose problem ideas for the next rounds. We increased our payment rates recently. Give back to the community.
The countdown has begun! Mark your calendars and prepare to GoForGold once again. We can’t wait to see your amazing submissions.
Stay tuned for more updates and happy coding!
Popular opinion: CF ratings are unrelated to your IOI results. CF contests differ significantly from IOI contests.
❌ False!
Unpopular opinion: A contestant's Codeforces rating is more predictive of their final IOI result than their score on Day 1 is of their score on Day 2.
✅ True!
A higher CF rating, with a gap of at least 50, correlates with an 84% chance of achieving a better placement at IOI. The relationship between IOI placement and CF rating is strongly connected. The Pierson Correlation Coefficient for these two factors is -0.813. At the same time, the Pierson Correlation Coefficient between the scores of day 1 and day 2 of IOI is 0.804.
A side note for IOI participants: If you performed poorly on the first day, just think of it as a single bad Codeforces contest—you can always do better next time! You can likely compensate on the second day. Likewise, if you did a great job on Day 1, don't relax too much; the next day is a new challenge. The 0.804 coefficient shows a strong connection, but just as CF rating!
Here are the statistics on CF ratings for each medal:
| Medal | Minimum Rating | Median Rating |
|---|---|---|
| 🥇 | 1991 | 2450 |
| 🥈 | 1693 | 2303 |
| 🥉 | 1318 | 2106 |
Additionally, I've discovered an interesting correlation: participants' ratings one year before IOI also correlate with their final ranks; the Pierson Correlation Coefficient is 0.70.
Based on this insight, I’ve trained a model that can predict your placement at IOI. If you’re curious about your predicted placement for IOI 2026, leave a comment! Note that as time passes, the model can determine your place more accurately. Feel free to comment again in six months to see the updated prediction.
You can check out a similar blog post for IOI 2024 here.
I predicted results for some people in the above blog.
| Predicted Place | Actual Place |
|---|---|
| 49 | 67 |
| 104 | 71 |
| 148 | 156 |
| 80 | 126 |
| 174 | 121 |
| 107 | 274 |
| 254 | 290 |
| 183 | 209 |
| 180 | 194 |
| 59 | 88 |
Update: If you want to make the data more complete, please comment if you know someone from this gist.
Join the codeforces group and checkout the contest.
Here, you can see the PDF version of the editorial.
Hello Codeforces!
Less than a week to IOI 2025! I used accounts from this blog and made the prediction for the IOI 2025 ranking. Ratings are calculated based on the average of the current rating and the maximum rating.
Competitive programmers, get ready! The Go for Gold Long Challenge is back, bringing another thrilling opportunity to test your problem-solving skills and climb the leaderboard on Codeforces!
We are excited to present yet another round of engaging and challenging problems for the community. Whether you're a seasoned competitor or just starting out, this contest is designed to offer a balanced mix of difficulty levels to help everyone push their limits.
Note: We have shifted the format of the Long Challenge from ICPC-style to IOI-style, which includes subtasks in problems, so that everyone can try all of them.
Please join the codeforces group and register for the contest.
All problems are prepared and tested by DeadlyCritic, ili, Hooded_Hood, amiraskarieh2003.
You can join our Discord server for any questions.
We invite you to propose problem ideas for the next rounds. We increased our payment rates recently. Give back to the community.
The countdown has begun! Mark your calendars and prepare to GoForGold once again. We can’t wait to see your amazing submissions.
Stay tuned for more updates and happy coding!
Join the codeforces group and checkout the contest.
Here, you can see the PDF version of the editorial.
Competitive programmers, get ready! The Go for Gold Long Challenge is back with its fifth iteration, bringing another thrilling opportunity to test your problem-solving skills and climb the leaderboard on Codeforces!
We are excited to present yet another round of engaging and challenging problems for the community. Whether you're a seasoned competitor or just starting out, this contest is designed to offer a balanced mix of difficulty levels to help everyone push their limits.
Note: We have shifted the format of the Long Challenge from ICPC-style to IOI-style, which includes subtasks in problems, so that everyone can try all of them.
Please join the codeforces group and register for the contest.
All problems are prepared and tested by DeadlyCritic, ili, and me.
You can join our Discord server for any questions.
We invite you to propose problem ideas for the next rounds. We increased our payment rates recently. Give back to the community.
The countdown has begun! Mark your calendars and prepare to GoForGold once again. We can’t wait to see your amazing submissions.
Stay tuned for more updates and happy coding!
Do you know the monotonic stack? You’ll learn something easier to understand with shorter code!
We’re going to discuss a common fundamental problem that you may face as part of other problems. The Next Smaller Element (NSE) problem.
Problem Statement
Given an array $$$a$$$, for each index $$$i$$$, find $$$next_i$$$, which is the first index to the right of $$$i$$$ that is smaller than $$$a_i$$$.
Example
Let's say $$$a = [5, 8, 2, 6, 7, 9, 1, 2]$$$. The output (zero-based) is $$$next = [2, 2, 6, 6, 6, 6, 7, 7]$$$.

Let’s begin with a simple, non-optimal solution.
for (int i = n - 1; i >= 0; --i) {
next[i] = i + 1;
while (next[i] != n && a[i] <= a[next[i]])
++next[i];
}
The time complexity of the above code is $$$\mathcal{O}(n^2)$$$. What if I reduce it to $$$\mathcal{O}(n)$$$ by changing only one line?
Think before you continue...
for (int i = n - 1; i >= 0; --i) {
next[i] = i + 1;
while (next[i] != n && a[i] <= a[next[i]])
next[i] = next[next[i]];
}
Now, let's compare them side by side:
| Old method (monotonic stack) | NSJ |
|---|---|
|
|
| 6 lines, 112 characters | 5 lines, 94 characters |
For a better understanding, check out the GIF below:

Trying to generate counterexamples? I did a lot at the beginning, too. Let’s prove it.
next values are correctWe know that $$$next_i$$$ is either $$$n$$$ or $$$a_{next_i} \lt a_i$$$. So we need to prove that it really is the first smaller index—i.e., no $$$j$$$ with $$$i \lt j \lt \text{next}_i$$$ has $$$a_j \lt a_i$$$. Let’s define $$$nextChain_i$$$ to be a sequence of indices we see in our while loop to finally find the $$$next_i$$$. Formally, $$$nextChain_{i, 0} = i + 1$$$, $$$nextChain_{i, k} = next_{nextChain_{i, k - 1}}$$$. The sequence continues until $$$a_i \gt a_{nextChain_{i, k}}$$$.
Consider there exists a $$$j$$$ s.t. $$$i \lt j \lt next_i$$$ where $$$a_j \lt a_i$$$. One can simply observe that $$$j$$$ can not be contained in the $$$nextChain$$$, because the algorithm will stop at that. So there exists a $$$k$$$ where $$$nextChain_{i, k - 1} \lt j \lt nextChain_{i, k}$$$. As we know $$$a_j \lt a_i \lt a_{nextChain_{i, k - 1}}$$$, it follows that $$$next_{nextChain_{i, k - 1}} = j$$$. This is a contradiction, so no such $$$j$$$ exists—and our argument is complete.
Lemma
Consider the line next[i] = next[next[i]]. Let k = next[i] (before the update). The pointer next[i] effectively skips over k to point to next[k]. An index k can be skipped over in this manner at most once.
Proof of lemma
Consider two indices $$$i \lt i'$$$ that skip over $$$k$$$ while finding their $$$next$$$. We know $$$a_{i'} \lt a_k$$$ and $$$i' \lt k$$$, so when we were finding $$$next_i$$$, we should reach $$$i'$$$ before we reach $$$k$$$, and then we never meet $$$k$$$. Formally, there is integer $$$l$$$ where $$$nextChain_{i, l} \lt i' \lt nextChain_{i, l + 1}$$$. Given $$$a_{i'} \lt a_k \lt nextChain_{i, l + 1}$$$, $$$next_{nextChain_{i, l}}$$$ is not $$$nextChain_{i, l + 1}$$$ because there is at least an element ($$$a_{i'}$$$) which is smaller than $$$a_{nextChain_{i, l}}$$$ and it's nearer to $$$nextChain_{i, l}$$$ than $$$nextChain_{i, l + 1}$$$. This is a contradiction, and our argument is proven.
Now, with the lemma, we know the number of times next[i] = next[next[i]] happens is $$$\mathcal{O}(n)$$$, so the total time complexity is $$$\mathcal{O}(n)$$$.
Shorter proofs are welcome!
The NSE problem is very popular and fundamental, I think I faced it 50 times over the past 13 years since I started CP. But I never saw anyone know NSJ. I checked dozens of submissions on Codeforces and LeetCode—none used the NSJ trick. I also queried several AI tools to see whether this algorithm had been used or discovered anywhere and found out it is used in this paper to solve another problem. However, it hasn’t become popular enough in the community to replace the monotonic stack. Why do you think that is?
I think the reason is that people try to learn from others instead of discovering things on their own. If you tried finding a solution for the NSE problem, what was the probability that you ended up with monotonic stack? How about NSJ?
This again confirms my teaching method slogan: "Be a fellow traveller, not a travel leader" (see my profile picture, and check out more here).
Problems for practicing:
Update (June 10): I know monotonic stack has other applications. But NSJ seems like a magic that you think gets TLE, but it works, and it's worth learning.
Join the codeforces group and checkout the contest.
Here, you can see the PDF version of the editorial.
Competitive programmers, get ready! The Go for Gold Long Challenge is back with its fourth iteration, bringing another thrilling opportunity to test your problem-solving skills and climb the leaderboard on Codeforces!
We are excited to present yet another round of engaging and challenging problems for the community. Whether you're a seasoned competitor or just starting out, this contest is designed to offer a balanced mix of difficulty levels to help everyone push their limits.
Note: We have shifted the format of the Long Challenge from ICPC-style to IOI-style, which includes subtasks in problems, so that everyone can try all of them.
Please join the codeforces group and register for the contest.
All problems are prepared and tested by DeadlyCritic, ili, and me.
You can join our Discord server for any questions.
We invite you to propose problem ideas for the next rounds. We increased our payment rates recently. Give back to the community.
The countdown has begun! Mark your calendars and prepare to GoForGold once again. We can’t wait to see your amazing submissions.
Stay tuned for more updates and happy coding!
Join the codeforces group and checkout the contest.
Here, you can see the PDF version of the editorial.
Competitive programmers, get ready! The Go for Gold Long Challenge is back with its fourth iteration, bringing another thrilling opportunity to test your problem-solving skills and climb the leaderboard on Codeforces!
We are excited to present yet another round of engaging and challenging problems for the community. Whether you're a seasoned competitor or just starting out, this contest is designed to offer a balanced mix of difficulty levels to help everyone push their limits.
Note: We have shifted the format of the Long Challenge from ICPC-style to IOI-style, which includes subtasks in problems, so that everyone can try all of them.
Please join the codeforces group and register for the contest.
All problems are prepared and tested by DeadlyCritic, ili, Enigma27, ludo., OIaspirant2307 and me.
You can join our Discord server for any questions.
We invite you to propose problem ideas for the next rounds. We increased our payment rates recently. Give back to the community. Thanks to ProofByContradiction_, AksLolCoding, GM_Dan4Life, lovewingbell, Muhammad-Ahmad for suggesting ideas for this contest!
The countdown has begun! Mark your calendars and prepare to GoForGold once again. We can’t wait to see your amazing submissions.
Stay tuned for more updates and happy coding!
UPD: Editorial is published.
Hello, Codeforces Community!
We are excited to announce the GoForGold Long Challenges—an innovative monthly contest series brought to you by Newton School of Technology. Starting on the second last Friday of every month, these challenges will run for 10 days, providing a fantastic platform to learn new things and hone your problem-solving skills.
As the Contest Coordinator, I invite you to share your creative problem ideas with us. This is a unique opportunity where you don't have to prepare a full-fledged problem—simply submit your idea. If your idea is accepted, you'll be rewarded with a cash prize!
Below is the reward structure based on the difficulty and corresponding Codeforces rating:
| Difficulty | CF Difficulty Rating | Idea Reward (USD) |
|---|---|---|
| Cakewalk | 800 — 1200 | $6 |
| Simple | 1200 — 1600 | $8 |
| Easy | 1600 — 1900 | $10 |
| Easy-Med | 1900 — 2200 | $15 |
| Medium | 2200 — 2400 | $35 |
| Med-Hard | 2400 — 2600 | $50 |
Submit your problem ideas using our Submission Form.
Happy problem proposing!
Hope you enjoyed the contest!
Text editorials will be published soon. I've created video editorials for all problems, except for problem M — Alternating Sum).
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 1e3 + 14, B = 60;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
ll x, y;
cin >> x >> y;
if (y > x) {
cout << "-1\n";
continue;
}
bool seen = false;
for (int i = B - 1; i >= 0; --i) {
if ((x >> i & 1) > (y >> i & 1))
seen = true;
if (seen && (x >> i & 1) == 0) {
x ^= (1ll << i + 1);
x |= (1ll << i + 1) - 1;
break;
}
}
if (popcount((unsigned long long) x) == 1)
cout << (1ll << popcount((unsigned long long) x)) - (y == 0) << '\n';
else
cout << (1ll << popcount((unsigned long long) x)) - (y != 0) << '\n';
}
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 1e6 + 1, MAX_P = MAX_N * 2;
int mark[MAX_N], mat[MAX_N][2], is_prime[MAX_P], par[MAX_N];
vector<int> g[MAX_N], cer_prefix[MAX_N], cer_suffix[MAX_N];
bool dfs(int v) {
if (mark[v])
return 0;
mark[v] = 1;
for (auto u : g[v])
if (mat[u][1] == -1 || dfs(mat[u][1]))
return mat[v][0] = u, mat[u][1] = v, 1;
return 0;
}
int maximum_matching(int l, int n) {
fill(mat[l], mat[n + 1], -1);
bool br = 0;
int ans = 0;
while (br ^= 1) {
fill(mark + l, mark + n + 1, false);
for (int i = l; i <= n; i++)
if (mat[i][0] == -1 && dfs(i))
ans++, br = 0;
}
return ans;
}
void print(int n) {
if (n == 0)
return;
if (n == 1) {
cout << "1 ";
return;
}
if (par[n] == -1) {
for (int i = n; i >= 1; i--) {
if (i % 2 == 1) {
for (int j = i + 1; j <= n; j += 2)
if (is_prime[i + j])
g[i].push_back(j);
}
else
for (int j = i + 1; j <= n; j += 2)
if (is_prime[i + j])
g[j].push_back(i);
if (i % 2 != n % 2 && maximum_matching(i, n) == (n - i) / 2 + 1) {
for (int j = i; j <= n; ++j) {
if (j % 2) {
cer_prefix[n].push_back(j);
cer_suffix[n].push_back(mat[j][0]);
}
g[j].clear();
}
ranges::reverse(cer_suffix[n]);
par[n] = i - 1;
break;
}
}
}
for (auto x : cer_prefix[n])
cout << x << ' ';
print(par[n]);
for (auto x : cer_suffix[n])
cout << x << ' ';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
fill_n(is_prime, MAX_P, true);
for (int p = 2; p * p < MAX_P; ++p)
for (int i = p * p; i < MAX_P; i += p)
is_prime[i] = false;
fill_n(par, MAX_N, -1);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
print(n);
cout << '\n';
}
}
My solution is an overkill. Checkout the following code from Seal Breakers.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
bool prime(ll n){
for(int i=2; i*i<=n; i++){
if(n%i==0) return false;
}
return true;
}
void f(ll n){
if(n==1) cout<<1<<" ";
if(n!=0){
ll i=1, a=1;
if(n%2!=0) i=2;
for(; i<=n; i++){
if(prime(n+i)){
a=i;
break;
}
}
for(;i<(n+a-i); i++) cout<<i<<" ";
f(a-1);
for(; i<=n; i++) cout<<i<<" ";
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--){
ll n;
cin>>n;
f(n);
cout<<endl;
}
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
struct ModInt {
int x;
bool operator==(const ModInt& rhs) const {
return x == rhs.x;
}
bool operator!=(const ModInt& rhs) const {
return !(rhs == *this);
}
ModInt(ll x = 0) : x(((x % MOD) + MOD) % MOD) {
}
friend ModInt operator+(const ModInt& l, const ModInt& r) {
return l.x + r.x;
}
ModInt& operator+=(const ModInt& o) {
return *this = *this + o;
}
friend ModInt operator-(const ModInt& l, const ModInt& r) {
return l.x - r.x;
}
ModInt operator-() const {
return -x;
}
ModInt& operator-=(const ModInt& o) {
return *this = *this - o;
}
friend ModInt operator*(const ModInt& l, const ModInt& r) {
return (ll)l.x * r.x;
}
ModInt& operator*=(const ModInt& o) {
return *this = *this * o;
}
ModInt pow(ll b) const {
ModInt ans = 1;
ModInt a = *this;
for (; b; b >>= 1, a = a * a)
if (b & 1)
ans *= a;
return ans;
}
ModInt rev() const {
return pow(MOD - 2);
}
friend ModInt operator/(const ModInt& l, const ModInt& r) {
return l * r.rev();
}
ModInt& operator/=(const ModInt& o) {
return *this = *this / o;
}
friend ostream& operator<<(ostream& os, const ModInt& anInt) {
os << anInt.x;
return os;
}
};
const int MAX_N = 2e2 + 14, D = 10;
int n, k;
ModInt cache[2][D][D][D][D][2 * D], zero, one = 1;
ModInt dp(int n, int last, int max_streak, int streak_l, int streak_r);
ModInt& dp(int n, int last, int l, int r, int max_streak, int streak) {
if (last < 0 || last >= D)
return zero;
if (n == 1)
return streak == 0 && l <= last && last <= r ? one : zero;
return cache[n & 1][last][l][r][max_streak][streak + D];
}
ModInt dp(int n, int last, int l, int r, int max_streak, int streak_l, int streak_r) {
ModInt ans = 0;
for (int s = streak_l; s <= streak_r; ++s)
ans += dp(n, last, l, r, max_streak, s);
return ans;
}
ModInt dp(int n, int last, int l, int r, int max_streak) {
return dp(n, last, l, r, max_streak, -max_streak, max_streak) - (max_streak
? dp(n, last, l, r, max_streak - 1,
-max_streak + 1, max_streak - 1)
: 0);
}
ModInt dp_pure(int n, int last, int l, int r, int max_streak) {
assert(l <= r);
if (l == r)
return dp(n, last, l, r, max_streak);
return dp(n, last, l, r, max_streak) - dp(n, last, l + 1, r, max_streak) - dp(n, last, l, r - 1, max_streak) + dp(
n, last, l + 1, r - 1, max_streak);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> k;
for (int i = 2; i <= n; ++i) {
fill(cache[i & 1][0][0][0][0], cache[(i & 1) + 1][0][0][0][0], ModInt());
for (int l = 0; l < D; ++l)
for (int r = 0; r < D; ++r)
for (int last = i == n ? 0 : l; last <= (i == n ? D - 1 : r); ++last)
for (int max_streak = 0; max_streak < D; ++max_streak)
for (int streak = -max_streak; streak <= max_streak; ++streak) {
ModInt& ans = dp(i, last, l, r, max_streak, streak);
if (streak > 1)
ans = dp(i - 1, last - 1, l, r, max_streak, streak - 1);
else if (streak < -1)
ans = dp(i - 1, last + 1, l, r, max_streak, streak + 1);
else if (streak == 0)
ans = dp(i - 1, last, l, r, max_streak, -max_streak, max_streak);
else if (streak == 1)
ans = dp(i - 1, last - 1, l, r, max_streak, -max_streak, 0);
else if (streak == -1)
ans = dp(i - 1, last + 1, l, r, max_streak, 0, max_streak);
}
}
ModInt ans;
for (int i = 0; i < D; ++i) {
for (int row_streak = -D + 1; row_streak < D; ++row_streak)
for (int col_streak = -D + 1; col_streak < D; ++col_streak)
if ((row_streak + 1) * (col_streak + 1) <= k)
for (int l = 0; l < D; ++l)
for (int r = l; r < D; ++r) {
int cl = max(0, i - l), cr = min(D - 1, D - 1 + i - r);
ans += dp_pure(n, i, l, r, row_streak) * dp(n, i, cl, cr, col_streak);
}
}
cout << ans << '\n';
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 1e5 + 14;
int ask(int i, int j, int k) {
cout << "? " << i + 1 << ' ' << j + 1 << ' ' << k + 1 << endl;
int x;
cin >> x;
return x;
}
int main() {
int t;
cin >> t;
while (t--){
int n;
cin >> n;
int a[4];
a[0] = ask(1, 2, 3);
a[1] = ask(0, 2, 3);
a[2] = ask(0, 1, 3);
a[3] = ask(0, 1, 2);
int p[n];
for (int i = 0; i < 4; ++i)
p[i] = accumulate(a, a + 4, 0) / 3 - a[i];
for (int i = 4; i < n; ++i)
p[i] = ask(0, 1, i) - p[0] - p[1];
cout << "! ";
for (int i = 0; i < n; ++i)
cout << p[i] << " ";
cout << endl;
}
}
t = int(input())
while t > 0:
t -= 1
n = int(input())
s = input()
ans = s[0]
sum = 0
for i in range(1, n):
if s[i] == ans[-1] or (i + 1 < n and s[i] == s[i + 1]):
sum += ans[-1] == s[i]
ans += s[i]
print(sum)
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
int mn = *min_element(a, a + n);
cout << mn * (ll) n + n - count(a, a + n, mn) << endl;
}
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
struct ModInt {
int x;
bool operator==(const ModInt& rhs) const {
return x == rhs.x;
}
bool operator!=(const ModInt& rhs) const {
return !(rhs == *this);
}
ModInt(ll x = 0) : x(((x % MOD) + MOD) % MOD) {
}
friend ModInt operator+(const ModInt& l, const ModInt& r) {
return l.x + r.x;
}
ModInt& operator+=(const ModInt& o) {
return *this = *this + o;
}
friend ModInt operator-(const ModInt& l, const ModInt& r) {
return l.x - r.x;
}
ModInt operator-() const {
return -x;
}
ModInt& operator-=(const ModInt& o) {
return *this = *this - o;
}
friend ModInt operator*(const ModInt& l, const ModInt& r) {
return (ll)l.x * r.x;
}
ModInt& operator*=(const ModInt& o) {
return *this = *this * o;
}
ModInt pow(ll b) const {
ModInt ans = 1;
ModInt a = *this;
for (; b; b >>= 1, a = a * a)
if (b & 1)
ans *= a;
return ans;
}
ModInt rev() const {
return pow(MOD - 2);
}
friend ModInt operator/(const ModInt& l, const ModInt& r) {
return l * r.rev();
}
ModInt& operator/=(const ModInt& o) {
return *this = *this / o;
}
friend ostream& operator<<(ostream& os, const ModInt& anInt) {
os << anInt.x;
return os;
}
};
const int MAX_N = 1e6 + 1;
int phi[MAX_N];
ModInt factor[MAX_N], ans[MAX_N];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
for (int i = 1; i < MAX_N; i++) {
phi[i] += i;
for (int j = i * 2; j < MAX_N; j += i)
phi[j] -= phi[i];
}
fill_n(factor, MAX_N, 1);
int n;
cin >> n;
while (n--) {
int a;
cin >> a;
factor[a] *= (ModInt(a) / phi[a] + 1);
}
ModInt total;
for (int i = MAX_N - 1; i >= 1; i--) {
ans[i] = 1;
for (int j = i; j < MAX_N; j += i)
ans[i] *= factor[j];
for (int j = i * 2; j < MAX_N; j += i)
ans[i] -= ans[j];
ans[i] -= 1;
total += ans[i] / i;
}
cout << total << '\n';
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int B = 20, MAX_N = 1 << B;
const int MOD = 1e9 + 7;
struct ModInt {
int x;
bool operator==(const ModInt& rhs) const {
return x == rhs.x;
}
bool operator!=(const ModInt& rhs) const {
return !(rhs == *this);
}
ModInt(ll x = 0) : x(((x % MOD) + MOD) % MOD) {
}
explicit operator int() const {
return x;
}
friend ModInt operator+(const ModInt& l, const ModInt& r) {
return l.x + r.x;
}
ModInt& operator+=(const ModInt& o) {
return *this = *this + o;
}
friend ModInt operator-(const ModInt& l, const ModInt& r) {
return l.x - r.x;
}
ModInt operator-() const {
return -x;
}
ModInt& operator-=(const ModInt& o) {
return *this = *this - o;
}
friend ModInt operator*(const ModInt& l, const ModInt& r) {
return (ll)l.x * r.x;
}
ModInt& operator*=(const ModInt& o) {
return *this = *this * o;
}
ModInt pow(ll b) const {
ModInt ans = 1;
ModInt a = *this;
for (; b; b >>= 1, a = a * a)
if (b & 1)
ans *= a;
return ans;
}
ModInt rev() const {
return pow(MOD - 2);
}
friend ModInt operator/(const ModInt& l, const ModInt& r) {
return l * r.rev();
}
ModInt& operator/=(const ModInt& o) {
return *this = *this / o;
}
friend ostream& operator<<(ostream& os, const ModInt& anInt) {
os << anInt.x;
return os;
}
};
ModInt fac[MAX_N] = {1}, rfac[MAX_N] = {1};
ModInt c(int n, int r) {
return n < r || r < 0 ? 0 : fac[n] * rfac[r] * rfac[n - r];
}
void prep() {
for (int i = 1; i < MAX_N; ++i)
fac[i] = fac[i - 1] * i;
rfac[MAX_N - 1] = fac[MAX_N - 1].rev();
for (int i = MAX_N - 2; i >= 0; --i)
rfac[i] = (i + 1) * rfac[i + 1];
}
ModInt cnt[MAX_N];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
prep();
int n, k;
cin >> n >> k;
while (n--) {
int a;
cin >> a;
cnt[a] += 1;
}
for (int i = 0; i < B; ++i)
for (int mask = 0; mask < MAX_N; ++mask)
if (mask >> i & 1)
cnt[mask] += cnt[mask ^ (1 << i)];
for (auto& dp : cnt)
dp = c((int) dp, k);
for (int i = 0; i < B; ++i)
for (int mask = 0; mask < MAX_N; ++mask)
if (mask >> i & 1)
cnt[mask] -= cnt[mask ^ (1 << i)];
int q;
cin >> q;
while (q--) {
int x;
cin >> x;
cout << cnt[x] << '\n';
}
}
B = 30
MOD = 10 ** 9 + 7
def count(n, b):
return n // (2 ** (b + 1)) * 2 ** b + max(0, n % (2 ** (b + 1)) - 2 ** b)
t = int(input())
while t > 0:
t -= 1
c, n = map(int, input().split())
if c == 1:
a = [i for i in range(n)]
for i in range(2, n - 1, 4):
a[i], a[i + 1] = a[i + 1], a[i]
if n % 4 == 3:
a = [a[-2]] + a[:-2] + [a[-1]]
print(*a)
else:
ans = 0
for b in range(B):
ones = count(n, b)
zeros = n - ones
cur_ans = (ones // 2) * (ones // 2 + 1)
if ones % 2 == 1:
cur_ans += ones // 2 + 1
cur_ans += (ones + 1) // 2 * zeros
ans += cur_ans * 2 ** b
print(ans % MOD)
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int B = 30;
const int MOD = 1e9 + 7;
long long count(long long n, int b) {
long long cycle = 1LL << (b + 1);
long long full = n / cycle;
long long res = full * (1LL << b);
long long rem = n % cycle;
long long add = max(0LL, rem - (1LL << b));
return res + add;
}
int main() {
int t;
cin >> t;
while (t--) {
int c;
long long n;
cin >> c >> n;
if (c == 1) {
int m = static_cast<int>(n);
vector<int> a(m);
for (int i = 0; i < m; ++i) {
a[i] = i;
}
for (int i = 2; i < m - 1; i += 4) {
swap(a[i], a[i + 1]);
}
if (m % 4 == 3) {
vector<int> new_a;
new_a.push_back(a[m - 2]);
for (int i = 0; i < m - 2; ++i) {
new_a.push_back(a[i]);
}
new_a.push_back(a[m - 1]);
a = new_a;
}
for (size_t i = 0; i < a.size(); ++i) {
if (i != 0) {
cout << ' ';
}
cout << a[i];
}
cout << endl;
} else {
long long ans = 0;
for (int b = 0; b < B; ++b) {
long long ones = count(n, b);
long long zeros = n - ones;
long long half = ones / 2;
long long cur_ans = half * (half + 1) % MOD;
if (ones % 2 == 1) {
cur_ans += half + 1;
}
cur_ans += ((ones + 1) / 2) * zeros % MOD;
ans = (ans + cur_ans * (1LL << b)) % MOD;
}
ans %= MOD;
cout << ans << endl;
}
}
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n], prefix_gcd[n + 1] = {};
for (int i = 0; i < n; ++i) {
cin >> a[i];
prefix_gcd[i + 1] = gcd(prefix_gcd[i], a[i]);
}
int suffix_gcd = 0, ans = 1;
for (int i = n - 1; i >= 0; --i) {
ans = max(ans, gcd(prefix_gcd[i], suffix_gcd));
suffix_gcd = gcd(suffix_gcd, a[i]);
}
cout << ans << '\n';
}
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 1e5 + 14;
vector<int> g[MAX_N];
map<int, ll> cache[MAX_N];
ll solve(int v, int k) {
if (cache[v].count(k))
return cache[v][k];
ll& ans = cache[v][k];
ans = (v + 1) ^ k;
vector<array<ll, 2>> child;
for (auto u : g[v])
if (k % g[v].size())
child.push_back({solve(u, k / g[v].size()), solve(u, k / g[v].size() + 1)});
else
ans += solve(u, k / g[v].size());
if (g[v].empty() || k % g[v].size() == 0)
return ans;
sort(child.begin(), child.end(), [](array<ll, 2> a, array<ll, 2> b) {
return a[1] - a[0] > b[1] - b[0];
});
for (int i = 0; i < child.size(); ++i)
ans += child[i][i < k % child.size()];
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
for (int i = 1; i < n; ++i) {
int p;
cin >> p;
--p;
g[p].push_back(i);
}
cout << solve(0, k) << '\n';
fill(g, g + n, vector<int>());
fill(cache, cache + n, map<int, ll>());
}
}
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 1e5 + 14, LG = 17;
int n, a[MAX_N], st[MAX_N], ft[MAX_N], sp[LG][MAX_N];
vector<int> g[MAX_N], appear[MAX_N];
void dfs(int v = 0, int p = -1) {
static int time = 0;
sp[0][time] = a[v];
appear[a[v]].push_back(time);
st[v] = time++;
for (int u : g[v])
if (u != p)
dfs(u, v);
ft[v] = time;
}
int count(int x, int l, int r) {
return ranges::lower_bound(appear[x], r) - ranges::lower_bound(appear[x], l);
}
int get(int l, int r, int c1, int c2) {
return get<1>(max(tuple{count(c1, l, r), c1}, tuple{count(c2, l, r), c2}));
}
int king(int l, int r) {
int ans = 0;
int p = l;
for (int i = 0; i < LG; ++i)
if (r - p >> i & 1) {
ans = get(l, r, ans, sp[i][p]);
p += 1 << i;
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 0; i < n; ++i)
cin >> a[i];
for (int i = 0; i < n - 1; ++i) {
int v, u;
cin >> v >> u;
--v;
--u;
g[v].push_back(u);
g[u].push_back(v);
}
dfs();
for (int k = 1; k < LG; ++k)
for (int i = 0; i + (1 << k) <= n; ++i)
sp[k][i] = get(i, i + (1 << k), sp[k - 1][i], sp[k - 1][i + (1 << k - 1)]);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
--u;
--v;
int sz = st[v] - st[u] + ft[u] - ft[v];
if (!(st[u] <= st[v] && ft[v] <= ft[u]) || sz % 2) {
cout << "NO\n";
continue;
}
int c1 = king(st[u], st[v]), c2 = king(ft[v], ft[u]);
int max_count = max(count(c1, st[u], st[v]) + count(c1, ft[v], ft[u]),
count(c2, st[u], st[v]) + count(c2, ft[v], ft[u]));
// cerr << max_count << endl;
cout << (max_count * 2 > sz ? "NO\n" : "YES\n");
}
}
The first step is to realize the solution to a well known dp problem for finding f(A) for a given array. We define dp[i][0] to be the maximum sum for element 1..i where I am allowed to pick element i+1 and dp[i][1] be the maximum sum for element 1...i where I may or may not be allowed to pick i+1 th element. defining such states ensures that dp[i][1]>=dp[i][0] the transition will be such dp[i][0]=dp[i-1][1] and dp[i][1]=max(dp[i][0],dp[i-1][0]+a[i]) where dp[n][1] will be the answer for entire array.
in other words dp[i][1] can use all elements 1....i whereas dp[i][0] can oonly use 1...i-1 elements
Defining it to allow dp[i][1]>=dp[i][0] helps us maintain dp[i][1]-dp[i][0] as one of the states of DP of the original problem where only on basis of the difference we get which elements would be picked in future and sum of dp[i][0] will always be taken in sum out of the excess dp[i][1]-dp[i][0] do we take into account the future dp transitions which is gauranteed to be within the range of just 1 additional element ai which is not allowed in dp[i][0] but is allowed to use in dp[i][1] and hence the difference is within the range of ai<=1e4
SO for the original problems the DP states are ans_dp[i][j] representing that among all subsets/subsequences (total 2^i) of the first i numbers ans_dp[i][j] elements have a differencce between their dp[i][1] and dp[i][0] to be j, note that it is not neccessary that the subsequences have the ith element in them it is just upto i among all subsequences including ai as well as not including ai
to transition from i to i+1 for all subsequences which is not taking a_(i+1) we can directly update for them ans_dp[i+1][j]+=ans_dp[i][j] later as they will have the same difference now considering all subsequces having a_(i+1) in them since dp[i+1][1]=max(dp[i][1],dp[i][0]+a_(i+1)) and dp[i+1][0]=dp[i][1] therefore for all differences j in ans_dp[i][j] where j=dp[i][1]-dp[i][0]>=a_(i+1) will be added to difference j=0 for the next state i+1 and for all j<a_(i+1) we will have gap between for the next state dp[i+1][1]-dp[i+1][0] to be dp[i][0]+a_(i+1)-dp[i][1] =a_(i+1)-j and for all these sequences while storing the gap for the next term we can forget the total common in both dp[i][0] and dp[i][1] by the time we have computed for i we have already added all dp[i][0] terms to the final_answer now for every term we are adding a_(i+1) we should add dp[i][1]-dp[i][0]=j to the final_answer to which n-(i+1) elements remain giving 2^(n-(i+1)) subsequences*j will be added for each of them to the final answer and we have transitioned with remaining gaps for the next as well as adding the answers upto dp[i+1][0] for all numbers.
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 1e5 + 14;
vector<int> g[MAX_N];
bool mark[MAX_N];
int par[MAX_N];
void dfs(int v = 0, int p = -1) {
for (auto u : g[v])
if (u != p){
par[u] = v;
dfs(u, v);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int i = 1; i < n; ++i) {
int v, u;
cin >> v >> u;
g[v].push_back(u);
g[u].push_back(v);
}
dfs();
array cer{0, 0};
int ans = 1;
mark[0] = true;
for (int i = 1; i < n; ++i) {
if (mark[i]) {
++ans;
continue;
}
int v = i;
while (!mark[v]) {
mark[v] = true;
v = par[v];
}
auto it = find(cer.begin(), cer.end(), v);
if (it == cer.end())
break;
*it = i;
++ans;
}
cout << ans << ' ';
for (int k = 3; k <= n; ++k)
cout << (k <= g[0].size() + 1) << ' ';
cout << '\n';
fill(g, g + n, vector<int>());
fill(mark, mark + n, false);
}
}
Please let me know how you prefer this kind of problem-solving videos.
Hi Codeforces!
I’ve recorded four videos about Range Minimum Query (RMQ) and related topics. These might be helpful for competitive programmers, especially if you’re diving into data structures or optimization techniques.
Problem statement:
You are given an array $$$a$$$ of size $$$n$$$. You are also given $$$q$$$ queries of type $$$[l, r)$$$ as a range. Each query asks for the minimum element of $$$a$$$ in the given range.
| |
| |
I just returned from the 1st edition of the GoForGold camp in India 🇮🇳, where I had the privilege of teaching some of the brightest Indian students as they prepare for the upcoming ICPC World Finals.
After organizing camps in Syria, Uzbekistan, Azerbaijan, and Croatia, this was yet another incredible experience of helping students push closer to their competitive programming goals.
A highlight of this trip was witnessing the unique approach of Newton School of Technology. They brought teachers right from industry to university to fill the gap — a truly innovative structure that left a lasting impression.
Congratulations to the top three winners in Div. 1:
🥇 404_solution_not_found: P.V.Sekhar, sai-17, nishkarsh
🥈 poocha kya: _helloLad, Atekichan, sv1shan
🥉 SoloTree: Dragokj03, Divine_Spark, evenvalue
Camp was held for 7 days, including a leisure day. Every day participants started their morning with a contest, which I selected for Div 1. I spent four days teaching first-division classes and two days teaching second-division classes. acraider and Dominater069 also covered the remaining two days of the first-division classes. I covered the following topics in lecture sessions: Sack, HLD, FFT, NTT, Network Flow, Treap, Geometry, and Game Theory. Also, I held the post-contest discussions.
On the first day, I told the students "You should die at the end of the camp" and they approved on the last day that they reached the goal I set for them. We grow under pressure, and a camp is the place to train under pressure. Every day having contests, post-contest discussions, and lecture sessions creates a high pressure that leads to incredible growth. I also experienced the same situation in the Moscow camp in 2020.
There are countless people to thank, but I’d especially like to express my gratitude to Deepak Enigma27 Gour for inviting me and the Newton School of Technology for their warm hospitality.
Hey there!
Thank you for being part of the ICPC India Prelims 2024! 🚀
I've put together hints and solutions for the problems to help you reflect on the challenges. As the contest admin, I even recorded myself solving the problems live — it's a mix of strategy, insights, and a behind-the-scenes look at my thought process.
🎥 Watch the video here: https://youtu.be/NsIj7CgDPY8
Let me know what you think, and feel free to share your thoughts or questions! 😊
The problems are ordered from easy to hard.
First, set all numbers to one. Increase if necessary.
t = int(input())
while t > 0:
t -= 1
n, k = map(int, input().split())
triplets = [[] for i in range(n + 1)]
while k > 0:
k -= 1
l, r, m = map(int, input().split())
triplets[m].append((l - 1, r)) # [l, r)
a = [1] * n
for i in range(1, n + 1):
for rng in triplets[i]:
if min(a[rng[0]:rng[1]]) == i:
a[rng[0]:rng[1]] = [i + 1] * (rng[1] - rng[0])
if n + 1 in a:
print(-1)
else:
print(*a)
Don't pick numbers that if you pick them, AND will not become k for sure. Pick everything else.
t = int(input())
while t > 0:
t -= 1
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = []
cur = (1 << 30) - 1
for i in range(n):
if a[i] & k == k:
ans.append(i + 1)
cur &= a[i]
if cur == k:
print('YES', '\n', len(ans), '\n', *ans)
else:
print('NO')
Backtrack and dp both work.
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 3000;
int n, a[MAX_N], b[MAX_N];
map<array<int, 2>, int> cache[MAX_N];
int solve(int i = 0, int mx = INT_MIN, int level = INT_MIN) {
if (i == n)
return 0;
if (cache[i].contains({mx, level}))
return cache[i][{mx, level}];
if (b[i] <= level || a[i] > level)
return cache[i][{mx, level}] = solve(i + 1, max(mx, b[i]), max(level, mx + b[i])) + (b[i] <= level);
return cache[i][{mx, level}] = max(solve(i + 1, max(mx, a[i]), max(level, mx + a[i])) + 1,
solve(i + 1, max(mx, b[i]), max(level, mx + b[i])));
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
cache[i].clear();
}
for (int i = 0; i < n; ++i) {
cin >> b[i];
if (a[i] > b[i])
swap(a[i], b[i]);
}
cout << solve() << '\n';
}
}
Use some primes, and also 6.
MAX_N = 2000000
is_p = [True] * MAX_N
for i in range(2, MAX_N):
if not is_p[i]:
continue
for j in range(i * i, MAX_N, i):
is_p[j] = False
prs = [i for i in range(2, MAX_N) if is_p[i]]
t = int(input())
while t > 0:
t -= 1
n, k = map(int, input().split())
if k > n * (n - 1) / 2:
print(-1)
continue
ptr = len(prs) - 1
while n or k:
if k >= n - 1:
print(prs[ptr], end=' ')
ptr -= 1
k -= n - 1
n -= 1
else:
if ptr > 0:
ptr = 1
print(6, end=' ')
else:
print(2, end=' ')
n -= 1
print()
DSU, but hard!
// In the name of Allah.
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 200000;
int p[MAX_N], val[MAX_N], k[MAX_N], rev[MAX_N];
// if p[i] == -1: a[i] = val[i]
// o.w. a[i] = k[i] + rev[i] * a[p[i]]
int root(int v) {
if (p[v] == -1)
return v;
int r = root(p[v]);
if (r == p[v])
return r;
// a[v] = k[v] + rev[v] * a[p[v]]
// a[p[v]] = k[p[v]] + rev[p[v]] * a[r]
// => a[v] = k[v] + rev[v] * k[p[v]] + rev[v] * rev[p[v]] * a[r]
// a[v] = k'[v] + rev'[v] * a[r]
k[v] += rev[v] * k[p[v]];
rev[v] *= rev[p[v]];
return p[v] = r;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, q;
cin >> n >> q;
fill(p, p + n, -1);
fill(val, val + n, -1);
fill(rev, rev + n, 1);
while (q--) {
int t, i, j, qk;
cin >> t >> i >> j;
--i;
--j;
if (t == 1) {
cin >> qk;
// a[i] + a[j] = qk
int ri = root(i), rj = root(j);
// cerr << ri << ' ' << rj << '\n';
if (ri == rj) {
// cerr << "r: " << rev[i] << ' ' << rev[j] << '\n';
if (val[ri] != -1 || rev[i] != rev[j])
continue;
// a[i] = k[i] + rev[i] * a[ri]
// a[j] = k[j] + rev[j] * a[ri]
// => 2 * rev[i] * a[ri] = qk - k[i] - k[j]
// a[ri] = (qk - k[i] - k[j]) / (2 * rev[i])
// cerr << "found!\n";
val[ri] = (qk - k[i] - k[j]) / (2 * rev[i]);
}
else {
// Make ri parent of rj
// a[i] = k[i] + rev[i] * a[ri]
// a[j] = k[j] + rev[j] * a[rj]
if (val[rj] != -1) {
// k[i] + rev[i] * a[ri] + k[j] + rev[j] * a[rj] = qk
val[ri] = (qk - (k[i] + k[j] + rev[j] * val[rj])) * rev[i];
continue;
}
// a[rj] = k[rj] + rev[rj] * a[ri]
// a[rj] = (qk - (k[i] + rev[i] * a[ri] + k[j])) * rev[j]
// a[rj] = rev[j] * (qk - k[i] - k[j]) - rev[i] * rev[j] * a[ri]
k[rj] = rev[j] * (qk - k[i] - k[j]);
rev[rj] = -rev[i] * rev[j];
p[rj] = ri;
}
}
else {
int ri = root(i), rj = root(j);
if (val[ri] != -1 && val[rj] != -1)
cout << k[i] + rev[i] * val[ri] + k[j] + rev[j] * val[rj] << '\n';
else if (ri == rj && rev[i] != rev[j]) {
// a[i] = k[i] + rev[i] * a[ri]
// a[j] = k[j] + rev[j] * a[ri]
cout << k[i] + k[j] << '\n';
}
else
cout << "-1\n";
}
}
}
Update:
I'm sorry about what happened in the ICPC prelims. The problems passed to me just 10 hours before the contest. As you can see in the video almost all the time I was just engaged with solving them. The time was such tight that I was occupied with just solving the problems to finish them before the contest started. I didn't have any time to test.
I know that the organizers are making a decision that will make everyone happy.
Salam, Codeforces!
On behalf of Sharif University of Technology, we are thrilled to invite you to the Rayan Programming Contest 2024!
The contest will feature three exciting rounds:
We would like to express our gratitude to:
Looking forward to seeing you in the upcoming rounds!
More information can be found at rayan.global.
Best of luck,
Rayan Programming Contest Team
It has been a year since our brothers and sisters in Palestine have been dying and watching their families die. With the war in Lebanon also unfolding, I wondered what I could do.
We, Algoritmi Academy, want to do the least we can to support people there. We sincerely apologize for not acting sooner.
Starting now, we will hold free weekly classes for Palestinian and Lebanese coders. Our priority will be those preparing for IOI and ICPC, but we may accept coders preparing for other goals.
To participate, register on our website and select group classes.
Our activities are not limited to one class per week; we’ll also have a monthly contest. If the number of participants grows, we’ll make two divisions to better maintain the level. For those who may struggle with English, mention it in your registration form; we may hold some classes in Arabic, too.
And finally, we want to send your strong, but injured heart a healing:
«أُذِنَ لِلَّذِينَ يُقَاتَلُونَ بِأَنَّهُمْ ظُلِمُوا وَإِنَّ اللَّهَ عَلَىٰ نَصْرِهِمْ لَقَدِيرٌ»Those who are fought against are permitted to defend themselves because they have been wronged, and God is indeed able to help them
Sincerely to all the resilient and unyielding Palestinian and Lebanese people, The Algoritmi Academy team:
CF ratings are unrelated to your IOI results. CF contests differ significantly from IOI contests.
❌ Wrong!
A higher CF rating, with a gap of at least 100, correlates with an 87% chance of achieving a better placement at IOI. In fact, the relationship between IOI placement and CF rating is strongly connected. The Pierson Correlation Coefficient for these two factors is -0.83.
❗ What is that outlier participant on the top-right? He is Jiyu Shen (Crysfly), with CF rating of 3000+, but it seems that he was unable to attend the contest 💔
Here are the statistics on CF ratings for each medal:
| Medal | Minimum | Median |
|---|---|---|
| 🥇 | 2029 | 2469 |
| 🥈 | 1501 | 2274 |
| 🥉 | 1637 | 2082 |
Additionally, I've discovered an interesting correlation: participants' ratings one year before IOI also correlate with their final ranks. By the way, some participants showed remarkable jumps in their ratings during that one-year period. Specifically, there were 4 participants with 1000+ growth in CF rating!
Based on this insight, I’ve trained a model that can predict your placement at IOI. If you’re curious about your predicted placement for IOI 2025, leave a comment! Note that as time passes, the model can determine your place more accurately. So you may comment again 6 months later to see the updated prediction.
Check out the similar blog for IOI 2019 here.
Hey everyone!
I’ve just returned from an incredible 13-day journey in Croatia, where I had the pleasure of being a part of OCPC 2024 Fall as the editorialist. It was an exhilarating experience to lead editorial sessions after each contest.
Explaining the solution to a problem while one of the participants is checking the distance to the river beach. :broken-heart:
The problem sets were amazing — I truly enjoyed them all. They took me back to my time at the Moscow Camp 2020, evoking the same excitement and challenge of solving numerous problems under time pressure. It was a refreshing and rewarding experience, especially since I don’t compete as frequently these days. After my World Finals in 2021, I semi-retired from competitive programming, shifting my focus to coaching instead: Algoritmi Academy. Now, I only compete a few times a year, so getting to dive deep into this environment again was a real pleasure.
While in Croatia, I also made sure to explore the beautiful landscapes. I rented a car and embarked on a breathtaking drive through the winding roads to Plitvice Lakes, and then onwards to the stunning Croatian coastline. It was a once-in-a-lifetime experience, filled with natural beauty and unforgettable moments.
Congratulations to the first team: Singapore Legged Forces: first place cheated (Wailydest, errorgorn, 244mhq). A huge thank you to OCPC, and of course, a special thanks to adamant and -is-this-fft- for the invitation — it was an honor to be part of this event.
Also read: adamant blog on this.
Watch editorial session for the eighth day contest contest: Link.
Welcome to the second part of our series on using CLion for competitive programming.
After our first blog post, we received helpful feedback that we’ll address here. We aim to keep our videos short and to the point, so we’ll cover more details and respond to comments in the blog.
Our goal is to create high-quality content for competitive programming, and we value your support and feedback in helping us reach this goal.
Once we’ve covered the IDE topics, we’ll move on to more in-depth content on algorithms, strategies, and problem-solving.
We’re not done yet. After we complete this series, you’ll be able to evaluate our claims and find an IDE or editor that meets what we've covered.
While configuring VSCode for an on-site contest can be challenging (and sometimes impossible), CLion is already set up for C++. You might prefer using VSCode for online contests if you’re more comfortable with it, but CLion can be a good choice for on-site contests due to its similarity to VSCode.
| Название |
|---|


