Long
Long
2.7
2023-12-31
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
gray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
brute force . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1: Erase First or Second Letter . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2: Easy As ABC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3: Don’t Try to Count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4: Grandma Capa Knits a Scarf . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5: Two Vessels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6: Download More RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7: Cirno’s Perfect Bitmasks Classroom . . . . . . . . . . . . . . . . . . . . . . 37
8: Pizza Separation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
9: Beautiful Divisors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
10: Fancy Coins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
11: ACM ICPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12: Local Extrema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
13: Another Permutation Problem . . . . . . . . . . . . . . . . . . . . . . . . 43
14: Fibonaccharsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
15: Desorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
16: Longest Divisors Interval . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
17: Balanced Round . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
18: Rudolph and Tic-Tac-Toe . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
19: Trust Nobody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
20: Gold Rush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
constructive algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
21: Binary Imbalance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22: Sorting with Twos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
23: Chips on the Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
24: MEXanized Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
25: Make It Zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
26: XOR Palindromes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
1
Coding with Jiangly 2023-12-31
Back to top 2
Coding with Jiangly 2023-12-31
Back to top 3
Coding with Jiangly 2023-12-31
Back to top 4
Coding with Jiangly 2023-12-31
Back to top 5
Coding with Jiangly 2023-12-31
Back to top 6
Coding with Jiangly 2023-12-31
Back to top 7
Coding with Jiangly 2023-12-31
Back to top 8
Coding with Jiangly 2023-12-31
Back to top 9
Coding with Jiangly 2023-12-31
Back to top 10
Coding with Jiangly 2023-12-31
Back to top 11
Coding with Jiangly 2023-12-31
Back to top 12
Coding with Jiangly 2023-12-31
Back to top 13
Coding with Jiangly 2023-12-31
Back to top 14
Coding with Jiangly 2023-12-31
Back to top 15
Coding with Jiangly 2023-12-31
Back to top 16
Coding with Jiangly 2023-12-31
Back to top 17
Coding with Jiangly 2023-12-31
Back to top 18
Coding with Jiangly 2023-12-31
misc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864
641: Salyg1n and Array (hard version) . . . . . . . . . . . . . . . . . . . . . . . 864
642: Playoff Fixing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865
643: Sausage Maximization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868
644: Cannon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 870
645: Hercule Poirot Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871
646: Nearest vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 873
647: New Game with a Chess Piece . . . . . . . . . . . . . . . . . . . . . . . . 878
648: Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879
649: Berland collider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 881
650: Deletion of Repeats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 886
651: Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
652: Vittorio Plays with LEGO Bricks . . . . . . . . . . . . . . . . . . . . . . . 890
653: Chemistry Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
654: Intersection and Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . 893
rose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
brute force . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
655: Vova Escapes the Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
656: Removing Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897
657: Balancing Weapons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
658: Survival of the Weakest (easy version) . . . . . . . . . . . . . . . . . . . . 901
659: Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 902
660: Serval and Music Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905
661: Magician and Pigs (Easy Version) . . . . . . . . . . . . . . . . . . . . . . . 906
662: Rebrending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
663: Project Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910
664: Josuke and Complete Graph . . . . . . . . . . . . . . . . . . . . . . . . . 912
665: Function Sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
666: Hossam and a Letter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915
667: Balance (Hard version) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
constructive algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918
668: Interactive Game with Coloring . . . . . . . . . . . . . . . . . . . . . . . 918
669: Great Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
670: In Search of Truth (Hard Version) . . . . . . . . . . . . . . . . . . . . . . . 922
671: Aztec Catacombs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 923
672: Two Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
673: The Fox and the Complete Tree Traversal . . . . . . . . . . . . . . . . . . 928
674: Square Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
Back to top 19
Coding with Jiangly 2023-12-31
Back to top 20
Coding with Jiangly 2023-12-31
Back to top 21
Coding with Jiangly 2023-12-31
Back to top 22
Coding with Jiangly 2023-12-31
Back to top 23
Coding with Jiangly 2023-12-31
Back to top 24
Coding with Jiangly 2023-12-31
Back to top 25
Coding with Jiangly 2023-12-31
Back to top 26
Coding with Jiangly 2023-12-31
Back to top 27
Coding with Jiangly 2023-12-31
misc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1549
962: Indefinite Clownfish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1549
963: Minimums or Medians . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1552
964: Olympic Team Building . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1554
965: Doremy’s Perfect DS Class (Hard Version) . . . . . . . . . . . . . . . . . . 1556
966: Minecraft Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1559
967: Joking (Hard Version) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1562
trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1564
968: Roads in E City . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1564
Appendix: some common template code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1567
MInt and MLong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1567
Comb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1569
DSU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1570
Fenwick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1571
HLD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1572
LazySegmentTree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1574
Problems are written by Codeforces writers. Codeforces platform is run by MikeMirzayanov. Submis-
sions are by jiangly, and the book is collated by 2.7.
Introduction
There are many good players at codeforces. Like many people, I read their submissions for inspirations
and practice helps. Among them, jiangly stands out for having one of the most readable code.
Benq and Um_nik use a large template, and tourist also fall in that category. Jiangly, however, only
copies templates when needed, and generally writes clean code. Personally, I find it much easier to
learn from shorter, more-readable submissions. I first had the idea for this project in Jan21, when
jiangly just became an LGM, and it is great to see jiangly climb to be one of the best players. While I
don’t know about the history of the jiangly fan club, perhaps that is why so many of us are there.
I took the first 50 pages of jiangly’s submissions, combined them with tags / other information, and put
them together as a large problem set. I suspect it is unnecessary to try all the problems at a level when
trying to improve, given the sheer quantity of problems here.
The difficulty ranges are divided into the following, roughly matching the rank colors. Not including
3000+ because of a coding bug.
1. Sub-1200 (Gray)
2. 1250-1600 (Green)
Back to top 28
Coding with Jiangly 2023-12-31
3. 1650-1900 (Blue)
4. 1950-2100 (Violet)
5. 2150-2300 (Orange)
6. 2350-2600 (Rose)
7. 2650-3000 (Red)
For each range, I sorted the tags by frequency, and selected the tags with the most frequent appearences.
I chose these until the tags account for at least 70% of all tags by frequency. For each I currently included
the link to the problem and a link to jiangly’s solution. At the end of each section I also included an
assortment of 20 problems, randomly selected from the remaining ones.
What might make this a good selection of problems? I think there are two common approaches to
practicing problems, namely solving contests & solving handout problems. Both have their pros and
cons.
1. Solving contests gets you an accurate sample of problems you will see in contexts, but does not
give you the right level. A 2k-rated player will encounter both 3k-rated and 800-rated problems
in a typical contest, and neither is very educational.
2. Handout problems can be tuned to be the right level. However, they often focus on interesting,
but infrequent topics. You will find many exotic data structures browsing through Codeforces.
The less flashy techniques (e.g. Greedy and DP), however, make up the majority of the problems.
I hope the selected problems can get the best of both worlds. The chapters are divided by difficulty, so
that one can find problems that are at the right level. The sections of a chapter are selected using the
most common tags found on Codeforces, so they should be teaching the most important techniques.
Of course, I didn’t include every problem of a given tag, since solving 10-12 of each is already plenty of
work.
Why do these here, instead of from the problemset page? I think solving from the problemset
page is a great approach as well, but this might still be an improvement. 1. It is easier to schedule
practice with a book. One can say “solve problems 430-440 from the blue book” and you will easily
know where to find them. 2. Each of these problems contain a good selected solution. The solution
here is answering “how would a black-level player solve this under time pressure?”, and are perhaps
more practical than the curated solutions. They will not be perfect, but they should be good. 3. It saves
you the hassle of finding problems.
What is up with the struct’s? There are some code that are frequently repeated, such as that for
modular arithmetic. Including them tends to make the code look less neat, so I took them out. The
common ones are found in the appendix.
What does this book not have? Of course, given I compiled this using a program, there are a few
limitations. 1. Explanation of the concepts. You can look around Codeforces, wikipedia, or ask an AI to
Back to top 29
Coding with Jiangly 2023-12-31
explain it. 2. Quality control. If a problem is way too easy / brutal for its difficulty, or has nothing to do
with the tag, feel free to comment it.
Finally, an observation: if you can solve all the problems in this book without looking at hints,
in (30 min for hard ones, 5min for easy ones), your tournament performances should be almost
indistinguishable from his. There are some notable differences, of course: 1. You know that some
black-level player, namely jiangly, was able to solve this problem. Jiangly may not have known that. 2.
You know the tags that the problem received.
Back to top 30
Coding with Jiangly 2023-12-31
gray
brute force
You are given a string s of length n. Let’s define two operations you can apply on the string:
Your task is to find the number of distinct non-empty strings that can be generated by applying the
given operations on the initial string any number of times (possibly zero), in any order.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 array<int, 26> cnt{};
10 int dist = 0;
11 int ans = 0;
12 for (auto c : s) {
13 dist += cnt[c - 'a']++ == 0;
14 ans += dist;
15 }
16 cout << ans << "\n";
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
Back to top 31
Coding with Jiangly 2023-12-31
2: Easy As ABC
You are playing a word puzzle. The puzzle starts with a 3 by 3 grid, where each cell contains either the
letter A, B, or C.
The goal of this puzzle is to find the lexicographically smallest possible word of length 3. The word
can be formed by choosing three different cells where the cell containing the first letter is adjacent to
the cell containing the second letter, and the cell containing the second letter is adjacent to the cell
containing the third letter.
Two cells are adjacent to each other if they share a border or a corner, as shown in the following
illustration. Formally, if (r, c) denotes the cell in the r-th row and c-th column, then cell (r, c) is
adjacent to cell (r, c + 1), (r − 1, c + 1), (r − 1, c), (r − 1, c − 1), (r, c − 1), (r + 1, c − 1), (r + 1, c),
and (r + 1, c + 1).
Determine the lexicographically smallest possible word of length 3 that you can find within the grid.
A string s of length n is lexicographically smaller than string t of the same length if there exists an
integer 1 ≤ i ≤ n such that sj = tj for all 1 ≤ j < i, and si < ti in alphabetical order. The following
illustration shows some examples on some grids and their the lexicographically smallest possible word
of length 3 that you can find within the grids.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 array<string, 3> s;
8 for (int i = 0; i < 3; i++) {
9 cin >> s[i];
10 }
11 array<array<int, 3>, 3> vis{};
12 string t;
13 string ans = "CCC";
14 auto dfs = [&](auto self, int i, int x, int y) -> void {
15 if (vis[x][y]) {
16 return;
17 }
18 t += s[x][y];
19 vis[x][y] = 1;
20 if (i == 2) {
Back to top 32
Coding with Jiangly 2023-12-31
Given a string x of length n and a string s of length m (n · m ≤ 25), consisting of lowercase Latin letters,
you can apply any number of operations to the string x.
In one operation, you append the current value of x to the end of the string x. Note that the value of x
will change after this.
For example, if x =“aba”, then after applying operations, x will change as follows: “aba” → “abaaba”
→ “abaabaabaaba”.
After what minimum number of operations s will appear in x as a substring? A substring of a string is
defined as a contiguous segment of it.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
Back to top 33
Coding with Jiangly 2023-12-31
7 string x, s;
8 cin >> x >> s;
9 int ans = 0;
10 while (x.find(s) == -1 && (ans == 0 || x.size() < 2 * m)) {
11 x = x + x;
12 ans++;
13 }
14 if (x.find(s) == -1) {
15 cout << -1 << "\n";
16 } else {
17 cout << ans << "\n";
18 }
19 }
20 int main() {
21 ios::sync_with_stdio(false);
22 cin.tie(nullptr);
23 int t;
24 cin >> t;
25 while (t--) {
26 solve();
27 }
28 return 0;
29 }
Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is
a string consisting of lowercase English letters. Grandpa Sher wrote a string s of length n.
Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from
a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid
offending him, she will choose one lowercase English letter and erase some (at her choice, possibly
none or all) occurrences of that letter in string s.
She also wants to minimize the number of erased symbols from the pattern. Please help her and find
the minimum number of symbols she can erase to make string s a palindrome, or tell her that it’s
impossible. Notice that she can only erase symbols equal to the one letter she chose.
A string is a palindrome if it is the same from the left to the right and from the right to the left. For
example, the strings ‘kek’, ‘abacaba’, ‘r’ and ‘papicipap’ are palindromes, while the strings ‘abb’ and ‘iq’
are not.
Problem: link
Tutorial: link
Back to top 34
Coding with Jiangly 2023-12-31
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 int ans = n + 1;
10 for (char x = 'a'; x <= 'z'; x++) {
11 int l = 0, r = n - 1;
12 int res = 0;
13 while (l < r) {
14 if (s[l] == s[r]) {
15 l++, r--;
16 } else if (s[l] == x) {
17 l++, res++;
18 } else if (s[r] == x) {
19 r--, res++;
20 } else {
21 res = n + 1;
22 break;
23 }
24 }
25 ans = min(ans, res);
26 }
27 if (ans == n + 1) {
28 ans = -1;
29 }
30 cout << ans << "\n";
31 }
32 int main() {
33 ios::sync_with_stdio(false);
34 cin.tie(nullptr);
35 int t;
36 cin >> t;
37 while (t--) {
38 solve();
39 }
40 return 0;
41 }
5: Two Vessels
You have two vessels with water. The first vessel contains a grams of water, and the second vessel
contains b grams of water. Both vessels are very large and can hold any amount of water.
You also have an empty cup that can hold up to c grams of water.
Back to top 35
Coding with Jiangly 2023-12-31
In one move, you can scoop up to c grams of water from any vessel and pour it into the other vessel.
Note that the mass of water poured in one move does not have to be an integer.
What is the minimum number of moves required to make the masses of water in the vessels equal?
Note that you cannot perform any actions other than the described moves.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 int d = abs(a - b);
8 int ans = (d + 2 * c - 1) / (2 * c);
9 cout << ans << "\n";
10 }
11 int main() {
12 ios::sync_with_stdio(false);
13 cin.tie(nullptr);
14 int t;
15 cin >> t;
16 while (t--) {
17 solve();
18 }
19 return 0;
20 }
Did you know you can download more RAM? There is a shop with n different pieces of software that
increase your RAM. The i-th RAM increasing software takes ai GB of memory to run (temporarily,
once the program is done running, you get the RAM back), and gives you an additional bi GB of RAM
(permanently). Each software can only be used once. Your PC currently has k GB of RAM.
Note that you can’t use a RAM-increasing software if it takes more GB of RAM to use than what you
currently have.
Since RAM is the most important thing in the world, you wonder, what is the maximum possible amount
of RAM achievable?
Back to top 36
Coding with Jiangly 2023-12-31
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n), b(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 0; i < n; i++) {
12 cin >> b[i];
13 }
14 vector<int> p(n);
15 iota(p.begin(), p.end(), 0);
16 sort(p.begin(), p.end(),
17 [&](int i, int j) {
18 return a[i] < a[j];
19 });
20 for (auto i : p) {
21 if (a[i] <= k) {
22 k += b[i];
23 }
24 }
25 cout << k << "\n";
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
Cirno gave her students a positive integer x. As an assignment, her students need to find the minimum
positive integer y, which satisfies the following two conditions:
x and y > 0
Back to top 37
Coding with Jiangly 2023-12-31
x xor y > 0
Where and is the bitwise AND operation, and xor is the bitwise XOR operation.
Among the students was Mystia, who was truly baffled by all these new operators. Please help her!
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int x;
6 cin >> x;
7 if (x & (x - 1)) {
8 cout << (x & -x) << "\n";
9 } else if (x == 1) {
10 cout << 3 << "\n";
11 } else {
12 cout << x + 1 << "\n";
13 }
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
8: Pizza Separation
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks
they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered
already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide
all pieces of pizza into two continuous sectors in such way that the difference between angles of these
sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors
can be empty.
Problem: link
Tutorial: link
Back to top 38
Coding with Jiangly 2023-12-31
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 vector<int> a(n);
10 for (int i = 0; i < n; i++) {
11 cin >> a[i];
12 }
13 int ans = 360;
14 for (int l = 0; l < n; l++) {
15 int sum = 0;
16 for (int r = l; r < n; r++) {
17 sum += a[r];
18 ans = min(ans, abs(2 * sum - 360));
19 }
20 }
21 cout << ans << "\n";
22 return 0;
23 }
9: Beautiful Divisors
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is
called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive
zeroes.
12 (110);
1102 (610);
11110002 (12010);
1111100002 (49610).
More formally, the number is beautiful iff there exists some positive integer k such that the number is
equal to (2k - 1) * (2k - 1).
Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find
it!
Back to top 39
Coding with Jiangly 2023-12-31
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 int ans = 1;
10 for (int x = 1; ; x *= 2) {
11 int v = (2 * x - 1) * x;
12 if (v > n) {
13 break;
14 }
15 if (n % v == 0) {
16 ans = v;
17 }
18 }
19 cout << ans << "\n";
20 return 0;
21 }
Back to top 40
Coding with Jiangly 2023-12-31
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int m, k, a1, ak;
6 cin >> m >> k >> a1 >> ak;
7 int t = max(0, min(m / k, (m - a1 + k - 1) / k));
8 int ans = max(0, t - ak) + max(0, m - t * k - a1);
9 cout << ans << "\n";
10 }
11 int main() {
12 ios::sync_with_stdio(false);
13 cin.tie(nullptr);
14 int t;
15 cin >> t;
16 while (t--) {
17 solve();
18 }
19 return 0;
20 }
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as
many teams of three as possible, but since there were only 6 students who wished to participate, the
decision was to build exactly two teams.
After practice competition, participant number i got a score of ai. Team score is defined as sum of
scores of its participants. High school management is interested if it’s possible to build two teams with
equal scores. Your task is to answer that question.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int a[6];
8 for (int i = 0; i < 6; i++) {
9 cin >> a[i];
10 }
11 for (int s = 0; s < (1 << 6); s++) {
12 if (__builtin_popcount(s) == 3) {
13 int bal = 0;
Back to top 41
Coding with Jiangly 2023-12-31
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both
of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it
is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one
neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to
calculate the number of local extrema in the given array.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 vector<int> a(n);
10 for (int i = 0; i < n; i++) {
11 cin >> a[i];
12 }
13 int ans = 0;
14 for (int i = 1; i < n - 1; i++) {
15 if (a[i] > a[i - 1] && a[i] > a[i + 1]) {
16 ans++;
Back to top 42
Coding with Jiangly 2023-12-31
17 }
18 if (a[i] < a[i - 1] && a[i] < a[i + 1]) {
19 ans++;
20 }
21 }
22 cout << ans << "\n";
23 return 0;
24 }
Andrey is just starting to come up with problems, and it’s difficult for him. That’s why he came up with
a strange problem about permutations† and asks you to solve it. Can you do it?
Let’s call the cost of a permutation p of length n the value of the expression:
For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the
array), and [1, 3, 4] is also not a permutation (n = 3 but there is 4 in the array).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 # struct DSU;
5 void solve() {
6 int n;
7 cin >> n;
8 int ans = 0;
9 for (int l = n * n; ; l--) {
10 DSU dsu(n + 1);
11 int sum = 0;
12 bool ok = true;
13 for (int i = n; i >= 1; i--) {
14 int x = dsu.find(min(n, l / i));
15 if (x == 0) {
16 ok = false;
17 break;
18 }
19 sum += i * x;
20 dsu.merge(x - 1, x);
21 }
22 if (!ok) {
23 break;
Back to top 43
Coding with Jiangly 2023-12-31
24 }
25 ans = max(ans, sum - l);
26 }
27 cout << ans << "\n";
28 }
29 int main() {
30 ios::sync_with_stdio(false);
31 cin.tie(nullptr);
32 int t;
33 cin >> t;
34 while (t--) {
35 solve();
36 }
37 return 0;
38 }
14: Fibonaccharsis
Ntarsis has received two integers n and k for his birthday. He wonders how many fibonacci-like
sequences of length k can be formed with n as the k-th element of the sequence.
For example, sequences such as [4, 5, 9, 14] and [0, 1, 1] are considered fibonacci-like sequences, while
[0, 0, 0, 1, 1], [1, 2, 1, 3], and [−1, −1, −2] are not: the first two do not always satisfy fi = fi−1 + fi−2 ,
the latter does not satisfy that the elements are non-negative.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 vector<i64> f{1, 1};
5 void solve() {
6 int n, k;
7 cin >> n >> k;
8 k--;
9 if (k - 1 >= 44 || f[k - 1] > n) {
10 cout << 0 << "\n";
11 return;
12 }
Back to top 44
Coding with Jiangly 2023-12-31
15: Desorting
Add 1 to a1 , a2 , . . . , ai .
Problem: link
Tutorial: link
Back to top 45
Coding with Jiangly 2023-12-31
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int ans = 1E9;
12 for (int i = 1; i < n; i++) {
13 ans = min(ans, max(0, (a[i] - a[i - 1] + 2) / 2));
14 }
15 cout << ans << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
Given a positive integer n, find the maximum size of an interval [l, r] of positive integers such that, for
every i in the interval (i.e., l ≤ i ≤ r), n is a multiple of i.
Given two integers l ≤ r, the size of the interval [l, r] is r − l + 1 (i.e., it coincides with the number of
integers belonging to the interval).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 i64 n;
6 cin >> n;
7 int ans = 1;
8 while (n % (ans + 1) == 0) {
9 ans++;
Back to top 46
Coding with Jiangly 2023-12-31
10 }
11 cout << ans << "\n";
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
You are the author of a Codeforces round and have prepared n problems you are going to set, problem
i having difficulty ai . You will do the following process:
A round is considered balanced if and only if the absolute difference between the difficulty of any two
consecutive problems is at most k (less or equal than k).
What is the minimum number of problems you have to remove so that an arrangement of problems is
balanced?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int ans = 0;
12 sort(a.begin(), a.end());
13 int lst = 0;
14 for (int i = 1; i <= n; i++) {
15 if (i == n || a[i] - a[i - 1] > k) {
16 ans = max(ans, i - lst);
Back to top 47
Coding with Jiangly 2023-12-31
17 lst = i;
18 }
19 }
20 cout << n - ans << "\n";
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
30 return 0;
31 }
Rudolph invented the game of tic-tac-toe for three players. It has classic rules, except for the third
player who plays with pluses. Rudolf has a 3 × 3 field - the result of the completed game. Each field
cell contains either a cross, or a nought, or a plus sign, or nothing. The game is won by the player who
makes a horizontal, vertical or diagonal row of 3’s of their symbols.
Rudolph wants to find the result of the game. Either exactly one of the three players won or it ended in
a draw. It is guaranteed that multiple players cannot win at the same time.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s[3];
6 for (int i = 0; i < 3; i++) {
7 cin >> s[i];
8 }
9 for (int i = 0; i < 3; i++) {
10 if (s[i][0] == s[i][1] && s[i][1] == s[i][2] && s[i][0] != '.') {
11 cout << s[i][0] << "\n";
12 return;
13 }
14 if (s[0][i] == s[1][i] && s[1][i] == s[2][i] && s[0][i] != '.') {
15 cout << s[0][i] << "\n";
16 return;
17 }
18 }
19 if (s[0][0] == s[1][1] && s[1][1] == s[2][2] && s[0][0] != '.') {
Back to top 48
Coding with Jiangly 2023-12-31
There is a group of n people. Some of them might be liars, who always tell lies. Other people always
tell the truth. The i-th person says “There are at least li liars amongst us”. Determine if what people are
saying is contradictory, or if it is possible. If it is possible, output the number of liars in the group. If
there are multiple possible answers, output any one of them.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> l(n);
8 for (int i = 0; i < n; i++) {
9 cin >> l[i];
10 }
11 for (int x = 0; x <= n; x++) {
12 int cnt = 0;
13 for (int i = 0; i < n; i++) {
14 cnt += x < l[i];
15 }
16 if (cnt == x) {
17 cout << x << "\n";
Back to top 49
Coding with Jiangly 2023-12-31
18 return;
19 }
20 }
21 cout << -1 << "\n";
22 }
23 int main() {
24 ios::sync_with_stdio(false);
25 cin.tie(nullptr);
26 int t;
27 cin >> t;
28 while (t--) {
29 solve();
30 }
31 return 0;
32 }
Initially you have a single pile with n gold nuggets. In an operation you can do the following:
Take any pile and split it into two piles, so that one of the resulting piles has exactly twice as many gold
nuggets as the other. (All piles should have an integer number of nuggets.)
One possible move is to take a pile of size 6 and split it into piles of sizes 2 and 4, which is valid since 4
is twice as large as 2.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 int t = 0;
8 while (n % 3 == 0 && m % 3 == 0) {
9 n /= 3;
10 m /= 3;
11 }
12 while (n % 3 == 0) {
13 n /= 3;
14 t++;
15 }
16 if (m % n != 0) {
17 cout << "NO\n";
18 return;
19 }
20 m /= n;
Back to top 50
Coding with Jiangly 2023-12-31
constructive algorithms
You are given a string s, consisting only of characters ‘0’ and/or ‘1’.
In one operation, you choose a position i from 1 to |s| − 1, where |s| is the current length of string s.
Then you insert a character between the i-th and the (i + 1)-st characters of s. If si = si+1 , you insert
‘1’. If si ̸= si+1 , you insert ‘0’.
Is it possible to make the number of zeroes in the string strictly greater than the number of ones, using
any number of operations (possibly, none)?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 if (count(s.begin(), s.end(), '1') == n) {
10 cout << "NO\n";
11 } else {
12 cout << "YES\n";
Back to top 51
Coding with Jiangly 2023-12-31
13 }
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
You are given an array of integers a1 , a2 , . . . , an . In one operation, you do the following:
Can you sort the array in non-decreasing order by performing some number (possibly zero) of opera-
tions?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 1; i < n; i++) {
12 if ((i & (i - 1)) != 0 && a[i] < a[i - 1]) {
13 cout << "NO\n";
14 return;
15 }
16 }
17 cout << "YES\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
Back to top 52
Coding with Jiangly 2023-12-31
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
You are given a board of size n × n (n rows and n colums) and two arrays of positive integers a and b of
size n.
Your task is to place the chips on this board so that the following condition is satisfied for every cell
(i, j):
there exists at least one chip in the same column or in the same row as the cell (i, j). I. e. there exists a
cell (x, y) such that there is a chip in that cell, and either x = i or y = j (or both).
For example, for n = 3, a = [1, 4, 1] and b = [3, 2, 2]. One of the possible chip placements is as
follows:
Calculate the minimum possible total cost of putting chips according to the rules above.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 i64 sa = 0;
8 int mina = 1E9;
9 for (int i = 0; i < n; i++) {
10 int a;
11 cin >> a;
12 sa += a;
Back to top 53
Coding with Jiangly 2023-12-31
You are given three non-negative integers n, k, and x. Find the maximum possible sum of elements in
an array consisting of non-negative integers, which has n elements, its MEX is equal to k, and all its
elements do not exceed x. If such an array does not exist, output −1.
The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to
the array. For instance:
The MEX of [3, 1, 0, 1] is 2, because 0 and 1 belong to the array, but 2 does not.
The MEX of [0, 3, 1, 2] is 4, because 0, 1, 2 and 3 belong to the array, but 4 does not.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
Back to top 54
Coding with Jiangly 2023-12-31
4 void solve() {
5 int n, k, x;
6 cin >> n >> k >> x;
7 if (k > n || k > x + 1) {
8 cout << -1 << "\n";
9 } else if (k == x) {
10 cout << k * (k - 1) / 2 + (n - k) * (k - 1) << "\n";
11 } else {
12 cout << k * (k - 1) / 2 + (n - k) * x << "\n";
13 }
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
During Zhongkao examination, Reycloer met an interesting problem, but he cannot come up with a
solution immediately. Time is running out! Please help him.
Initially, you are given an array a consisting of n ≥ 2 integers, and you want to change all elements in
it to 0.
In one operation, you select two indices l and r (1 ≤ l ≤ r ≤ n) and do the following:
You can use the operation above in any order at most 8 times in total.
Find a sequence of operations, such that after performing the operations in order, all elements in a are
equal to 0. It can be proven that the solution always exists.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
Back to top 55
Coding with Jiangly 2023-12-31
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 cout << 5 << "\n";
12 cout << 1 << " " << n << "\n";
13 cout << 1 << " " << n << "\n";
14 cout << 1 << " " << n - 1 << "\n";
15 cout << n - 1 << " " << n << "\n";
16 cout << n - 1 << " " << n << "\n";
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
You are given a binary string s of length n (a string that consists only of 0 and 1). A number x is good if
there exists a binary string l of length n, containing x ones, such that if each symbol si is replaced by
si ⊕ li (where ⊕ denotes the bitwise XOR operation), then the string s becomes a palindrome.
A palindrome is a string that reads the same from left to right as from right to left. For example, 01010,
1111, 0110 are palindromes.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
Back to top 56
Coding with Jiangly 2023-12-31
9 int l = 0, r = 0;
10 for (int i = 0; i < n - 1 - i; i++) {
11 if (s[i] == s[n - 1 - i]) {
12 r += 2;
13 } else {
14 l++, r++;
15 }
16 }
17 string ans(n + 1, '0');
18 for (int i = l; i <= r; i += 2) {
19 ans[i] = '1';
20 if (n % 2 == 1) {
21 ans[i + 1] = '1';
22 }
23 }
24 cout << ans << "\n";
25 }
26 int main() {
27 ios::sync_with_stdio(false);
28 cin.tie(nullptr);
29 int t;
30 cin >> t;
31 while (t--) {
32 solve();
33 }
34 return 0;
35 }
green_gold_dog has an array a of length n, and he wants to find a permutation b of length n such that
the number of distinct numbers in the element-wise difference between array a and permutation b is
maximized.
A permutation of length n is an array consisting of n distinct integers from 1 to n in any order. For
example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (as 2 appears twice in the
array) and [1, 3, 4] is also not a permutation (as n = 3, but 4 appears in the array).
The element-wise difference between two arrays a and b of length n is an array c of length n, where ci
= ai − bi (1 ≤ i ≤ n).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
Back to top 57
Coding with Jiangly 2023-12-31
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector<int> p(n);
12 iota(p.begin(), p.end(), 0);
13 sort(p.begin(), p.end(),
14 [&](int i, int j) {
15 return a[i] < a[j];
16 });
17 vector<int> b(n);
18 for (int i = 0; i < n; i++) {
19 b[p[i]] = n - i;
20 }
21 for (int i = 0; i < n; i++) {
22 cout << b[i] << " \n"[i == n - 1];
23 }
24 }
25 int main() {
26 ios::sync_with_stdio(false);
27 cin.tie(nullptr);
28 int t;
29 cin >> t;
30 while (t--) {
31 solve();
32 }
33 return 0;
34 }
Madoka’s father just reached 1 million subscribers on Mathub! So the website decided to send him a
personalized award - The Mathhub’s Bit Button!
The Bit Button is a rectangular table with n rows and m columns with 0 or 1 in each cell. After exploring
the table Madoka found out that:
A subrectangle is called nice if it’s black and it’s not contained in another black subrectangle.
Back to top 58
Coding with Jiangly 2023-12-31
The table is called elegant if there are no two nice intersecting subrectangles.
For example, in the first illustration the red subrectangle is nice, but in the second one it’s not, because
it’s contained in the purple subrectangle.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<string> s(n);
8 for (int i = 0; i < n; i++) {
9 cin >> s[i];
10 }
11 for (int i = 0; i < n - 1; i++) {
12 for (int j = 0; j < m - 1; j++) {
13 if (s[i][j] - '0' + s[i][j + 1] - '0' + s[i + 1][j] - '0' + s[i + 1][j + 1] -
'0' == 3) {
14 cout << "NO\n";
15 return;
16 }
17 }
18 }
19 cout << "YES\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
Patchouli is making a magical talisman. She initially has n magical tokens. Their magical power can be
represented with positive integers a1 , a2 , . . . , an .
Back to top 59
Coding with Jiangly 2023-12-31
Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power
equal to the sum of the two chosen tokens.
Reduction: Patchouli chooses a token with an even value of magical power x, removes it and creates a
new token with magical power equal to x2 .
Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the
minimum number of operations she needs to make magical powers of all tokens odd values.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int even = 0;
8 int l = 30;
9 for (int i = 0; i < n; i++) {
10 int a;
11 cin >> a;
12 even += (a % 2 == 0);
13 l = min(l, __builtin_ctz(a));
14 }
15 int ans = l == 0 ? even : n - 1 + l;
16 cout << ans << "\n";
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
You are given three integers n, l, and r. You need to construct an array a1 , a2 , . . . , an (l ≤ ai ≤ r) such
that gcd(i, ai ) are all distinct or report there’s no solution.
Back to top 60
Coding with Jiangly 2023-12-31
Here gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, l, r;
6 cin >> n >> l >> r;
7 vector<int> a(n);
8 for (int i = 1; i <= n; i++) {
9 if (r / i == (l - 1) / i) {
10 cout << "NO\n";
11 return;
12 }
13 a[i - 1] = r / i * i;
14 }
15 cout << "YES\n";
16 for (int i = 0; i < n; i++) {
17 cout << a[i] << " \n"[i == n - 1];
18 }
19 }
20 int main() {
21 ios::sync_with_stdio(false);
22 cin.tie(nullptr);
23 int t;
24 cin >> t;
25 while (t--) {
26 solve();
27 }
28 return 0;
29 }
You are given two strings a and b of equal length, consisting of only characters 0 and/or 1; both strings
start with character 0 and end with character 1.
You can perform the following operation any number of times (possibly zero):
choose one of the strings and two equal characters in it; then turn all characters between them into
those characters.
Formally, you choose one of these two strings (let the chosen string be s), then pick two integers l and
r such that 1 ≤ l < r ≤ |s| and sl = sr , then replace every character si such that l < i < r with sl .
Back to top 61
Coding with Jiangly 2023-12-31
For example, if the chosen string is 010101, you can transform it into one of the following strings by
applying one operation:
You have to determine if it’s possible to make the given strings equal by applying this operation any
number of times.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string a, b;
6 cin >> a >> b;
7 int n = a.size();
8 for (int i = 0; i < n - 1; i++) {
9 if (a[i] == '0' && b[i] == '0' && a[i + 1] == '1' && b[i + 1] == '1') {
10 cout << "YES\n";
11 return;
12 }
13 }
14 cout << "NO\n";
15 }
16 int main() {
17 ios::sync_with_stdio(false);
18 cin.tie(nullptr);
19 int t;
20 cin >> t;
21 while (t--) {
22 solve();
23 }
24 return 0;
25 }
Back to top 62
Coding with Jiangly 2023-12-31
A prime number is a positive integer that has exactly two different positive divisors: 1 and the integer
itself. For example, 2, 3, 13 and 101 are prime numbers; 1, 4, 6 and 42 are not.
You are given a sequence of digits from 1 to 9, in which every digit from 1 to 9 appears exactly once.
You are allowed to do the following operation several (maybe zero) times: choose any digit from the
sequence and delete it. However, you cannot perform this operation if the sequence consists of only
two digits.
Your goal is to obtain a sequence which represents a prime number. Note that you cannot reorder the
digits in the sequence.
Print the resulting sequence, or report that it is impossible to perform the operations so that the
resulting sequence is a prime number.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 if (s.find('1') < s.find('3')) {
8 cout << "13\n";
9 } else {
10 cout << "31\n";
11 }
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
You are given a string s of length n consisting of lowercase English letters, and an integer k. In one step
you can perform any one of the two operations below:
Back to top 63
Coding with Jiangly 2023-12-31
Pick an index i (1 ≤ i ≤ n − k + 1) and reverse the order of letters formed by the range [i, i + k − 1] of
the string. Formally, if the string currently is equal to s1 . . . si−1 si si+1 . . . si+k−2 si+k−1 si+k . . . sn−1 sn ,
change it to s1 . . . si−1 si+k−1 si+k−2 . . . si+1 si si+k . . . sn−1 sn .
You can make as many steps as you want (possibly, zero). Your task is to find the lexicographically
smallest string you can obtain after some number of steps.
A string a is lexicographically smaller than a string b of the same length if and only if the following
holds:
in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet
than the corresponding letter in b.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 string s;
8 cin >> s;
9 if (k % 2 == 0) {
10 sort(s.begin(), s.end());
11 } else {
12 for (int p = 0; p < 2; p++) {
13 string t;
14 for (int i = p; i < n; i += 2) {
15 t += s[i];
16 }
17 sort(t.begin(), t.end());
18 for (int i = p; i < n; i += 2) {
19 s[i] = t[i / 2];
20 }
21 }
22 }
23 cout << s << "\n";
24 }
25 int main() {
26 ios::sync_with_stdio(false);
27 cin.tie(nullptr);
28 int t;
29 cin >> t;
30 while (t--) {
31 solve();
32 }
33 return 0;
34 }
Back to top 64
Coding with Jiangly 2023-12-31
Your task is to construct an array a consisting of n integers which satisfies the following conditions:
a1 = x, an = y;
if we denote bi = ai+1 − ai for 1 ≤ i ≤ n − 1, then b is strictly decreasing (i.e. b1 > b2 > . . . > bn−1 ).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int x, y, n;
6 cin >> x >> y >> n;
7 if (y - x < n * (n - 1) / 2) {
8 cout << -1 << "\n";
9 return;
10 }
11 vector<int> a(n);
12 a[0] = x;
13 a[n - 1] = y;
14 int t = 1;
15 for (int i = n - 2; i > 0; i--) {
16 y -= t;
17 t++;
18 a[i] = y;
19 }
20 for (int i = 0; i < n; i++) {
21 cout << a[i] << " \n"[i == n - 1];
22 }
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
Back to top 65
Coding with Jiangly 2023-12-31
First, Vika comes up with a sequence of positive integers a of length m and writes it down on a piece of
paper. Then she takes a new piece of paper and writes down the sequence b according to the following
rule:
Then, she writes down only those ai (2 ≤ i ≤ m) such that ai−1 ≤ ai . Let the length of this sequence
be denoted as n.
For example, from the sequence a = [4, 3, 2, 6, 3, 3], Vika will obtain the sequence b = [4, 6, 3].
She then gives the piece of paper with the sequence b to Tema. He, in turn, tries to guess the sequence
a.
Tema considers winning in such a game highly unlikely, but still wants to find at least one sequence a
that could have been originally chosen by Vika. Help him and output any such sequence.
Note that the length of the sequence you output should not exceed the input sequence length by more
than two times.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> b(n);
8 for (int i = 0; i < n; i++) {
9 cin >> b[i];
10 }
11 vector<int> a;
12 a.reserve(2 * n);
13 for (int i = 0; i < n; i++) {
14 if (i == 0 || b[i] >= b[i - 1]) {
15 a.push_back(b[i]);
16 } else {
17 a.push_back(b[i]);
18 a.push_back(b[i]);
Back to top 66
Coding with Jiangly 2023-12-31
19 }
20 }
21 const int m = a.size();
22 cout << m << "\n";
23 for (int i = 0; i < m; i++) {
24 cout << a[i] << " \n"[i == m - 1];
25 }
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
A bracket sequence is a string consisting of characters ‘(’ and/or ‘)’. A regular bracket sequence is a
bracket sequence that can be transformed into a correct arithmetic expression by inserting characters
‘1’ and ‘+’ between the original characters of the sequence. For example:
bracket sequences “()()” and “(())” are regular (they can be transformed into “(1)+(1)” and “((1+1)+1)”,
respectively);
You are given a bracket sequence s; let’s define its length as n. Your task is to find a regular bracket
sequence t of length 2n such that s does not occur in t as a contiguous substring, or report that there
is no such sequence.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 int n = s.size();
Back to top 67
Coding with Jiangly 2023-12-31
8 if (s == "()") {
9 cout << "NO\n";
10 return;
11 }
12 cout << "YES\n";
13 bool alt = true;
14 for (int i = 1; i < n; i++) {
15 if (s[i] == s[i - 1]) {
16 alt = false;
17 }
18 }
19 if (alt) {
20 cout << string(n, '(') + string(n, ')') << "\n";
21 } else {
22 for (int i = 1; i <= n; i++) {
23 cout << "()";
24 }
25 cout << "\n";
26 }
27 }
28 int main() {
29 ios::sync_with_stdio(false);
30 cin.tie(nullptr);
31 int t;
32 cin >> t;
33 while (t--) {
34 solve();
35 }
36 return 0;
37 }
Alex got a new game called “GCD permutations” as a birthday present. Each round of this game
proceeds as follows:
Then, for each i from 1 to n, an integer di = gcd(ai , a(i mod n)+1 ) is calculated.
Alex has already played several rounds so he decided to find a permutation a1 , a2 , . . . , an such that its
score is as large as possible.
Recall that gcd(x, y) denotes the greatest common divisor (GCD) of numbers x and y, and x mod y
denotes the remainder of dividing x by y.
Back to top 68
Coding with Jiangly 2023-12-31
For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the
array), and [1, 3, 4] is also not a permutation (n = 3 but there is 4 in the array).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a;
8 a.reserve(n);
9 for (int i = 1; i <= n; i += 2) {
10 for (int j = i; j <= n; j *= 2) {
11 a.push_back(j);
12 }
13 }
14 for (int i = 0; i < n; i++) {
15 cout << a[i] << " \n"[i == n - 1];
16 }
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
Artem suggested a game to the girl Olya. There is a list of n arrays, where the i-th array contains mi ≥ 2
positive integers ai,1 , ai,2 , . . . , ai,mi .
Olya can move at most one (possibly 0) integer from each array to another array. Note that integers
can be moved from one array only once, but integers can be added to one array multiple times, and all
the movements are done at the same time.
The beauty of the list of arrays is defined as the sum ni=1 minm
j=1 ai,j . In other words, for each array,
P i
Back to top 69
Coding with Jiangly 2023-12-31
The goal of the game is to maximize the beauty of the list of arrays. Help Olya win this challenging
game!
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<vector<int>> a(n);
8 int min = 1E9;
9 int min2 = 1E9;
10 i64 ans = 0;
11 for (int i = 0; i < n; i++) {
12 int m;
13 cin >> m;
14 a[i].resize(m);
15 for (int j = 0; j < m; j++) {
16 cin >> a[i][j];
17 }
18 nth_element(a[i].begin(), a[i].begin() + 1, a[i].end());
19 min = min(min, a[i][0]);
20 min2 = min(min2, a[i][1]);
21 ans += a[i][1];
22 }
23 ans -= min2;
24 ans += min;
25 cout << ans << "\n";
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
Given an array a of length n, containing integers. And there are two initially empty arrays b and c. You
need to add each element of array a to exactly one of the arrays b or c, in order to satisfy the following
conditions:
Back to top 70
Coding with Jiangly 2023-12-31
Both arrays b and c are non-empty. More formally, let lb be the length of array b, and lc be the length of
array c. Then lb , lc ≥ 1.
Output the arrays b and c that can be obtained, or output −1 if they do not exist.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 # struct SCC;
5 void solve() {
6 int n;
7 cin >> n;
8 SCC g(n);
9 vector<int> a(n);
10 for (int i = 0; i < n; i++) {
11 cin >> a[i];
12 }
13 for (int i = 0; i < n; i++) {
14 for (int j = 0; j < n; j++) {
15 if (a[i] % a[j] == 0) {
16 g.addEdge(i, j);
17 }
18 }
19 }
20 auto bel = g.work();
21 if (bel == vector(n, 0)) {
22 cout << -1 << "\n";
23 return;
24 }
25 vector<int> b, c;
26 for (int i = 0; i < n; i++) {
27 if (bel[i] == 0) {
28 b.push_back(i);
29 } else {
30 c.push_back(i);
31 }
32 }
33 cout << b.size() << " " << c.size() << "\n";
34 for (auto i : b) {
35 cout << a[i] << " \n"[i == b.back()];
36 }
37 for (auto i : c) {
38 cout << a[i] << " \n"[i == c.back()];
39 }
40 }
41 int main() {
42 ios::sync_with_stdio(false);
43 cin.tie(nullptr);
44 int t;
45 cin >> t;
46 while (t--) {
47 solve();
48 }
49 return 0;
50 }
Back to top 71
Coding with Jiangly 2023-12-31
One day, Vlad became curious about who he can have a conversation with on the escalator in the
subway. There are a total of n passengers. The escalator has a total of m steps, all steps indexed from 1
to m and i-th step has height i · k.
Vlad’s height is H centimeters. Two people with heights a and b can have a conversation on the
escalator if they are standing on different steps and the height difference between them is equal to the
height difference between the steps.
For example, if two people have heights 170 and 180 centimeters, and m = 10, k = 5, then they can
stand on steps numbered 7 and 5, where the height difference between the steps is equal to the height
difference between the two people: k · 2 = 5 · 2 = 10 = 180 − 170. There are other possible ways.
Given an array h of size n, where hi represents the height of the i-th person. Vlad is interested in how
many people he can have a conversation with on the escalator individually.
For example, if n = 5, m = 3, k = 3, H = 11, and h = [5, 4, 14, 18, 2], Vlad can have a conversation
with the person with height 5 (Vlad will stand on step 1, and the other person will stand on step 3) and
with the person with height 14 (for example, Vlad can stand on step 3, and the other person will stand
on step 2). Vlad cannot have a conversation with the person with height 2 because even if they stand
on the extreme steps of the escalator, the height difference between them will be 6, while their height
difference is 9. Vlad cannot have a conversation with the rest of the people on the escalator, so the
answer for this example is 2.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m, k, H;
6 cin >> n >> m >> k >> H;
7 int ans = 0;
8 for (int i = 0; i < n; i++) {
9 int h;
10 cin >> h;
11 if (h != H && (h - H) % k == 0 && abs(h - H) < m * k) {
12 ans++;
13 }
Back to top 72
Coding with Jiangly 2023-12-31
14 }
15 cout << ans << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
greedy
Masha and Olya have an important team olympiad coming up soon. In honor of this, Masha, for
warm-up, suggested playing a game with Olya:
There is an array a of size n. Masha goes first, and the players take turns. Each move is described by
the following sequence of actions:
• The player who is currently playing chooses two different indices i, j (1 ≤ i, j ≤ |a|), and performs
the following operation - removes ai and aj from the array and adds to the array a number equal to
a +a
⌊ i 2 j ⌋ · 2. In other words, first divides the sum of the numbers ai , aj by 2 rounding down, and then
multiplies the result by 2.
Masha aims to maximize the final number, while Olya aims to minimize it.
Masha and Olya decided to play on each non-empty prefix of the initial array a, and asked for your
help.
For each k = 1, 2, . . . , n, answer the following question. Let only the first k elements of the array a be
present in the game, with indices 1, 2, . . . , k respectively. What number will remain at the end with
optimal play by both players?
Problem: link
Tutorial: link
Back to top 73
Coding with Jiangly 2023-12-31
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 i64 sum = 0;
8 int odd = 0;
9 for (int i = 1; i <= n; i++) {
10 int a;
11 cin >> a;
12 sum += a;
13 odd += a % 2;
14 int res;
15 if (odd == 1 && i == 1) {
16 res = 0;
17 } else {
18 res = odd / 3;
19 if (odd % 3 == 1) {
20 res += 1;
21 }
22 }
23 cout << sum - res << " \n"[i == n];
24 }
25 }
26 int main() {
27 ios::sync_with_stdio(false);
28 cin.tie(nullptr);
29 int t;
30 cin >> t;
31 while (t--) {
32 solve();
33 }
34 return 0;
35 }
Lura was bored and decided to make a simple language using the five letters a, b, c, d, e. There are
two types of letters:
A word in the language is a sequence of syllables. Lura has written a word in the language, but she
doesn’t know how to split it into syllables. Help her break the word into syllables.
Back to top 74
Coding with Jiangly 2023-12-31
For example, given the word bacedbab, it would be split into syllables as ba.ced.bab (the dot .
represents a syllable boundary).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 bool isVowel(char c) {
5 return c == 'a' || c == 'e';
6 }
7 void solve() {
8 int n;
9 cin >> n;
10 string s;
11 cin >> s;
12 vector<string> t;
13 for (int i = n - 1; i >= 0; ) {
14 if (isVowel(s[i])) {
15 t.push_back(s.substr(i - 1, 2));
16 i -= 2;
17 } else {
18 t.push_back(s.substr(i - 2, 3));
19 i -= 3;
20 }
21 }
22 reverse(t.begin(), t.end());
23 for (int i = 0; i < t.size(); i++) {
24 cout << t[i] << ".\n"[i == t.size() - 1];
25 }
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
Winter holidays are coming up. They are going to last for n days.
During the holidays, Monocarp wants to try all of these activities exactly once with his friends:
go skiing;
Back to top 75
Coding with Jiangly 2023-12-31
Monocarp knows that, on the i-th day, exactly ai friends will join him for skiing, bi friends will join him
for a movie and ci friends will join him for board games.
Monocarp also knows that he can’t try more than one activity in a single day.
Thus, he asks you to help him choose three distinct days x, y, z in such a way that the total number of
friends to join him for the activities (ax + by + cz ) is maximized.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n), b(n), c(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 0; i < n; i++) {
12 cin >> b[i];
13 }
14 for (int i = 0; i < n; i++) {
15 cin >> c[i];
16 }
17 vector<int> pa(n), pb(n), pc(n);
18 iota(pa.begin(), pa.end(), 0);
19 iota(pb.begin(), pb.end(), 0);
20 iota(pc.begin(), pc.end(), 0);
21 sort(pa.begin(), pa.end(),
22 [&](int i, int j) {
23 return a[i] > a[j];
24 });
25 sort(pb.begin(), pb.end(),
26 [&](int i, int j) {
27 return b[i] > b[j];
28 });
29 sort(pc.begin(), pc.end(),
30 [&](int i, int j) {
31 return c[i] > c[j];
32 });
33 int ans = 0;
34 for (int i = 0; i < 3; i++) {
35 for (int j = 0; j < 3; j++) {
36 for (int k = 0; k < 3; k++) {
37 int x = pa[i], y = pb[j], z = pc[k];
38 if (x != y && y != z && x != z) {
39 ans = max(ans, a[x] + b[y] + c[z]);
40 }
41 }
42 }
43 }
Back to top 76
Coding with Jiangly 2023-12-31
44: Quests
Monocarp is playing a computer game. In order to level up his character, he can complete quests. There
are n quests in the game, numbered from 1 to n.
the i-th quest is available for completion if all quests j < i have been completed at least once.
Note that Monocarp can complete the same quest multiple times.
For each completion, the character gets some amount of experience points:
for the first completion of the i-th quest, he gets ai experience points;
for each subsequent completion of the i-th quest, he gets bi experience points.
Monocarp is a very busy person, so he has free time to complete no more than k quests. Your task is to
calculate the maximum possible total experience Monocarp can get if he can complete no more than k
quests.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
Back to top 77
Coding with Jiangly 2023-12-31
Compress all the vertices on the path from u to v into one vertex. In other words, all the vertices on
path from u to v will be erased from the tree, a new vertex w will be created. Then every vertex s that
had an edge to some vertex on the path from u to v will have an edge to the vertex w.
Determine the minimum number of zelda-operations required for the tree to have only one vertex.
† A tree is a connected acyclic undirected graph.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
Back to top 78
Coding with Jiangly 2023-12-31
Vlad found a string s consisting of n lowercase Latin letters, and he wants to make it as short as
possible.
To do this, he can remove any pair of adjacent characters from s any number of times, provided they
are different. For example, if s=racoon, then by removing one pair of characters he can obtain the
strings coon, roon, raon, and raco, but he cannot obtain racn (because the removed letters were the
same) or rcon (because the removed letters were not adjacent).
What is the minimum length Vlad can achieve by applying any number of deletions?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
Back to top 79
Coding with Jiangly 2023-12-31
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 array<int, 26> cnt{};
10 for (auto c : s) {
11 cnt[c - 'a'] += 1;
12 }
13 int ans = n - 2 * min(n / 2, n - *max_element(cnt.begin(), cnt.end()));
14 cout << ans << "\n";
15 }
16 int main() {
17 ios::sync_with_stdio(false);
18 cin.tie(nullptr);
19 int t;
20 cin >> t;
21 while (t--) {
22 solve();
23 }
24 return 0;
25 }
There is a ribbon divided into n cells, numbered from 1 to n from left to right. Initially, an integer 0 is
written in each cell.
Monocarp plays a game with a chip. The game consists of several turns. During the first turn, Monocarp
places the chip in the 1-st cell of the ribbon. During each turn except for the first turn, Monocarp does
exactly one of the two following actions:
move the chip to the next cell (i. e. if the chip is in the cell i, it is moved to the cell i + 1). This action is
impossible if the chip is in the last cell;
choose any cell x and teleport the chip into that cell. It is possible to choose the cell where the chip is
currently located.
At the end of each turn, the integer written in the cell with the chip is increased by 1.
Monocarp’s goal is to make some turns so that the 1-st cell contains the integer c1 , the 2-nd cell contains
the integer c2 , . . . , the n-th cell contains the integer cn . He wants to teleport the chip as few times as
possible.
Help Monocarp calculate the minimum number of times he has to teleport the chip.
Problem: link
Back to top 80
Coding with Jiangly 2023-12-31
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> c(n);
8 for (int i = 0; i < n; i++) {
9 cin >> c[i];
10 }
11 i64 ans = c[0];
12 for (int i = 1; i < n; i++) {
13 ans += max(0, c[i] - c[i - 1]);
14 }
15 cout << ans - 1 << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
There is a road, which can be represented as a number line. You are located in the point 0 of the number
line, and you want to travel from the point 0 to the point x, and back to the point 0.
You travel by car, which spends 1 liter of gasoline per 1 unit of distance travelled. When you start at the
point 0, your car is fully fueled (its gas tank contains the maximum possible amount of fuel).
There are n gas stations, located in points a1 , a2 , . . . , an . When you arrive at a gas station, you fully
refuel your car. Note that you can refuel only at gas stations, and there are no gas stations in points 0
and x.
You have to calculate the minimum possible volume of the gas tank in your car (in liters) that will allow
you to travel from the point 0 to the point x and back to the point 0.
Problem: link
Back to top 81
Coding with Jiangly 2023-12-31
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, x;
6 cin >> n >> x;
7 vector<int> a(n + 1);
8 for (int i = 1; i <= n; i++) {
9 cin >> a[i];
10 }
11 int ans = 2 * (x - a[n]);
12 for (int i = 1; i <= n; i++) {
13 ans = max(ans, a[i] - a[i - 1]);
14 }
15 cout << ans << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
In Cyprus, the weather is pretty hot. Thus, Theofanis saw this as an opportunity to create an ice cream
company.
He keeps the ice cream safe from other ice cream producers by locking it inside big storage rooms.
However, he forgot the password. Luckily, the lock has a special feature for forgetful people!
It gives you a table M with n rows and n columns of non-negative integers, and to open the lock, you
need to find an array a of n elements such that:
The lock has a bug, and sometimes it gives tables without any solutions. In that case, the ice cream
will remain frozen for the rest of eternity.
Back to top 82
Coding with Jiangly 2023-12-31
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector M(n, vector<int>(n));
8 vector<int> a(n, (1 << 30) - 1);
9 for (int i = 0; i < n; i++) {
10 for (int j = 0; j < n; j++) {
11 cin >> M[i][j];
12 if (i != j) {
13 a[i] &= M[i][j];
14 a[j] &= M[i][j];
15 }
16 }
17 }
18 for (int i = 0; i < n; i++) {
19 for (int j = 0; j < n; j++) {
20 if (i != j && M[i][j] != (a[i] | a[j])) {
21 cout << "NO\n";
22 return;
23 }
24 }
25 }
26 cout << "YES\n";
27 for (int i = 0; i < n; i++) {
28 cout << a[i] << " \n"[i == n - 1];
29 }
30 }
31 int main() {
32 ios::sync_with_stdio(false);
33 cin.tie(nullptr);
34 int t;
35 cin >> t;
36 while (t--) {
37 solve();
38 }
39 return 0;
40 }
Theofanis is busy after his last contest, as now, he has to deliver many halloumis all over the world. He
stored them inside n boxes and each of which has some number ai written on it.
Back to top 83
Coding with Jiangly 2023-12-31
He wants to sort them in non-decreasing order based on their number, however, his machine works in
a strange way. It can only reverse any subarray† of boxes with length at most k.
Find if it’s possible to sort the boxes using any number of reverses.
† Reversing a subarray means choosing two indices i and j (where 1 ≤ i ≤ j ≤ n) and changing
the array a1 , a2 , . . . , an to a1 , a2 , . . . , ai−1 , aj , aj−1 , . . . , ai , aj+1 , . . . , an−1 , an . The length of the
subarray is then j − i + 1.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 if (k > 1 || is_sorted(a.begin(), a.end())) {
12 cout << "YES\n";
13 } else {
14 cout << "NO\n";
15 }
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
Monocarp is a student at Berland State University. Due to recent changes in the Berland education
system, Monocarp has to study only one subject - programming.
The academic term consists of n days, and in order not to get expelled, Monocarp has to earn at least
P points during those n days. There are two ways to earn points - completing practical tasks and
Back to top 84
Coding with Jiangly 2023-12-31
attending lessons. For each practical task Monocarp fulfills, he earns t points, and for each lesson he
attends, he earns l points.
Practical tasks are unlocked “each week” as the term goes on: the first task is unlocked on day 1 (and
can be completed on any day from 1 to n), the second task is unlocked on day 8 (and can be completed
on any day from 8 to n), the third task is unlocked on day 15, and so on.
Every day from 1 to n, there is a lesson which can be attended by Monocarp. And every day, Monocarp
chooses whether to study or to rest the whole day. When Monocarp decides to study, he attends a
lesson and can complete no more than 2 tasks, which are already unlocked and not completed yet. If
Monocarp rests the whole day, he skips a lesson and ignores tasks.
Monocarp wants to have as many days off as possible, i. e. he wants to maximize the number of days
he rests. Help him calculate the maximum number of days he can rest!
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 i64 P;
7 int l, t;
8 cin >> n >> P >> l >> t;
9 int task = (n - 1) / 7 + 1;
10 int ans = max((P - 1) / (l + 2LL * t) + 1, (P - 1LL * t * task - 1) / l + 1);
11 ans = n - ans;
12 cout << ans << "\n";
13 }
14 int main() {
15 ios::sync_with_stdio(false);
16 cin.tie(nullptr);
17 int t;
18 cin >> t;
19 while (t--) {
20 solve();
21 }
22 return 0;
23 }
Back to top 85
Coding with Jiangly 2023-12-31
Filip has a row of cells, some of which are blocked, and some are empty. He wants all empty cells to
have water in them. He has two actions at his disposal:
2 - remove water from a cell and place it in any other empty cell.
If at some moment cell i (2 ≤ i ≤ n − 1) is empty and both cells i − 1 and i + 1 contains water, then it
becomes filled with water.
Find the minimum number of times he needs to perform action 1 in order to fill all empty cells with
water.
Note that you don’t need to minimize the use of action 2. Note that blocked cells neither contain water
nor can Filip place water in them.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 int ans = 0;
10 for (int l = 0, r = 0; l < n; l = r) {
11 while (r < n && s[l] == s[r]) {
12 r++;
13 }
14 if (s[l] == '.') {
15 ans += r - l;
16 if (r - l >= 3) {
17 ans = 2;
18 break;
19 }
20 }
21 }
22 cout << ans << "\n";
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
Back to top 86
Coding with Jiangly 2023-12-31
Yarik recently found an array a of n elements and became very interested in finding the maximum sum
of a non empty subarray. However, Yarik doesn’t like consecutive integers with the same parity, so the
subarray he chooses must have alternating parities for adjacent elements.
For example, [1, 2, 3] is acceptable, but [1, 2, 4] is not, as 2 and 4 are both even and adjacent.
You need to help Yarik by finding the maximum sum of such a subarray.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int ans = -1E9;
12 int suf = -1E9;
13 for (int i = 0; i < n; i++) {
14 if (i && (a[i] - a[i - 1]) % 2 == 0) {
15 suf = 0;
16 }
17 suf = max(suf, 0) + a[i];
18 ans = max(ans, suf);
19 }
20 cout << ans << "\n";
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
30 return 0;
31 }
Back to top 87
Coding with Jiangly 2023-12-31
You are given a sequence of integers a of length 2n. You have to split these 2n integers into n pairs; each
pair will represent the coordinates of a point on a plane. Each number from the sequence a should
become the x or y coordinate of exactly one point. Note that some points can be equal.
After the points are formed, you have to choose a path s that starts from one of these points, ends at
one of these points, and visits all n points at least once.
The length of path s is the sum of distances between all adjacent points on the path. In this problem,
the distance between two points (x1 , y1 ) and (x2 , y2 ) is defined as |x1 − x2 | + |y1 − y2 |.
Your task is to form n points and choose a path s in such a way that the length of path s is minimized.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(2 * n);
8 for (int i = 0; i < 2 * n; i++) {
9 cin >> a[i];
10 }
11 sort(a.begin(), a.end());
12 int ans = a[n - 1] - a[0] + a[2 * n - 1] - a[n];
13 cout << ans << "\n";
14 for (int i = 0; i < n; i++) {
15 cout << a[i] << " " << a[n + i] << "\n";
16 }
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
Back to top 88
Coding with Jiangly 2023-12-31
You are given a number in binary representation consisting of exactly n bits, possibly, with leading
zeroes. For example, for n = 5 the number 6 will be given as 00110, and for n = 4 the number 9 will be
given as 1001.
Let’s fix some integer i such that 1 ≤ i ≤ n. In one operation you can swap any two adjacent bits in
the binary representation. Your goal is to find the smallest number of operations you are required to
perform to make the number divisible by 2i , or say that it is impossible.
Please note that for each 1 ≤ i ≤ n you are solving the problem independently.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 i64 ans = 0;
10 int l = n, r = n;
11 for (int i = 1; i <= n; i++) {
12 if (ans != -1) {
13 if (l > n - i && s[n - i] == '0') {
14 l -= 1;
15 } else {
16 while (l > 0 && s[l - 1] == '1') {
17 l -= 1;
18 }
19 if (l == 0) {
20 ans = -1;
21 } else {
22 ans += r - l;
23 }
24 l -= 1;
25 }
26 r -= 1;
27 }
28 cout << ans << " \n"[i == n];
29 }
30 }
31 int main() {
32 ios::sync_with_stdio(false);
33 cin.tie(nullptr);
Back to top 89
Coding with Jiangly 2023-12-31
34 int t;
35 cin >> t;
36 while (t--) {
37 solve();
38 }
39 return 0;
40 }
A positive integer is called k-beautiful, if the digit sum of the decimal representation of this number is
divisible by k † . For example, 9272 is 5-beautiful, since the digit sum of 9272 is 9 + 2 + 7 + 2 = 20.
You are given two integers x and k. Please find the smallest integer y ≥ x which is k-beautiful.
† An integer n is divisible by k if there exists an integer m such that n = k · m.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int f(int x) {
5 return x ? f(x / 10) + x % 10 : 0;
6 }
7 void solve() {
8 int x, k;
9 cin >> x >> k;
10 while (f(x) % k != 0) {
11 x++;
12 }
13 cout << x << "\n";
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
Back to top 90
Coding with Jiangly 2023-12-31
One day, Ahmed_Hossam went to Hemose and said “Let’s solve a gym contest!”. Hemose didn’t want
to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract
him. Sadly, Ahmed can’t solve it. . . Could you help him?
There is an Agent in Valorant, and he has n weapons. The i-th weapon has a damage value ai , and the
Agent will face an enemy whose health value is H.
The Agent will perform one or more moves until the enemy dies.
In one move, he will choose a weapon and decrease the enemy’s health by its damage value. The
enemy will die when his health will become less than or equal to 0. However, not everything is so easy:
the Agent can’t choose the same weapon for 2 times in a row.
What is the minimum number of times that the Agent will need to use the weapons to kill the enemy?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, H;
6 cin >> n >> H;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 nth_element(a.begin(), a.begin() + 1, a.end(), greater());
12 int ans = H / (a[0] + a[1]) * 2;
13 H %= a[0] + a[1];
14 if (H > 0) {
15 ans += 1;
16 }
17 if (H > a[0]) {
18 ans += 1;
19 }
20 cout << ans << "\n";
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
Back to top 91
Coding with Jiangly 2023-12-31
30 return 0;
31 }
Theofanis has a string s1 s2 . . . sn and a character c. He wants to make all characters of the string equal
to c using the minimum number of operations.
In one operation he can choose a number x (1 ≤ x ≤ n) and for every position i, where i is not divisible
by x, replace si with c.
Find the minimum number of operations required to make all the characters equal to c and the x-s
that he should use in his operations.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 char c;
8 cin >> c;
9 string s;
10 cin >> s;
11 if (s == string(n, c)) {
12 cout << 0 << "\n";
13 return;
14 }
15 for (int i = 1; i <= n; i++) {
16 bool ok = true;
17 for (int j = i; j <= n; j += i) {
18 if (s[j - 1] != c) {
19 ok = false;
20 }
21 }
22 if (ok) {
23 cout << 1 << "\n";
24 cout << i << "\n";
25 return;
26 }
27 }
28 cout << 2 << "\n";
29 cout << n - 1 << " " << n << "\n";
30 }
31 int main() {
Back to top 92
Coding with Jiangly 2023-12-31
32 ios::sync_with_stdio(false);
33 cin.tie(nullptr);
34 int t;
35 cin >> t;
36 while (t--) {
37 solve();
38 }
39 return 0;
40 }
Pak Chanek is the chief of a village named Khuntien. On one night filled with lights, Pak Chanek has a
sudden and important announcement that needs to be notified to all of the n residents in Khuntien.
First, Pak Chanek shares the announcement directly to one or more residents with a cost of p for
each person. After that, the residents can share the announcement to other residents using a magical
helmet-shaped device. However, there is a cost for using the helmet-shaped device. For each i, if the
i-th resident has got the announcement at least once (either directly from Pak Chanek or from another
resident), he/she can share the announcement to at most ai other residents with a cost of bi for each
share.
If Pak Chanek can also control how the residents share the announcement to other residents, what is
the minimum cost for Pak Chanek to notify all n residents of Khuntien about the announcement?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, p;
6 cin >> n >> p;
7 vector<int> a(n), b(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 0; i < n; i++) {
12 cin >> b[i];
13 }
14 vector<int> ord(n);
15 iota(ord.begin(), ord.end(), 0);
16 sort(ord.begin(), ord.end(),
17 [&](int i, int j) {
18 return b[i] < b[j];
Back to top 93
Coding with Jiangly 2023-12-31
19 });
20 i64 ans = p;
21 int k = n - 1;
22 for (auto i : ord) {
23 while (k > 0 && a[i] > 0) {
24 a[i]--, k--;
25 ans += min(p, b[i]);
26 }
27 }
28 cout << ans << "\n";
29 }
30 int main() {
31 ios::sync_with_stdio(false);
32 cin.tie(nullptr);
33 int t;
34 cin >> t;
35 while (t--) {
36 solve();
37 }
38 return 0;
39 }
We define an integer to be the most common on a subsegment, if its number of occurrences on that
subsegment is larger than the number of occurrences of any other integer in that subsegment. A
subsegment of an array is a consecutive segment of elements in the array a.
Given an array a of size n, and an integer k, determine if there exists a non-empty subsegment of a
where k is the most common element.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 if (find(a.begin(), a.end(), k) != a.end()) {
12 cout << "YES\n";
13 } else {
14 cout << "NO\n";
15 }
Back to top 94
Coding with Jiangly 2023-12-31
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
implementation
61: 2023
In a sequence a, whose product was equal to 2023, k numbers were removed, leaving a sequence b of
length n. Given the resulting sequence b, find any suitable sequence a and output which k elements
were removed from it, or state that such a sequence could not have existed.
Notice that you are not guaranteed that such array exists.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 int res = 2023;
8 vector<int> b(n);
9 for (int i = 0; i < n; i++) {
10 cin >> b[i];
11 }
12 for (int i = 0; i < n; i++) {
13 if (res % b[i]) {
14 cout << "NO\n";
15 return;
16 }
17 res /= b[i];
18 }
19 cout << "YES\n";
20 for (int i = 0; i < k; i++) {
21 cout << (i == 0 ? res : 1) << " \n"[i == k - 1];
Back to top 95
Coding with Jiangly 2023-12-31
22 }
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
Calin has n buckets, the i-th of which contains ai wooden squares of side length 1.
Can Calin build a square using all the given squares?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 i64 s = 0;
8 for (int i = 0; i < n; i++) {
9 int a;
10 cin >> a;
11 s += a;
12 }
13 i64 res = sqrt(s);
14 if (res * res == s) {
15 cout << "YES\n";
16 } else {
17 cout << "NO\n";
18 }
19 }
20 int main() {
21 ios::sync_with_stdio(false);
22 cin.tie(nullptr);
23 int t;
24 cin >> t;
25 while (t--) {
26 solve();
27 }
28 return 0;
29 }
Back to top 96
Coding with Jiangly 2023-12-31
You are given three digits a, b, c. Two of them are equal, but the third one is different from the other
two.
Back to top 97
Coding with Jiangly 2023-12-31
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 cout << (a ^ b ^ c) << "\n";
8 }
9 int main() {
10 ios::sync_with_stdio(false);
11 cin.tie(nullptr);
12 int t;
13 cin >> t;
14 while (t--) {
15 solve();
16 }
17 return 0;
18 }
You are located at the point (0, 0) of an infinite Cartesian plane. You have a controller with 4 buttons
which can perform one of the following operations:
Unfortunately, the controller is broken. If you press all the 4 buttons (in any order), the controller
stops working. It means that, during the whole trip, you can only press at most 3 distinct buttons (any
number of times, in any order).
There are n special points in the plane, with integer coordinates (xi , yi ).
Can you visit all the special points (in any order) without breaking the controller?
Problem: link
Back to top 98
Coding with Jiangly 2023-12-31
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 array<bool, 4> req{};
6 int n;
7 cin >> n;
8 while (n--) {
9 int x, y;
10 cin >> x >> y;
11 if (x > 0) {
12 req[0] = true;
13 }
14 if (x < 0) {
15 req[1] = true;
16 }
17 if (y > 0) {
18 req[2] = true;
19 }
20 if (y < 0) {
21 req[3] = true;
22 }
23 }
24 if (count(req.begin(), req.end(), true) == 4) {
25 cout << "NO\n";
26 } else {
27 cout << "YES\n";
28 }
29 }
30 int main() {
31 ios::sync_with_stdio(false);
32 cin.tie(nullptr);
33 int t;
34 cin >> t;
35 while (t--) {
36 solve();
37 }
38 return 0;
39 }
Monocarp is participating in a programming contest, which features 26 problems, named from ‘A’ to ‘Z’.
The problems are sorted by difficulty. Moreover, it’s known that Monocarp can solve problem ‘A’ in 1
minute, problem ‘B’ in 2 minutes, . . . , problem ‘Z’ in 26 minutes.
After the contest, you discovered his contest log - a string, consisting of uppercase Latin letters, such
that the i-th letter tells which problem Monocarp was solving during the i-th minute of the contest. If
Back to top 99
Coding with Jiangly 2023-12-31
Monocarp had spent enough time in total on a problem to solve it, he solved it. Note that Monocarp
could have been thinking about a problem after solving it.
Given Monocarp’s contest log, calculate the number of problems he solved during the contest.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 array<int, 26> cnt{};
10 for (auto c : s) {
11 cnt[c - 'A'] += 1;
12 }
13 int ans = 0;
14 for (int i = 0; i < 26; i++) {
15 ans += (cnt[i] > i);
16 }
17 cout << ans << "\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
Monocarp knew that, before the round, his rating was a. After the round, it increased to b (b > a). He
wrote both values one after another to not forget them.
However, he wrote them so close to each other, that he can’t tell now where the first value ends and
the second value starts.
b > a;
they produce the given value ab when written one after another.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 for (int i = 1; i < s.size(); i++) {
8 string a = s.substr(0, i);
9 string b = s.substr(i);
10 if (b[0] != '0' && stoi(b) > stoi(a)) {
11 cout << a << " " << b << "\n";
12 return;
13 }
14 }
15 cout << -1 << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
68: YetnotherrokenKeoard
Now, when he presses the ‘b’ key, it acts like an unusual backspace: it deletes the last (rightmost)
lowercase letter in the typed string. If there are no lowercase letters in the typed string, then the press
is completely ignored.
Similarly, when he presses the ‘B’ key, it deletes the last (rightmost) uppercase letter in the typed string.
If there are no uppercase letters in the typed string, then the press is completely ignored.
In both cases, the letters ‘b’ and ‘B’ are not added to the typed string when these keys are pressed.
Consider an example where the sequence of key presses was “ARaBbbitBaby”. In this case, the typed
A R a B b b i t B a
string will change as follows: “” −
→ “A” −
→ “AR” −
→ “ARa” −
→ “Aa” −
→ “A” −
→ “A” −
→ “Ai” −
→ “Ait” −
→ “it” −
→
b y
“ita” −
→ “it” −→ “ity”.
Given a sequence of pressed keys, output the typed string after processing all key presses.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 vector<int> u, l;
8 for (int i = 0; i < s.size(); i++) {
9 if (s[i] == 'B') {
10 if (!u.empty()) {
11 u.pop_back();
12 }
13 } else if (s[i] == 'b') {
14 if (!l.empty()) {
15 l.pop_back();
16 }
17 } else if (isupper(s[i])) {
18 u.push_back(i);
19 } else {
20 l.push_back(i);
21 }
22 }
23 int i = 0, j = 0;
24 while (i < u.size() || j < l.size()) {
25 if (i < u.size() && (j == l.size() || u[i] < l[j])) {
26 cout << s[u[i++]];
27 } else {
28 cout << s[l[j++]];
29 }
30 }
31 cout << "\n";
32 }
33 int main() {
34 ios::sync_with_stdio(false);
35 cin.tie(nullptr);
36 int t;
37 cin >> t;
38 while (t--) {
39 solve();
40 }
41 return 0;
42 }
69: Rook
As you probably know, chess is a game that is played on a board with 64 squares arranged in an 8 × 8
grid. Columns of this board are labeled with letters from a to h, and rows are labeled with digits from 1
to 8. Each square is described by the row and column it belongs to.
The rook is a piece in the game of chess. During its turn, it may move any non-zero number of squares
horizontally or vertically. Your task is to find all possible moves for a rook on an empty chessboard.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 for (char x = 'a'; x <= 'h'; x++) {
8 for (char y = '1'; y <= '8'; y++) {
9 if ((x == s[0]) ^ (y == s[1])) {
10 cout << x << y << "\n";
11 }
12 }
13 }
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
Alex is participating in the filming of another video of BrMeast, and BrMeast asked Alex to prepare 250
thousand tons of TNT, but Alex didn’t hear him well, so he prepared n boxes and arranged them in a
row waiting for trucks. The i-th box from the left weighs ai tons.
All trucks that Alex is going to use hold the same number of boxes, denoted by k. Loading happens the
following way:
···
Upon loading is completed, each truck must have exactly k boxes. In other words, if at some point it is
not possible to load exactly k boxes into the truck, then the loading option with that k is not possible.
Alex hates justice, so he wants the maximum absolute difference between the total weights of two
trucks to be as great as possible. If there is only one truck, this value is 0.
Alex has quite a lot of connections, so for every 1 ≤ k ≤ n, he can find a company such that each of its
trucks can hold exactly k boxes. Print the maximum absolute difference between the total weights of
any two trucks.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 vector<i64> s(n + 1);
9 for (int i = 0; i < n; i++) {
10 cin >> a[i];
11 }
12 for (int i = 0; i < n; i++) {
13 s[i + 1] = s[i] + a[i];
14 }
15 i64 ans = 0;
16 for (int k = 1; k <= n; k++) {
17 if (n % k == 0) {
18 i64 mx = 0, mn = s[n];
19 for (int i = 0; i < n; i += k) {
20 i64 v = s[i + k] - s[i];
21 mx = max(mx, v);
22 mn = min(mn, v);
23 }
24 ans = max(ans, mx - mn);
25 }
26 }
27 cout << ans << "\n";
28 }
29 int main() {
30 ios::sync_with_stdio(false);
31 cin.tie(nullptr);
32 int t;
33 cin >> t;
34 while (t--) {
35 solve();
36 }
37 return 0;
38 }
Milica has a string s of length n, consisting only of characters A and B. She wants to modify s so it
contains exactly k instances of B. In one operation, she can do the following:
Then, replace each of the first i characters of string s (that is, characters s1 , s2 , . . . , si ) with c.
Milica does not want to perform too many operations in order not to waste too much time on them.
She asks you to find the minimum number of operations required to modify s so it contains exactly k
instances of B. She also wants you to find these operations (that is, integer i and character c selected in
each operation).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
Kristina has a matrix of size n by n, filled with lowercase Latin letters. The value of n is even.
She wants to change some characters so that her matrix becomes a perfect square. A matrix is called a
perfect square if it remains unchanged when rotated 90◦ clockwise once.
In one operation, Kristina can choose any cell and replace its value with the next character in the
alphabet. If the character is equal to “z”, its value does not change.
Find the minimum number of operations required to make the matrix a perfect square.
a b b a
b c b b
b c c b
a b b a
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<string> s(n);
8 for (int i = 0; i < n; i++) {
9 cin >> s[i];
10 }
11 int ans = 0;
12 for (int i = 0; i < n / 2; i++) {
13 for (int j = 0; j < n / 2; j++) {
14 int sum = s[i][j] + s[j][n - 1 - i] + s[n - 1 - i][n - 1 - j] + s[n - 1 - j][i
];
15 int max = max({s[i][j], s[j][n - 1 - i], s[n - 1 - i][n - 1 - j], s[n - 1 - j
][i]});
16 ans += max * 4 - sum;
17 }
18 }
19 cout << ans << "\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
73: 1D Eraser
You are given a strip of paper s that is n cells long. Each cell is either black or white. In an operation
you can take any k consecutive cells and make them all white.
Find the minimum number of operations needed to remove all black cells.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 string s;
8 cin >> s;
9 int ans = 0;
10 int t = -1;
11 for (int i = 0; i < n; i++) {
12 if (s[i] == 'B' && i > t) {
13 ans++;
14 t = i + k - 1;
15 }
16 }
17 cout << ans << "\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
A 10×10 target is made out of five “rings” as shown. Each ring has a different point value: the outermost
ring - 1 point, the next ring - 2 points, . . . , the center ring - 5 points.
Vlad fired several arrows at the target. Help him determine how many points he got.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int ans = 0;
6 for (int i = 0; i < 10; i++) {
7 for (int j = 0; j < 10; j++) {
8 char c;
9 cin >> c;
10 if (c == 'X') {
11 ans += min({i + 1, 10 - i, j + 1, 10 - j});
12 }
13 }
14 }
15 cout << ans << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
There are three cards with letters a, b, c placed in a row in some order. You can do the following
operation at most once:
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 if (s == "abc" || s == "acb" || s == "bac" || s == "cba") {
8 cout << "YES\n";
9 } else {
10 cout << "NO\n";
11 }
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
Black is gifted with a Divine array a consisting of n (1 ≤ n ≤ 2000) integers. Each position in a has
an initial value. After shouting a curse over the array, it becomes angry and starts an unstoppable
transformation.
The transformation consists of infinite steps. Array a changes at the i-th step in the following way: for
every position j, aj becomes equal to the number of occurrences of aj in a before starting this step.
In the initial array, we had two 2-s, three 1-s, only one 4 and only one 3, so after the first step, each
element became equal to the number of its occurrences in the initial array: all twos changed to 2, all
ones changed to 3, four changed to 1 and three changed to 1.
You have to process q queries: in each query, Black is curious to know the value of ax after the k-th
step of transformation.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int q;
12 cin >> q;
13 vector<int> ans(q);
14 vector<array<int, 3>> qry(q);
15 for (int i = 0; i < q; i++) {
16 int x, k;
17 cin >> x >> k;
18 x--;
19 k = min(k, 20);
20 qry[i] = {k, x, i};
21 }
22 sort(qry.begin(), qry.end());
23 int cur = 0;
24 for (auto [k, x, i] : qry) {
25 while (cur < k) {
26 vector<int> cnt(n + 1);
27 for (auto x : a) {
28 cnt[x]++;
29 }
30 for (auto &x : a) {
31 x = cnt[x];
32 }
33 cur++;
34 }
35 ans[i] = a[x];
36 }
37 for (int i = 0; i < q; i++) {
38 cout << ans[i] << "\n";
39 }
40 }
41 int main() {
42 ios::sync_with_stdio(false);
43 cin.tie(nullptr);
44 int t;
45 cin >> t;
46 while (t--) {
47 solve();
48 }
49 return 0;
50 }
You are given a string s. You need to find two non-empty strings a and b such that the following
conditions are satisfied:
For each index i, character si of string s must belong to exactly one of strings a or b.
Reminder:
A string a (b) is a subsequence of a string s if a (b) can be obtained from s by deletion of several (possibly,
zero) elements. For example, “dores”, “cf”, and “for” are subsequences of “codeforces”, while “decor”
and “fork” are not.
A string x is lexicographically smaller than a string y if and only if one of the following holds:
x is a prefix of y, but x ̸= y;
in the first position where x and y differ, the string x has a letter that appears earlier in the alphabet
than the corresponding letter in y.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 int x = min_element(s.begin(), s.end()) - s.begin();
8 cout << s[x] << " " << s.substr(0, x) + s.substr(x + 1) << "\n";
9 }
10 int main() {
11 ios::sync_with_stdio(false);
12 cin.tie(nullptr);
13 int t;
14 cin >> t;
15 while (t--) {
16 solve();
17 }
18 return 0;
19 }
You are in a corridor that extends infinitely to the right, divided into square rooms. You start in room 1,
proceed to room k, and then return to room 1. You can choose the value of k. Moving to an adjacent
room takes 1 second.
Additionally, there are n traps in the corridor: the i-th trap is located in room di and will be activated si
seconds after you enter the room di . Once a trap is activated, you cannot enter or exit a room with that
trap.
Determine the maximum value of k that allows you to travel from room 1 to room k and then return to
room 1 safely.
For instance, if n = 1 and d1 = 2, s1 = 2, you can proceed to room k = 2 and return safely (the trap
will activate at the moment 1 + s1 = 1 + 2 = 3, it can’t prevent you to return back). But if you attempt
to reach room k = 3, the trap will activate at the moment 1 + s1 = 1 + 2 = 3, preventing your return
(you would attempt to enter room 2 on your way back at second 3, but the activated trap would block
you). Any larger value for k is also not feasible. Thus, the answer is k = 2.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int ans = 1E9;
8 for (int i = 0; i < n; i++) {
9 int d, s;
10 cin >> d >> s;
11 ans = min(ans, d + (s - 1) / 2);
12 }
13 cout << ans << "\n";
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
Petya has got an interesting flower. Petya is a busy person, so he sometimes forgets to water it. You are
given n days from Petya’s live and you have to determine what happened with his flower in the end.
If the flower is watered in the i-th and in the (i − 1)-th day (i > 1), then it grows by 5 centimeters
instead of 1.
If the flower is not watered in the i-th day, it does not grow.
At the beginning of the 1-st day the flower is 1 centimeter tall. What is its height after n days?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int ans = 1;
12 for (int i = 0; i < n; i++) {
13 if (a[i]) {
14 if (i && a[i - 1]) {
15 ans += 5;
16 } else {
17 ans += 1;
18 }
19 } else if (i && !a[i - 1]) {
20 ans = -1;
21 break;
22 }
23 }
24 cout << ans << "\n";
25 }
26 int main() {
27 ios::sync_with_stdio(false);
28 cin.tie(nullptr);
29 int t;
30 cin >> t;
31 while (t--) {
32 solve();
33 }
34 return 0;
35 }
80: Game
You are playing a very popular computer game. The next level consists of n consecutive locations,
numbered from 1 to n, each of them containing either land or water. It is known that the first and last
locations contain land, and for completing the level you have to move from the first location to the last.
Also, if you become inside a location with water, you will die, so you can only move between locations
with land.
You can jump between adjacent locations for free, as well as no more than once jump from any location
with land i to any location with land i + x, spending x coins (x ≥ 0).
Your task is to spend the minimum possible number of coins to move from the first location to the last
one.
Note that this is always possible since both the first and last locations are the land locations.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int l = 0, r = n - 1;
12 while (l < r && a[l + 1] == 1) {
13 l++;
14 }
15 while (r > l && a[r - 1] == 1) {
16 r--;
17 }
18 int ans = r - l;
19 cout << ans << "\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
math
A certain number 1 ≤ x ≤ 109 is chosen. You are given two integers a and b, which are the two largest
divisors of the number x. At the same time, the condition 1 ≤ a < b < x is satisfied.
For the given numbers a, b, you need to find the value of x.
† The number y is a divisor of the number x if there is an integer k such that x = y · k.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b;
6 cin >> a >> b;
7 if (b % a == 0) {
8 cout << b / a * b << "\n";
9 } else {
10 cout << lcm(a, b) << "\n";
11 }
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
You are given an array of integers a1 , a2 , . . . , an . You can perform the following operation any number
of times (possibly zero):
Choose any element ai from the array and change its value to any integer between 0 and ai (inclusive).
More formally, if ai < 0, replace ai with any integer in [ai , 0], otherwise replace ai with any integer in
[0, ai ].
Let r be the minimum possible product of all the ai after performing the operation any number of
times.
Find the minimum number of operations required to make the product equal to r. Also, print one such
shortest sequence of operations. If there are multiple answers, you can print any of them.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 int sgn = 1;
9 for (int i = 0; i < n; i++) {
10 cin >> a[i];
11 if (a[i] < 0) {
12 sgn *= -1;
13 } else if (a[i] == 0) {
14 sgn = 0;
15 }
16 }
17 if (sgn <= 0) {
18 cout << 0 << "\n";
19 return;
20 }
21 cout << 1 << "\n";
22 cout << 1 << " " << 0 << "\n";
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
You are given an array a1 , a2 , . . . , an of distinct positive integers. You have to do the following operation
exactly once:
Find a value of k such that 1 ≤ k ≤ 1018 and the array a1 , a2 , . . . , an contains exactly 2 distinct values
at the end of the operation. It can be shown that, under the constraints of the problem, at least one
such k always exists. If there are multiple solutions, you can print any of them.
† a mod b denotes the remainder after dividing a by b. For example:
7 mod 3 = 1 since 7 = 3 · 2 + 1
15 mod 4 = 3 since 15 = 4 · 3 + 3
21 mod 1 = 0 since 21 = 21 · 1 + 0
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<i64> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 i64 k = 1;
12 while (true) {
13 for (int i = 0; i < n; i++) {
14 if (a[i] % k != a[0] % k) {
15 cout << k << "\n";
16 return;
17 }
18 }
19 k *= 2;
20 }
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
30 return 0;
31 }
Monocarp is practicing for a big contest. He plans to solve n problems to make sure he’s prepared.
Each of these problems has a difficulty level: the first problem has a difficulty level of 1, the second
problem has a difficulty level of 2, and so on, until the last (n-th) problem, which has a difficulty level
of n.
Monocarp will choose some order in which he is going to solve all n problems. Whenever he solves a
problem which is more difficult than the last problem he solved, he gets excited because he feels like
he’s progressing. He doesn’t get excited when he solves the first problem in his chosen order.
For example, if Monocarp solves the problems in the order [3, 5, 4, 1, 6, 2], he gets excited twice (the
corresponding problems are underlined).
Monocarp wants to get excited exactly k times during his practicing session. Help him to choose the
order in which he has to solve the problems!
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 for (int i = n - k; i <= n; i++) {
8 cout << i << " ";
9 }
10 for (int i = n - k - 1; i > 0; i--) {
11 cout << i << " ";
12 }
13 cout << "\n";
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
Gridlandia has been hit by flooding and now has to reconstruct all of it’s cities. Gridlandia can be
described by an n × m matrix.
Initially, all of its cities are in economic collapse. The government can choose to rebuild certain cities.
Additionally, any collapsed city which has at least one vertically neighboring rebuilt city and at least
one horizontally neighboring rebuilt city can ask for aid from them and become rebuilt without help
from the government. More formally, collapsed city positioned in (i, j) can become rebuilt if both of
the following conditions are satisfied:
If the city is located on the border of the matrix and has only one horizontally or vertically neighbouring
city, then we consider only that city.
The government wants to know the minimum number of cities it has to rebuild such that after some
time all the cities can be rebuild.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 int ans = max(n, m);
8 cout << ans << "\n";
9 }
10 int main() {
11 ios::sync_with_stdio(false);
12 cin.tie(nullptr);
13 int t;
14 cin >> t;
15 while (t--) {
16 solve();
17 }
18 return 0;
19 }
Laura is a girl who does not like combinatorics. Nemanja will try to convince her otherwise.
Nemanja wrote some digits on the board. All of them are either 1, 2, or 3. The number of digits 1 is a.
The number of digits 2 is b and the number of digits 3 is c. He told Laura that in one operation she can
do the following:
Select two different digits and erase them from the board. After that, write the digit (1, 2, or 3) different
from both erased digits.
For example, let the digits be 1, 1, 1, 2, 3, 3. She can choose digits 1 and 3 and erase them. Then
the board will look like this 1, 1, 2, 3. After that, she has to write another digit 2, so at the end of the
operation, the board will look like 1, 1, 2, 3, 2.
Nemanja asked her whether it was possible for only digits of one type to remain written on the board
after some operations. If so, which digits can they be?
Laura was unable to solve this problem and asked you for help. As an award for helping her, she will
convince Nemanja to give you some points.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 cout << (b + c + 1) % 2 << " " << (c + a + 1) % 2 << " " << (a + b + 1) % 2 << "\n";
8 }
9 int main() {
10 ios::sync_with_stdio(false);
11 cin.tie(nullptr);
12 int t;
13 cin >> t;
14 while (t--) {
15 solve();
16 }
17 return 0;
18 }
Vanya and Vova are playing a game. Players are given an integer n. On their turn, the player can add
1 to the current integer or subtract 1. The players take turns; Vanya starts. If after Vanya’s move the
integer is divisible by 3, then he wins. If 10 moves have passed and Vanya has not won, then Vova
wins.
Write a program that, based on the integer n, determines who will win if both players play optimally.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 if (n % 3 != 0) {
8 cout << "First\n";
9 } else {
10 cout << "Second\n";
11 }
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
Monocarp has found a treasure map. The map represents the treasure location as an OX axis. Monocarp
is at 0, the treasure chest is at x, the key to the chest is at y.
Obviously, Monocarp wants to open the chest. He can perform the following actions:
pick the key or the chest up if he is in the same point as that object (spending 0 seconds);
open the chest if he’s in the same point as the chest and has picked the key up (spending 0 seconds).
Monocarp can carry the chest, but the chest is pretty heavy. He knows that he can carry it for at most k
seconds in total (putting it down and picking it back up doesn’t reset his stamina).
What’s the smallest time required for Monocarp to open the chest?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int x, y, k;
6 cin >> x >> y >> k;
7 int ans;
8 if (x > y) {
9 ans = x;
10 } else {
11 ans = y + max(0, y - x - k);
12 }
13 cout << ans << "\n";
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
89: Deja Vu
You are given an array a of length n, consisting of positive integers, and an array x of length q, also
consisting of positive integers.
There are q modification. On the i-th modification (1 ≤ i ≤ q), for each j (1 ≤ j ≤ n), such that aj
is divisible by 2xi , you add 2xi −1 to aj . Note that xi (1 ≤ xi ≤ 30) is a positive integer not exceeding
30.
After all modification queries, you need to output the final array.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, q;
6 cin >> n >> q;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 array<int, 30> f{};
12 for (int i = 0; i < 30; i++) {
13 f[i] = 1 << i;
14 }
15 while (q--) {
16 int x;
17 cin >> x;
18 for (int i = 0; i < 30; i++) {
19 if ((f[i] & ((1 << x) - 1)) == 0) {
20 f[i] += 1 << (x - 1);
21 }
22 }
23 }
24 for (int i = 0; i < n; i++) {
25 int k = __builtin_ctz(a[i]);
26 a[i] += f[k] - (1 << k);
27 cout << a[i] << " \n"[i == n - 1];
28 }
29 }
30 int main() {
31 ios::sync_with_stdio(false);
32 cin.tie(nullptr);
33 int t;
34 cin >> t;
35 while (t--) {
36 solve();
37 }
38 return 0;
39 }
Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As
you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go
to all discount markets in Germany.
Hemose has an array of n integers. He wants Samez to sort the array in the non-decreasing order. Since
it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:
Choose indices i and j such that 1 ≤ i, j ≤ n, and |i − j| ≥ x. Then, swap elements ai and aj .
Choose indices i and j such that 1 ≤ i, j ≤ n, and |i − j| ≥ x. Then, swap elements ai and aj .
Can you tell Samez if there’s a way to sort the array in the non-decreasing order by using the operation
written above some finite number of times (possibly 0)?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, x;
6 cin >> n >> x;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 if (n - x <= x - 1) {
12 int l = n - x, r = x;
13 rotate(a.begin() + l, a.begin() + r, a.end());
14 sort(a.begin(), a.end() - (r - l));
15 rotate(a.begin() + l, a.end() - (r - l), a.end());
16 if (is_sorted(a.begin(), a.end())) {
17 cout << "YES\n";
18 } else {
19 cout << "NO\n";
20 }
21 } else {
22 cout << "YES\n";
23 }
24 }
25 int main() {
26 ios::sync_with_stdio(false);
27 cin.tie(nullptr);
28 int t;
29 cin >> t;
30 while (t--) {
31 solve();
32 }
33 return 0;
34 }
Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem
about a sequence that consists of only special numbers.
Let’s call a positive number special if it can be written as a sum of different non-negative powers of n.
For example, for n = 4 number 17 is special, because it can be written as 40 + 42 = 1 + 16 = 17, but 9
is not.
Theofanis asks you to help him find the k-th special number if they are sorted in increasing order. Since
this number may be too large, output it modulo 109 + 7.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 template<class T>
5 constexpr T power(T a, i64 b) {
6 T res = 1;
7 for (; b; b /= 2, a *= a) {
8 if (b % 2) {
9 res *= a;
10 }
11 }
12 return res;
13 }
14 constexpr i64 mul(i64 a, i64 b, i64 p) {
15 i64 res = a * b - i64(1.L * a * b / p) * p;
16 res %= p;
17 if (res < 0) {
18 res += p;
19 }
20 return res;
21 }
22 template<i64 P>
23 # struct MLong;
24 template<>
25 i64 MLong<0LL>::Mod = i64(1E18) + 9;
26 template<int P>
27 # struct MInt;
28 template<>
29 int MInt<0>::Mod = 998244353;
30 template<int V, int P>
31 constexpr MInt<P> CInv = MInt<P>(V).inv();
32 constexpr int P = 1000000007;
33 using Z = MInt<P>;
34 void solve() {
35 int n, k;
36 cin >> n >> k;
37 Z ans = 0;
38 Z p = 1;
39 for (int i = 0; i < 30; i++) {
40 if (k >> i & 1) {
41 ans += p;
42 }
43 p *= n;
44 }
45 cout << ans << "\n";
46 }
47 int main() {
48 ios::sync_with_stdio(false);
49 cin.tie(nullptr);
50 int t;
51 cin >> t;
52 while (t--) {
53 solve();
54 }
55 return 0;
56 }
Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi
for free (Cypriot cheese).
You are given an integer n. You need to find two integers l and r such that −1018 ≤ l < r ≤ 1018 and
l + (l + 1) + . . . + (r − 1) + r = n.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 i64 n;
6 cin >> n;
7 cout << -n + 1 << " " << n << "\n";
8 }
9 int main() {
10 ios::sync_with_stdio(false);
11 cin.tie(nullptr);
12 int t;
13 cin >> t;
14 while (t--) {
15 solve();
16 }
17 return 0;
18 }
Once upon a time, bartender Decim found three threadlets and a pair of scissors.
In one operation, Decim chooses any threadlet and cuts it into two threadlets, whose lengths are
positive integers and their sum is equal to the length of the threadlet being cut.
For example, he can cut a threadlet of length 5 into threadlets of lengths 2 and 3, but he cannot cut it
into threadlets of lengths 2.5 and 2.5, or lengths 0 and 5, or lengths 3 and 4.
Decim can perform at most three operations. He is allowed to cut the threadlets obtained from previous
cuts. Will he be able to make all the threadlets of equal length?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 for (auto x : {a, a / 2, a / 3, a / 4}) {
8 if (x == 0) {
9 continue;
10 }
11 bool ok = true;
12 int cnt = 0;
13 for (auto y : {a, b, c}) {
14 if (y % x != 0) {
15 ok = false;
16 break;
17 }
18 cnt += y / x - 1;
19 }
20 if (ok && cnt <= 3) {
21 cout << "YES\n";
22 return;
23 }
24 }
25 cout << "NO\n";
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
Monocarp tries to get home from work. He is currently at the point O = (0, 0) of a two-dimensional
plane; his house is at the point P = (Px , Py ).
Unfortunately, it is late in the evening, so it is very dark. Monocarp is afraid of the darkness. He would
like to go home along a path illuminated by something.
Thankfully, there are two lanterns, located in the points A = (Ax , Ay ) and B = (Bx , By ). You can
choose any non-negative number w and set the power of both lanterns to w. If a lantern’s power is set
to w, it illuminates a circle of radius w centered at the lantern location (including the borders of the
circle).
You have to choose the minimum non-negative value w for the power of the lanterns in such a way
that there is a path from the point O to the point P which is completely illuminated. You may assume
that the lanterns don’t interfere with Monocarp’s movement.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
He wants to represent his number as a sum of three distinct positive integers x, y, and z. Additionally,
Monocarp wants none of the numbers x, y, and z to be divisible by 3.
Your task is to help Monocarp to find any valid triplet of distinct positive integers x, y, and z, or report
that such a triplet does not exist.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 for (int x = 1; x <= 10; x++) {
8 for (int y = x + 1; y <= 10; y++) {
9 int z = n - x - y;
10 if (x % 3 != 0 && y % 3 != 0 && z % 3 != 0 && z > y) {
11 cout << "YES\n";
12 cout << x << " " << y << " " << z << "\n";
13 return;
14 }
15 }
16 }
17 cout << "NO\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
96: Joyboard
Chaneka, a gamer kid, invented a new gaming controller called joyboard. Interestingly, the joyboard
she invented can only be used to play one game.
The joyboard has a screen containing n + 1 slots numbered from 1 to n + 1 from left to right. The n + 1
slots are going to be filled with an array of non-negative integers [a1 , a2 , a3 , . . . , an+1 ]. Chaneka, as
the player, must assign an+1 with an integer between 0 and m inclusive. Then, for each i from n to 1,
the value of ai will be equal to the remainder of dividing ai+1 (the adjacent value to the right) by i. In
other words, ai = ai+1 mod i.
Chaneka wants it such that after every slot is assigned with an integer, there are exactly k distinct
values in the entire screen (among all n + 1 slots). How many valid ways are there for assigning a
non-negative integer into slot n + 1?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m, k;
6 cin >> n >> m >> k;
7 if (k == 1) {
8 cout << 1 << "\n";
9 } else if (k == 2) {
10 cout << min(m, n - 1) + m / n << "\n";
11 } else if (k == 3) {
12 cout << m - min(m, n - 1) - m / n << "\n";
13 } else {
14 cout << 0 << "\n";
15 }
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
There are n teams in a football tournament. Each pair of teams match up once. After every match,
Pak Chanek receives two integers as the result of the match, the number of goals the two teams score
during the match. The efficiency of a team is equal to the total number of goals the team scores in each
of its matches minus the total number of goals scored by the opponent in each of its matches.
After the tournament ends, Pak Dengklek counts the efficiency of every team. Turns out that he forgot
about the efficiency of one of the teams. Given the efficiency of n − 1 teams a1 , a2 , a3 , . . . , an−1 . What
is the efficiency of the missing team? It can be shown that the efficiency of the missing team can be
uniquely determined.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int ans = 0;
8 for (int i = 0; i < n - 1; i++) {
9 int x;
10 cin >> x;
11 ans -= x;
12 }
13 cout << ans << "\n";
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
Aca and Milovan, two fellow competitive programmers, decided to give Vasilije a problem to test his
skills.
Vasilije is given three positive integers: n, k, and x, and he has to determine if he can choose k distinct
integers between 1 and n, such that their sum is equal to x.
Since Vasilije is now in the weirdest city in Serbia where Aca and Milovan live, Cacak, the problem
seems weird to him. So he needs your help with this problem.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 i64 x;
7 cin >> n >> k >> x;
8 if (x >= 1LL * k * (k + 1) / 2 && x <= 1LL * k * (n + n - k + 1) / 2) {
9 cout << "YES\n";
10 } else {
11 cout << "NO\n";
12 }
13 }
14 int main() {
15 ios::sync_with_stdio(false);
16 cin.tie(nullptr);
17 int t;
18 cin >> t;
19 while (t--) {
20 solve();
21 }
22 return 0;
23 }
After the Serbian Informatics Olympiad, Aleksa was very sad, because he didn’t win a medal (he didn’t
know stack), so Vasilije came to give him an easy problem, just to make his day better.
Vasilije gave Aleksa a positive integer n (n ≥ 3) and asked him to construct a strictly increasing array of
size n of positive integers, such that
Since Aleksa thinks he is a bad programmer now, he asked you to help him find such an array.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 for (int i = 0; i < n; i++) {
8 cout << int(5E8) + i << " \n"[i == n - 1];
9 }
10 }
11 int main() {
12 ios::sync_with_stdio(false);
13 cin.tie(nullptr);
14 int t;
15 cin >> t;
16 while (t--) {
17 solve();
18 }
19 return 0;
20 }
Slavic is preparing a present for a friend’s birthday. He has an array a of n digits and the present will be
the product of all these digits. Because Slavic is a good kid who wants to make the biggest product
possible, he wants to add 1 to exactly one of his digits.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 sort(a.begin(), a.end());
12 a[0]++;
13 int ans = 1;
14 for (int i = 0; i < n; i++) {
15 ans *= a[i];
16 }
17 cout << ans << "\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
misc
There are n food items lying in a row on a long table. Each of these items is either a loaf of bread
(denoted as a capital Latin letter ‘L’ with ASCII code 76) or an onion (denoted as a capital Latin letter ‘O’
with ASCII code 79). There is at least one loaf of bread and at least one onion on the table.
You and your friend want to divide the food on the table: you will take a prefix of this row (several
leftmost items), and the friend will take the rest. However, there are several restrictions:
The number of your loaves should differ from the number of your friend’s loaves.
The number of your onions should differ from the number of your friend’s onions.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 string s;
10 cin >> s;
11 vector<array<int, 2>> pre(n + 1);
12 for (int i = 0; i < n; i++) {
13 pre[i + 1] = pre[i];
14 if (s[i] == 'O') {
15 pre[i + 1][0] += 1;
16 } else {
17 pre[i + 1][1] += 1;
18 }
19 }
20 for (int i = 1; i < n; i++) {
21 if (pre[i][0] * 2 != pre[n][0] && pre[i][1] * 2 != pre[n][1]) {
22 cout << i << "\n";
23 return 0;
24 }
25 }
26 cout << -1 << "\n";
27 return 0;
28 }
You are given a binary string s (a string consisting only of 0-s and 1-s).
You can perform these operations any number of times and in any order.
Let’s name a string you’ve got after performing operations above as t. The string t is good if for each i
from 1 to |t| ti ̸= si (|t| is the length of the string t). The empty string is always good. Note that you are
comparing the resulting string t with the initial string s.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 array<int, 2> cnt{};
8 for (auto x : s) {
9 cnt[x - '0'] += 1;
10 }
11 int n = s.size();
12 int ans = n;
13 auto cur = cnt;
14 for (int i = n - 1; i >= 0; i--) {
15 if (cur[0] <= cnt[1] && cur[1] <= cnt[0]) {
16 ans = n - 1 - i;
17 break;
18 }
19 cur[s[i] - '0'] -= 1;
20 }
21 cout << ans << "\n";
22 }
23 int main() {
24 ios::sync_with_stdio(false);
25 cin.tie(nullptr);
26 int t;
27 cin >> t;
28 while (t--) {
29 solve();
30 }
31 return 0;
32 }
You are given a sequence a1 , a2 , . . . , an . A sequence b1 , b2 , . . . , bn is called good, if it satisfies all of the
following conditions:
bi ̸= ai for i = 1, 2, . . . , n;
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int x = 1;
8 for (int i = 0; i < n; i++) {
9 int a;
10 cin >> a;
11 if (x == a) {
12 x++;
13 }
14 x++;
15 }
16 cout << x - 1 << "\n";
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
104: Rigged!
Monocarp organizes a weightlifting competition. There are n athletes participating in the competition,
the i-th athlete has strength si and endurance ei . The 1-st athlete is Monocarp’s friend Polycarp, and
Monocarp really wants Polycarp to win.
The competition will be conducted as follows. The jury will choose a positive (greater than zero) integer
w, which denotes the weight of the barbell that will be used in the competition. The goal for each
athlete is to lift the barbell as many times as possible. The athlete who lifts the barbell the most amount
of times will be declared the winner (if there are multiple such athletes - there’s no winner).
If the barbell’s weight w is strictly greater than the strength of the i-th athlete si , then the i-th athlete
will be unable to lift the barbell even one single time. Otherwise, the i-th athlete will be able to lift the
barbell, and the number of times he does it will be equal to his endurance ei .
Monocarp wants to choose w in such a way that Polycarp (the 1-st athlete) wins the competition. Help
him to choose the value of w, or report that it is impossible.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> s(n), e(n);
8 bool ok = true;
9 for (int i = 0; i < n; i++) {
10 cin >> s[i] >> e[i];
11 if (i > 0 && s[i] >= s[0] && e[i] >= e[0]) {
12 ok = false;
13 }
14 }
15 cout << (ok ? s[0] : -1) << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
You are given two arrays of integers - a1 , . . . , an of length n, and b1 , . . . , bm of length m. You can choose
any element bj from array b (1 ≤ j ≤ m), and for all 1 ≤ i ≤ n perform ai = ai |bj . You can perform
any number of such operations.
After all the operations, the value of x = a1 ⊕ a2 ⊕ . . . ⊕ an will be calculated. Find the minimum and
maximum values of x that could be obtained after performing any set of operations.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int o = 0;
12 for (int i = 0; i < m; i++) {
13 int b;
14 cin >> b;
15 o |= b;
16 }
17 int x = 0, y = 0;
18 for (int i = 0; i < n; i++) {
19 x ^= a[i];
20 y ^= (a[i] | o);
21 }
22 if (x > y) {
23 swap(x, y);
24 }
Luntik came out for a morning stroll and found an array a of length n. He calculated the sum s of the
elements of the array (s = ni=1 ai ). Luntik calls a subsequence of the array a nearly full if the sum of
P
Luntik really wants to know the number of nearly full subsequences of the array a. But he needs to
come home so he asks you to solve that problem!
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int cnt[2] {};
8 for (int i = 0; i < n; i++) {
9 int a;
10 cin >> a;
11 if (a <= 1) {
12 cnt[a]++;
13 }
14 }
15 i64 ans = (1LL * cnt[1]) << cnt[0];
16 cout << ans << "\n";
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
Luntik has decided to try singing. He has a one-minute songs, b two-minute songs and c three-minute
songs. He wants to distribute all songs into two concerts such that every song should be included to
exactly one concert.
He wants to make the absolute difference of durations of the concerts as small as possible. The duration
of the concert is the sum of durations of all songs in that concert.
Please help Luntik and find the minimal possible difference in minutes between the concerts dura-
tions.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 if (c % 2 == 1 && a == 0 && b == 0) {
8 cout << 3 << "\n";
9 } else if ((c % 2 == 1 && a == 1 && b == 0) || (c % 2 == 0 && a == 0 && b == 1)) {
10 cout << 2 << "\n";
11 } else if ((a + c) % 2 == 1) {
12 cout << 1 << "\n";
13 } else {
14 cout << 0 << "\n";
15 }
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
109: Era
Shohag has an integer sequence a1 , a2 , . . . , an . He can perform the following operation any number of
times (possibly, zero):
Choose any position in the sequence (possibly the beginning or end of the sequence, or in between
any two elements) and insert k into the sequence at this position.
This way, the sequence a changes, and the next operation is performed on this changed sequence.
For example, if a = [3, 3, 4] and he selects k = 2, then after the operation he can obtain one of the
sequences [2, 3, 3, 4], [3, 2, 3, 4], [3, 3, 2, 4], or [3, 3, 4, 2].
Shohag wants this sequence to satisfy the following condition: for each 1 ≤ i ≤ |a|, ai ≤ i. Here, |a|
denotes the size of a.
Help him to find the minimum number of operations that he has to perform to achieve this goal. We
can show that under the constraints of the problem it’s always possible to achieve this goal in a finite
number of operations.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int ans = 0;
8 for (int i = 1; i <= n; i++) {
9 int a;
10 cin >> a;
11 ans = max(ans, a - i);
12 }
A number a2 is said to be the arithmetic mean of two numbers a1 and a3 , if the following condition
holds: a1 + a3 = 2 · a2 .
Arithmetic means a lot to Jeevan. He has three numbers a1 , a2 and a3 and he wants to minimize the
arithmetic mean deviation d(a1 , a2 , a3 ). To do so, he can perform the following operation any number
of times (possibly zero):
Help Jeevan find out the minimum value of d(a1 , a2 , a3 ) that can be obtained after applying the
operation any number of times.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 cout << ((a + b + c) % 3 != 0) << "\n";
8 }
9 int main() {
10 ios::sync_with_stdio(false);
11 cin.tie(nullptr);
12 int t;
13 cin >> t;
14 while (t--) {
15 solve();
16 }
17 return 0;
18 }
David was given a red checkered rectangle of size n × m. But he doesn’t like it. So David cuts the
original or any other rectangle piece obtained during the cutting into two new pieces along the grid
lines. He can do this operation as many times as he wants.
David also knows how to paint the cells blue. He wants each rectangle from the resulting set of pieces
to be colored such that any pair of adjacent cells by side (from the same piece) have different colors.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 int ans = (n * m - 1) / 3 + 1;
8 cout << ans << "\n";
9 }
10 int main() {
11 ios::sync_with_stdio(false);
12 cin.tie(nullptr);
13 int t;
14 cin >> t;
15 while (t--) {
16 solve();
17 }
18 return 0;
19 }
Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test
have the following form:
You are given two positive integers u and v, find any pair of integers (not necessarily positive) x, y, such
that:
x y x+y
+ = .
u v u+v
The solution x = 0, y = 0 is forbidden, so you should find any solution with (x, y) ̸= (0, 0).
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int u, v;
6 cin >> u >> v;
7 cout << 1LL * u * u << " " << -1LL * v * v << "\n";
8 }
9 int main() {
10 ios::sync_with_stdio(false);
11 cin.tie(nullptr);
12 int t;
13 cin >> t;
14 while (t--) {
15 solve();
16 }
17 return 0;
18 }
You are given 3 integers - n, x, y. Let’s call the score of a permutation† p1 , . . . , pn the following value:
In other words, the score of a permutation is the sum of pi for all indices i divisible by x, minus the sum
of pi for all indices i divisible by y.
You need to find the maximum possible score among all permutations of length n.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, x, y;
6 cin >> n >> x >> y;
7 i64 l = lcm(1LL * x, 1LL * y);
8 int pos = n / x - n / l;
9 int neg = n / y - n / l;
10 i64 ans = 1LL * (n + n - pos + 1) * pos / 2 - 1LL * (neg + 1) * neg / 2;
11 cout << ans << "\n";
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
You are given two integers l ≤ r. You need to find positive integers a and b such that the following
conditions are simultaneously satisfied:
l ≤a+b≤r
gcd(a, b) ̸= 1
gcd(a, b) denotes the greatest common divisor of numbers a and b. For example, gcd(6, 9) = 3,
gcd(8, 9) = 1, gcd(4, 2) = 2.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int l, r;
6 cin >> l >> r;
7 for (int i = max(4, l); i <= r; i++) {
8 for (int j = 2; j * j <= i; j++) {
9 if (i % j == 0) {
10 cout << j << " " << i - j << "\n";
11 return;
12 }
13 }
14 }
15 cout << -1 << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
Consider the array a composed of all the integers in the range [l, r]. For example, if l = 3 and r = 7,
then a = [3, 4, 5, 6, 7].
Given l, r, and k, is it possible for gcd(a) to be greater than 1 after doing the following operation at
most k times?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int l, r, k;
6 cin >> l >> r >> k;
7 bool ok;
8 if (l == r) {
9 if (l != 1) {
10 ok = true;
11 } else {
12 ok = false;
13 }
14 } else if (k >= (r + 1) / 2 - l / 2) {
15 ok = true;
16 } else {
17 ok = false;
18 }
19 cout << (ok ? "YES" : "NO") << "\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
You are given an array a of n elements. You can apply the following operation to it any number of
times:
For example, if a = [2, 1, 3, 4, 5, 3], then choose l = 1 and k = 2, applying this operation the array will
become a = [3, 4, 3, 4, 5, 3].
Find the minimum number of operations (possibly zero) needed to make all the elements of the array
equal.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int v = a[n - 1];
12 int l = n;
13 while (l > 0 && a[l - 1] == v) {
14 l--;
15 }
16 int ans = 0;
17 while (l > 0) {
18 l = max(0, 2 * l - n);
19 while (l > 0 && a[l - 1] == v) {
20 l--;
21 }
22 ans++;
23 }
24 cout << ans << "\n";
25 }
26 int main() {
27 ios::sync_with_stdio(false);
28 cin.tie(nullptr);
29 int t;
30 cin >> t;
31 while (t--) {
32 solve();
33 }
34 return 0;
35 }
You are given two arrays a and b of n positive integers each. You can apply the following operation to
them any number of times:
Select an index i (1 ≤ i ≤ n) and swap ai with bi (i. e. ai becomes bi and vice versa).
Find the minimum possible value of max(a1 , a2 , . . . , an )·max(b1 , b2 , . . . , bn ) you can get after applying
such operation any number of times (possibly zero).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector<int> b(n);
12 for (int i = 0; i < n; i++) {
13 cin >> b[i];
14 }
15 for (int i = 0; i < n; i++) {
16 if (a[i] > b[i]) {
17 swap(a[i], b[i]);
18 }
19 }
20 int ans = *max_element(a.begin(), a.end())
21 * *max_element(b.begin(), b.end());
22 cout << ans << "\n";
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
Sam is a kindergartener, and there are n children in his group. He decided to create a team with some
of his children to play “brawl:go 2”.
Sam has n power-ups, the i-th has type ai . A child’s strength is equal to the number of different types
among power-ups he has.
For a team of size k, Sam will distribute all n power-ups to k children in such a way that each of the k
children receives at least one power-up, and each power-up is given to someone.
For each integer k from 1 to n, find the minimum sum of strengths of a team of k children Sam can
get.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 set s(a.begin(), a.end());
12 int dist = s.size();
13 for (int k = 1; k <= n; k++) {
14 cout << max(dist, k) << " \n"[k == n];
15 }
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the
triangle:
He calls a point on the downtown’s border (that is the border of the triangle) safe if he can reach this
point from at least one point of the line y = 0 walking along some straight line, without crossing the
interior of the triangle.
Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are
segments and their number is finite.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int x[3], y[3];
6 for (int i = 0; i < 3; i++) {
7 cin >> x[i] >> y[i];
8 }
9 int ans = 0;
10 for (int i = 0; i < 3; i++) {
11 if (y[0] == y[1] && y[0] > y[2]) {
12 ans += abs(x[0] - x[1]);
13 }
14 rotate(x, x + 1, x + 3);
15 rotate(y, y + 1, y + 3);
16 }
17 cout << ans << "\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
Madoka finally found the administrator password for her computer. Her father is a well-known popu-
larizer of mathematics, so the password is the answer to the following problem.
Find the maximum decimal number without zeroes and with no equal digits in a row, such that the
sum of its digits is n.
Madoka is too tired of math to solve it herself, so help her to solve this problem!
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int t = n % 3 == 1 ? 1 : 2;
8 while (n > 0) {
9 cout << t;
10 n -= t;
11 t = 3 - t;
12 }
13 cout << "\n";
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
You are given a grid with n rows and m columns. Rows and columns are numbered from 1 to n, and
from 1 to m. The intersection of the a-th row and b-th column is denoted by (a, b).
Initially, you are standing in the top left corner (1, 1). Your goal is to reach the bottom right corner
(n, m).
You can move in four directions from (a, b): up to (a − 1, b), down to (a + 1, b), left to (a, b − 1) or right
to (a, b + 1).
You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What
is the minimum number of moves to reach (n, m)?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 int ans;
8 if (n == 1 && m == 1) {
9 ans = 0;
10 } else if (n + m == 3) {
11 ans = 1;
12 } else if (n == 1 || m == 1) {
13 ans = -1;
14 } else {
15 ans = max(n, m) * 2 - 3;
16 if (ans % 2 != (n + m) % 2) {
17 ans++;
18 }
19 }
20 cout << ans << "\n";
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
30 return 0;
31 }
You are allowed to perform this operation any number of times (possibly, zero):
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 bool ok = true;
9 for (int i = 0; i < n; i++) {
10 cin >> a[i];
11 if (a[i] % a[0] != 0) {
12 ok = false;
13 }
14 }
15 cout << (ok ? "YES" : "NO") << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
Chaneka, Pak Chanek’s child, is an ambitious kid, so Pak Chanek gives her the following problem to
test her ambition.
Given an array of integers [A1 , A2 , A3 , . . . , AN ]. In one operation, Chaneka can choose one element,
then increase or decrease the element’s value by 1. Chaneka can do that operation multiple times,
even for different elements.
What is the minimum number of operations that must be done to make it such that A1 × A2 × A3 ×
. . . × AN = 0?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int N;
8 cin >> N;
9 int ans = 1E9;
10 for (int i = 0; i < N; i++) {
11 int x;
12 cin >> x;
13 ans = min(ans, abs(x));
14 }
15 cout << ans << "\n";
16 return 0;
17 }
You are given an array a1 , a2 , . . . , an of pairwise distinct integers from 0 to n. Consider the following
operation:
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n);
8 i64 b = 1LL * n * (n + 1) / 2;
9 for (int i = 0; i < n; i++) {
10 cin >> a[i];
11 b -= a[i];
12 }
13 a.push_back(b);
14 k %= (n + 1);
15 rotate(a.begin(), a.end() - k, a.end());
125: Channel
Petya is an administrator of a channel in one of the messengers. A total of n people are subscribed to
his channel, and Petya is not considered a subscriber.
Petya has published a new post on the channel. At the moment of the publication, there were a
subscribers online. We assume that every subscriber always reads all posts in the channel if they are
online.
After this, Petya starts monitoring the number of subscribers online. He consecutively receives q
notifications of the form “a subscriber went offline” or “a subscriber went online”. Petya does not know
which exact subscriber goes online or offline. It is guaranteed that such a sequence of notifications
could have indeed been received.
Petya wonders if all of his subscribers have read the new post. Help him by determining one of the
following:
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, a, q;
6 cin >> n >> a >> q;
7 bool ok = (a == n);
8 string s;
9 cin >> s;
10 int sum = a;
11 for (int i = 0; i < q; i++) {
12 a += (s[i] == '+' ? 1 : -1);
13 sum += (s[i] == '+' ? 1 : 0);
14 ok |= a == n;
15 }
16 if (ok) {
17 cout << "YES\n";
18 } else if (sum < n) {
19 cout << "NO\n";
20 } else {
21 cout << "MAYBE\n";
22 }
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
Recently, Tema and Vika celebrated Family Day. Their friend Arina gave them a carpet, which can be
represented as an n · m table of lowercase Latin letters.
Vika hasn’t seen the gift yet, but Tema knows what kind of carpets she likes. Vika will like the carpet
if she can read her name on. She reads column by column from left to right and chooses one or zero
letters from current column.
Formally, the girl will like the carpet if it is possible to select four distinct columns in order from left to
right such that the first column contains “v”, the second one contains “i”, the third one contains “k”,
and the fourth one contains “a”.
Help Tema understand in advance whether Vika will like Arina’s gift.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<string> s(n);
8 for (int i = 0; i < n; i++) {
9 cin >> s[i];
10 }
11 string t = "vika";
12 array<bool, 5> dp{};
13 dp[0] = 1;
14 for (int i = 0; i < m; i++) {
15 array<bool, 4> b{};
16 for (int j = 0; j < n; j++) {
17 int x = t.find(s[j][i]);
18 if (x != -1) {
19 b[x] = true;
20 }
21 }
22 for (int x = 3; x >= 0; x--) {
23 if (b[x]) {
24 dp[x + 1] |= dp[x];
25 }
26 }
27 }
28 cout << (dp[4] ? "YES" : "NO") << "\n";
29 }
30 int main() {
31 ios::sync_with_stdio(false);
32 cin.tie(nullptr);
33 int t;
34 cin >> t;
35 while (t--) {
36 solve();
37 }
38 return 0;
39 }
Mishka has got n empty boxes. For every i (1 <= i <= n), i-th box is a cube with side length ai.
Mishka can put a box i into another box j if the following conditions are met:
Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number
of visible boxes. A box is called visible iff it is not put into some another box.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 map<int, int> cnt;
10 for (int i = 0; i < n; i++) {
11 int a;
12 cin >> a;
13 cnt[a]++;
14 }
15 int ans = 0;
16 for (auto [a, c] : cnt) {
17 ans = max(ans, c);
18 }
19 cout << ans << "\n";
20 return 0;
21 }
Vova is again playing some computer game, now an RPG. In the game Vova’s character received a quest:
to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab
has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong
healing potions and to prepare for battle.
Vova’s character has h1 health points and an attack power of a1. Also he has a large supply of healing
potions, each of which increases his current amount of health points by c1 when Vova drinks a potion.
All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the
monster (thus reducing its health by a1) or drink a healing potion (it increases Vova’s health by c1;
Vova’s health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his
health by a2. The battle ends when Vova’s (or Modcrab’s) health drops to 0 or lower. It is possible that
the battle ends in a middle of a phase after Vova’s attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to
make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and
that he can always win.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int h1, a1, c1;
8 cin >> h1 >> a1 >> c1;
9 int h2, a2;
10 cin >> h2 >> a2;
11 vector<string> ans;
12 while (h2 > 0) {
13 if (a1 >= h2 || h1 > a2) {
14 ans.push_back("STRIKE");
15 h2 -= a1;
16 h1 -= a2;
17 } else {
18 ans.push_back("HEAL");
19 h1 += c1 - a2;
20 }
21 }
22 cout << ans.size() << "\n";
23 for (auto s : ans) {
24 cout << s << "\n";
25 }
26 return 0;
27 }
Ivan’s classes at the university have just finished, and now he wants to go to the local CFK cafe and eat
some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one - 7
chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly this amount
of chicken.
Formally, Ivan wants to know if he can choose two non-negative integers a and b in such a way that a
small portions and b large ones contain exactly x chunks.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int x;
6 cin >> x;
7 if (set{1, 2, 4, 5, 8, 11}.count(x)) {
8 cout << "NO\n";
9 } else {
10 cout << "YES\n";
11 }
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after
removal of which the remaining points are located on one side of the OY axis.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 int pos = 0;
10 for (int i = 0; i < n; i++) {
11 int x, y;
12 cin >> x >> y;
13 pos += (x > 0);
14 }
15 if (pos <= 1 || pos >= n - 1) {
16 cout << "Yes\n";
17 } else {
18 cout << "No\n";
19 }
20 return 0;
21 }
sortings
You love fish, that’s why you have decided to build an aquarium. You have a piece of coral made of n
columns, the i-th of which is ai units tall. Afterwards, you will build a tank around the coral as follows:
Pick an integer h ≥ 1 - the height of the tank. Build walls of height h on either side of the tank.
Then, fill the tank up with water so that the height of each column is h, unless the coral is taller than h;
then no water should be added to this column.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, x;
6 cin >> n >> x;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 sort(a.begin(), a.end());
12 i64 sum = 0;
13 i64 ans = 0;
14 for (int i = 0; i < n; i++) {
15 if (i && sum + 1LL * i * (a[i] - a[i - 1]) > x) {
16 ans = a[i - 1] + (x - sum) / i;
17 break;
18 }
19 if (i) {
20 sum += 1LL * i * (a[i] - a[i - 1]);
21 }
22 if (i == n - 1) {
23 ans = a[i] + (x - sum) / n;
24 }
25 }
26 cout << ans << "\n";
27 }
28 int main() {
29 ios::sync_with_stdio(false);
30 cin.tie(nullptr);
31 int t;
32 cin >> t;
33 while (t--) {
34 solve();
35 }
36 return 0;
37 }
132: 2D Traveling
Piggy lives on an infinite plane with the Cartesian coordinate system on it.
There are n cities on the plane, numbered from 1 to n, and the first k cities are defined as major cities.
The coordinates of the i-th city are (xi , yi ).
Piggy, as a well-experienced traveller, wants to have a relaxing trip after Zhongkao examination.
Currently, he is in city a, and he wants to travel to city b by air. You can fly between any two cities, and
you can visit several cities in any order while travelling, but the final destination must be city b.
Because of active trade between major cities, it’s possible to travel by plane between them for free.
Formally, the price of an air ticket f (i, j) between two cities i and j is defined as follows:
0, if cities i and j are both major cities
f (i, j) =
|x − x | + |y − y |,
i j i j otherwise
Piggy doesn’t want to save time, but he wants to save money. So you need to tell him the minimum
value of the total cost of all air tickets if he can take any number of flights.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k, a, b;
6 cin >> n >> k >> a >> b;
7 a--, b--;
8 vector<int> x(n), y(n);
9 for (int i = 0; i < n; i++) {
10 cin >> x[i] >> y[i];
11 }
12 i64 ans = 1LL * abs(x[a] - x[b]) + abs(y[a] - y[b]);
13 i64 da = 1E18, db = 1E18;
14 for (int i = 0; i < k; i++) {
15 da = min(da, 1LL * abs(x[a] - x[i]) + abs(y[a] - y[i]));
16 db = min(db, 1LL * abs(x[b] - x[i]) + abs(y[b] - y[i]));
17 }
18 ans = min(ans, da + db);
19 cout << ans << "\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
m chairs are arranged in a circle sequentially. The chairs are numbered from 0 to m − 1. n people want
to sit in these chairs. The i-th of them wants at least a[i] empty chairs both on his right and left side.
More formally, if the i-th person sits in the j-th chair, then no one else should sit in the following chairs:
(j − a[i]) mod m, (j − a[i] + 1) mod m, . . . (j + a[i] − 1) mod m, (j + a[i]) mod m.
Decide if it is possible to sit down for all of them, under the given limitations.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 i64 ans = accumulate(a.begin(), a.end(), 0LL);
12 ans += *max_element(a.begin(), a.end());
13 ans -= *min_element(a.begin(), a.end());
14 ans += n;
15 cout << (ans <= m ? "YES" : "NO") << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
You can change the current permutation by applying the following operation several (possibly, zero)
times:
create a new permutation by: first, writing down all elements of p that are less than x, without changing
their order; second, writing down all elements of p that are greater than or equal to x, without changing
their order;
first, writing down all elements of p that are less than x, without changing their order;
second, writing down all elements of p that are greater than or equal to x, without changing their
order;
For example, if the permutation used to be [6, 4, 3, 5, 2, 1] and you choose x = 4, then you will first
write down [3, 2, 1], then append this with [6, 4, 5]. So the initial permutation will be replaced by
[3, 2, 1, 6, 4, 5].
Find the minimum number of operations you need to achieve pi = i for i = 1, 2, . . . , n. We can show
that it is always possible to do so.
†A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order.
For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the
array), and [1, 3, 4] is also not a permutation (n = 3 but there is 4 in the array).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> p(n);
8 for (int i = 0; i < n; i++) {
9 int x;
10 cin >> x;
11 x--;
12 p[x] = i;
13 }
14 int ans = 0;
15 for (int i = 1; i < n; i++) {
16 ans += (p[i - 1] > p[i]);
17 }
18 cout << ans << "\n";
19 }
20 int main() {
21 ios::sync_with_stdio(false);
22 cin.tie(nullptr);
23 int t;
24 cin >> t;
25 while (t--) {
26 solve();
27 }
28 return 0;
29 }
Anya lives in the Flower City. By order of the city mayor, she has to build a fence for herself.
The fence consists of n planks, each with a height of ai meters. According to the order, the heights of
the planks must not increase. In other words, it is true that ai ≥ aj for all i < j.
Anya became curious whether her fence is symmetrical with respect to the diagonal. In other words,
will she get the same fence if she lays all the planks horizontally in the same order.
For example, for n = 5, a = [5, 4, 3, 2, 1], the fence is symmetrical. Because if all the planks are laid
horizontally, the fence will be [5, 4, 3, 2, 1], as shown in the diagram.
On the left is the fence [5, 4, 3, 2, 1], on the right is the same fence laid horizontally
But for n = 3, a = [4, 2, 1], the fence is not symmetrical. Because if all the planks are laid horizontally,
the fence will be [3, 2, 1, 1], as shown in the diagram.
On the left is the fence [4, 2, 1], on the right is the same fence laid horizontally
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 0, j = n; i < n; i++) {
12 while (j > 0 && a[j - 1] <= i) {
13 j--;
14 }
15 if (a[i] != j) {
16 cout << "NO\n";
17 return;
18 }
19 }
20 cout << "YES\n";
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
30 return 0;
31 }
136: Destroyer
John is a lead programmer on a destroyer belonging to the space navy of the Confederacy of Indepen-
dent Operating Systems. One of his tasks is checking if the electronic brains of robots were damaged
during battles.
A standard test is to order the robots to form one or several lines, in each line the robots should stand
one after another. After that, each robot reports the number of robots standing in front of it in its line.
The i-th robot reported number li . Unfortunately, John does not know which line each robot stands in,
and can’t check the reported numbers. Please determine if it is possible to form the lines in such a way
that all reported numbers are correct, or not.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> cnt(n + 1);
8 for (int i = 0; i < n; i++) {
9 int x;
10 cin >> x;
11 cnt[min(n, x)]++;
12 }
13 for (int i = 1; i <= n; i++) {
14 if (cnt[i] > cnt[i - 1]) {
15 cout << "NO\n";
16 return;
17 }
18 }
19 cout << "YES\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
Sasha has an array a of n integers. He got bored and for all i, j (i < j), he wrote down the minimum
value of ai and aj . He obtained a new array b of size n·(n−1)
2 .
For example, if a = [2, 3, 5, 1], he would write [min(2, 3), min(2, 5), min(2, 1), min(3, 5), min(3, 1), min(5, 1)]
= [2, 2, 1, 3, 1, 1].
Unfortunately, he forgot the array a, and your task is to restore any possible array a from which the
array b could have been obtained.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n * (n - 1) / 2);
8 for (int i = 0; i < n * (n - 1) / 2; i++) {
9 cin >> a[i];
10 }
11 sort(a.begin(), a.end());
12 for (int i = 0; i < n - 1; i++) {
13 cout << a[(n - 1 + n - i) * i / 2] << " ";
14 }
15 cout << a.back() << "\n";
16 }
17 int main() {
18 ios::sync_with_stdio(false);
19 cin.tie(nullptr);
20 int t;
21 cin >> t;
22 while (t--) {
23 solve();
24 }
25 return 0;
26 }
138: Monsters
Monocarp is playing yet another computer game. And yet again, his character is killing some monsters.
There are n monsters, numbered from 1 to n, and the i-th of them has ai health points initially.
Monocarp’s character has an ability that deals k damage to the monster with the highest current health.
If there are several of them, the one with the smaller index is chosen. If a monster’s health becomes
less than or equal to 0 after Monocarp uses his ability, then it dies.
Monocarp uses his ability until all monsters die. Your task is to determine the order in which monsters
will die.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector<int> p(n);
12 iota(p.begin(), p.end(), 0);
13 stable_sort(p.begin(), p.end(),
14 [&](int i, int j) {
15 return (a[i] - 1) % k > (a[j] - 1) % k;
16 });
17 for (int i = 0; i < n; i++) {
18 cout << p[i] + 1 << " \n"[i == n - 1];
19 }
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
You have an array of integers a of length n. You can apply the following operation to the given array:
Swap two elements ai and aj such that i ̸= j, ai and aj are either both even or both odd.
Determine whether it is possible to sort the array in non-decreasing order by performing the operation
any number of times (possibly zero).
For example, let a = [7, 10, 1, 3, 2]. Then we can perform 3 operations to sort the array:
Swap a3 = 1 and a1 = 7, since 1 and 7 are odd. We get a = [1, 10, 7, 3, 2];
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 auto b = a;
12 sort(b.begin(), b.end());
13 for (int i = 0; i < n; i++) {
14 if ((a[i] - b[i]) % 2) {
15 cout << "NO\n";
16 return;
17 }
18 }
19 cout << "YES\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
In the game show “Ten Words of Wisdom”, there are n participants numbered from 1 to n, each of
whom submits one response. The i-th response is ai words long and has quality bi . No two responses
have the same quality, and at least one response has length at most 10.
The winner of the show is the response which has the highest quality out of all responses that are not
longer than 10 words. Which response is the winner?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 int x = 0, q = 0;
8 for (int i = 1; i <= n; i++) {
9 int a, b;
10 cin >> a >> b;
11 if (a <= 10 && b > q) {
12 q = b;
13 x = i;
14 }
15 }
16 cout << x << "\n";
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
141: To My Critics
Since math isn’t his strongest point, he asks you to determine if you can choose any two digits to make
a sum greater or equal to 10.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 if (max({a + b, b + c, c + a}) >= 10) {
8 cout << "YES\n";
9 } else {
10 cout << "NO\n";
11 }
12 }
13 int main() {
14 ios::sync_with_stdio(false);
15 cin.tie(nullptr);
16 int t;
17 cin >> t;
18 while (t--) {
19 solve();
20 }
21 return 0;
22 }
Kars is tired and resentful of the narrow mindset of his village since they are content with staying where
they are and are not trying to become the perfect life form. Being a top-notch inventor, Kars wishes
to enhance his body and become the perfect life form. Unfortunately, n of the villagers have become
suspicious of his ideas. The i-th villager has a suspicion of ai on him. Individually each villager is scared
of Kars, so they form into groups to be more powerful.
Here |x − y| is the absolute value of x − y. A group with only one villager has a power of 0.
Kars wants to break the villagers into exactly k contiguous subgroups so that the sum of their power is
minimized. Formally, he must find k − 1 positive integers 1 ≤ r1 < r2 < . . . < rk−1 < n such that
f (1, r1 ) + f (r1 + 1, r2 ) + . . . + f (rk−1 + 1, n) is minimised. Help Kars in finding the minimum value
of f (1, r1 ) + f (r1 + 1, r2 ) + . . . + f (rk−1 + 1, n).
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector<int> d(n - 1);
12 for (int i = 0; i < n - 1; i++) {
13 d[i] = abs(a[i + 1] - a[i]);
14 }
15 sort(d.begin(), d.end());
16 int ans = 0;
17 for (int i = 0; i < n - k; i++) {
18 ans += d[i];
19 }
20 cout << ans << "\n";
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
30 return 0;
31 }
In the summer, Vika likes to visit her country house. There is everything for relaxation: comfortable
swings, bicycles, and a river.
There is a wooden bridge over the river, consisting of n planks. It is quite old and unattractive, so Vika
decided to paint it. And in the shed, they just found cans of paint of k colors.
After painting each plank in one of k colors, Vika was about to go swinging to take a break from work.
However, she realized that the house was on the other side of the river, and the paint had not yet
completely dried, so she could not walk on the bridge yet.
In order not to spoil the appearance of the bridge, Vika decided that she would still walk on it, but only
stepping on planks of the same color. Otherwise, a small layer of paint on her sole will spoil the plank
of another color. Vika also has a little paint left, but it will only be enough to repaint one plank of the
bridge.
Now Vika is standing on the ground in front of the first plank. To walk across the bridge, she will choose
some planks of the same color (after repainting), which have numbers 1 ≤ i1 < i2 < . . . < im ≤ n
(planks are numbered from 1 from left to right). Then Vika will have to cross i1 − 1, i2 − i1 − 1, i3 −
i2 − 1, . . . , im − im−1 − 1, n − im planks as a result of each of m + 1 steps.
Since Vika is afraid of falling, she does not want to take too long steps. Help her and tell her the
minimum possible maximum number of planks she will have to cross in one step, if she can repaint
one (or zero) plank a different color while crossing the bridge.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> c(n);
Rudolf has registered for a programming competition that will follow the rules of ICPC. The rules imply
that for each solved problem, a participant gets 1 point, and also incurs a penalty equal to the number
of minutes passed from the beginning of the competition to the moment of solving the problem. In
the final table, the participant with the most points is ranked higher, and in case of a tie in points, the
participant with the lower penalty is ranked higher.
In total, n participants have registered for the competition. Rudolf is a participant with index 1. It is
known that m problems will be proposed. And the competition will last h minutes.
A powerful artificial intelligence has predicted the values ti,j , which represent the number of minutes
it will take for the i-th participant to solve the j-th problem.
Rudolf realized that the order of solving problems will affect the final result. For example, if h = 120,
and the times to solve problems are [20, 15, 110], then if Rudolf solves the problems in the order:
3, 1, 2, then he will only solve the third problem and get 1 point and 110 penalty.
1, 2, 3, then he will solve the first problem after 20 minutes from the start, the second one after 20+15 =
35 minutes, and he will not have time to solve the third one. Thus, he will get 2 points and 20 + 35 = 55
penalty.
2, 1, 3, then he will solve the second problem after 15 minutes from the start, the first one after 15+20 =
35 minutes, and he will not have time to solve the third one. Thus, he will get 2 points and 15 + 35 = 50
penalty.
Rudolf became interested in what place he will take in the competition if each participant solves
problems in the optimal order based on the predictions of the artificial intelligence. It will be assumed
that in case of a tie in points and penalty, Rudolf will take the best place.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m, h;
6 cin >> n >> m >> h;
7 vector t(n, vector<int>(m));
8 vector<pair<int, i64>> a(n);
9 for (int i = 0; i < n; i++) {
10 for (int j = 0; j < m; j++) {
11 cin >> t[i][j];
12 }
13 sort(t[i].begin(), t[i].end());
14 int c = 0;
15 i64 p = 0;
16 int sum = 0;
17 for (auto x : t[i]) {
18 if (sum + x <= h) {
19 sum += x;
20 p += sum;
21 c++;
22 }
23 }
24 a[i] = {c, -p};
25 }
26 int ans = 1;
27 for (int i = 1; i < n; i++) {
28 ans += (a[0] < a[i]);
29 }
30 cout << ans << "\n";
31 }
32 int main() {
33 ios::sync_with_stdio(false);
34 cin.tie(nullptr);
35 int t;
36 cin >> t;
37 while (t--) {
38 solve();
39 }
40 return 0;
41 }
145: Lamps
You have n lamps, numbered by integers from 1 to n. Each lamp i has two integer parameters ai and
bi .
At each moment each lamp is in one of three states: it may be turned on, turned off, or broken.
Initially all lamps are turned off. In one operation you can select one lamp that is turned off and turn it
on (you can’t turn on broken lamps). You receive bi points for turning lamp i on. The following happens
after each performed operation:
Let’s denote the number of lamps that are turned on as x (broken lamps do not count). All lamps i
such that ai ≤ x simultaneously break, whether they were turned on or off.
Please note that broken lamps never count as turned on and that after a turned on lamp breaks, you
still keep points received for turning it on.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 i64 ans = 0;
8 vector<pair<int, int>> l(n);
9 for (int i = 0; i < n; i++) {
10 int a, b;
11 cin >> a >> b;
12 l[i] = {a, -b};
13 }
14 sort(l.begin(), l.end());
15 int cnt = 0;
16 for (int i = 0, j = 0; i < n; i++) {
17 if (i >= j) {
18 cnt++;
19 ans += -l[i].second;
20 }
You are given an array a containing the weather forecast for Berlandia for the last n days. That is, ai - is
the estimated air temperature on day i (1 ≤ i ≤ n).
You are also given an array b - the air temperature that was actually present on each of the days.
However, all the values in array b are mixed up.
Determine which day was which temperature, if you know that the weather never differs from the
forecast by more than k degrees. In other words, if on day i the real air temperature was c, then the
equality |ai − c| ≤ k is always true.
For example, let an array a = [1, 3, 5, 3, 9] of length n = 5 and k = 2 be given and an array b =
[2, 5, 11, 2, 4]. Then, so that the value of bi corresponds to the air temperature on day i, we can
rearrange the elements of the array b so: [2, 2, 5, 4, 11]. Indeed:
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n), b(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 0; i < n; i++) {
12 cin >> b[i];
13 }
14 vector<int> o(n), ans(n);
15 iota(o.begin(), o.end(), 0);
16 sort(o.begin(), o.end(), [&](int i, int j) {
17 return a[i] < a[j];
18 });
19 sort(b.begin(), b.end());
20 for (int i = 0; i < n; i++) {
21 ans[o[i]] = b[i];
22 }
23 for (int i = 0; i < n; i++) {
24 cout << ans[i] << " \n"[i == n - 1];
25 }
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
You are given two arrays a and b each consisting of n integers. All elements of a are pairwise distinct.
Find the number of ways to reorder a such that ai > bi for all 1 ≤ i ≤ n, modulo 109 + 7.
Two ways of reordering are considered different if the resulting arrays are different.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 template<class T>
5 constexpr T power(T a, i64 b) {
6 T res = 1;
7 for (; b; b /= 2, a *= a) {
8 if (b % 2) {
9 res *= a;
10 }
11 }
12 return res;
13 }
14 constexpr i64 mul(i64 a, i64 b, i64 p) {
15 i64 res = a * b - i64(1.L * a * b / p) * p;
16 res %= p;
17 if (res < 0) {
18 res += p;
19 }
20 return res;
21 }
22 template<i64 P>
23 # struct MLong;
24 template<>
25 i64 MLong<0LL>::Mod = 1;
26 template<int P>
27 # struct MInt;
28 template<>
29 int MInt<0>::Mod = 1;
30 template<int V, int P>
31 constexpr MInt<P> CInv = MInt<P>(V).inv();
32 constexpr int P = 1000000007;
33 using Z = MInt<P>;
34 void solve() {
35 int n;
36 cin >> n;
37 vector<int> a(n), b(n);
38 for (int i = 0; i < n; i++) {
39 cin >> a[i];
40 }
41 for (int i = 0; i < n; i++) {
42 cin >> b[i];
43 }
44 sort(a.begin(), a.end());
45 sort(b.begin(), b.end());
46 Z ans = 1;
47 for (int i = 0, j = 0; i < n; i++) {
48 while (j < n && a[i] > b[j]) {
49 j++;
50 }
51 ans *= j - i;
52 }
53 cout << ans << "\n";
54 }
55 int main() {
56 ios::sync_with_stdio(false);
57 cin.tie(nullptr);
58 int t;
59 cin >> t;
60 while (t--) {
61 solve();
62 }
63 return 0;
64 }
Xenia the beginner mathematician is a third year student at elementary school. She is now learning
the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make
the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn’t enough for Xenia. She
is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing
order. For example, she can’t calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You’ve got the sum that was written on the board. Rearrange the summans and print the sum in such a
way that Xenia can calculate the sum.
Problem: link
Tutorial: link
Solution: link
1 a = list(map(int, input().split('+')))
2 a.sort()
3 print('+'.join(map(str, a)))
Let’s define a permutation of length n as an array p of length n, which contains every number from 1 to
n exactly once.
You are given a permutation p1 , p2 , . . . , pn and a number k. You need to sort this permutation in the
ascending order. In order to do it, you can repeat the following operation any number of times (possibly,
zero):
pick two elements of the permutation pi and pj such that |i − j| = k, and swap them.
Unfortunately, some permutations can’t be sorted with some fixed numbers k. For example, it’s
impossible to sort [2, 4, 3, 1] with k = 2.
That’s why, before starting the sorting, you can make at most one preliminary exchange:
check whether is it possible to sort the permutation without any preliminary exchanges,
if it’s not, check, whether is it possible to sort the permutation using exactly one preliminary ex-
change.
For example, if k = 2 and permutation is [2, 4, 3, 1], then you can make a preliminary exchange of p1
and p4 , which will produce permutation [1, 4, 3, 2], which is possible to sort with given k.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 int cnt = 0;
8 for (int i = 0; i < n; i++) {
9 int x;
10 cin >> x;
11 x--;
12 cnt += (x % k != i % k);
13 }
14 if (cnt > 2) {
15 cout << -1 << "\n";
16 return;
17 }
18 cout << cnt / 2 << "\n";
19 }
20 int main() {
21 ios::sync_with_stdio(false);
22 cin.tie(nullptr);
23 int t;
24 cin >> t;
25 while (t--) {
26 solve();
27 }
28 return 0;
29 }
Karina has an array of n integers a1 , a2 , a3 , . . . , an . She loves multiplying numbers, so she decided that
the beauty of a pair of numbers is their product. And the beauty of an array is the maximum beauty of
a pair of adjacent elements in the array.
For example, for n = 4, a = [3, 5, 7, 4], the beauty of the array is max(3 · 5, 5 · 7, 7 · 4) = max(15, 35, 28)
= 35.
Karina wants her array to be as beautiful as possible. In order to achieve her goal, she can remove
some elements (possibly zero) from the array. After Karina removes all elements she wants to, the
array must contain at least two elements.
Unfortunately, Karina doesn’t have enough time to do all her tasks, so she asks you to calculate the
maximum beauty of the array that she can get by removing any number of elements (possibly zero).
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 sort(a.begin(), a.end());
12 if (n > 4) {
13 a.erase(a.begin() + 2, a.end() - 2);
14 n = 4;
15 }
16 i64 ans = -1E18;
17 for (int i = 0; i < n; i++) {
18 for (int j = i+1; j < n; j++) {
19 ans = max(ans, 1LL * a[i] * a[j]);
20 }
21 }
22 cout << ans << "\n";
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
green
brute force
Given a non-negative integer number n (n ≥ 0). Let’s say a triple of non-negative integers (a, b, c) is
good if a + b + c = n, and digsum(a) + digsum(b) + digsum(c) = digsum(n), where digsum(x) is
the sum of digits of number x.
For example, if n = 26, then the pair (4, 12, 10) is good, because 4 + 12 + 10 = 26, and (4) + (1 + 2) +
(1 + 0) = (2 + 6).
Your task is to find the number of good triples for the given number n. The order of the numbers in a
triple matters. For example, the triples (4, 12, 10) and (10, 12, 4) are two different triples.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 i64 ans = 1;
6 int n;
7 cin >> n;
8 while (n > 0) {
9 int x = n % 10;
10 ans *= (x + 1) * (x + 2) / 2;
11 n /= 10;
12 }
13 cout << ans << "\n";
14 }
15 int main() {
16 ios::sync_with_stdio(false);
17 cin.tie(nullptr);
18 int t;
19 cin >> t;
20 while (t--) {
21 solve();
22 }
23 return 0;
24 }
• ......
• What?
If a number is palindrome and length of its decimal representation without leading zeros is even,
we call it a zcy number. A number is palindrome means when written in decimal representation, it
contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221
are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.
Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo
p.
Unfortunately, Willem isn’t good at solving this kind of problems, so he asks you for help!
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 template<class T>
5 constexpr T power(T a, i64 b) {
6 T res = 1;
7 for (; b; b /= 2, a *= a) {
8 if (b % 2) {
9 res *= a;
10 }
11 }
12 return res;
13 }
14 constexpr i64 mul(i64 a, i64 b, i64 p) {
15 i64 res = a * b - i64(1.L * a * b / p) * p;
16 res %= p;
17 if (res < 0) {
18 res += p;
19 }
20 return res;
21 }
22 template<i64 P>
23 # struct MLong;
24 template<>
25 i64 MLong<0LL>::Mod = i64(1E18) + 9;
26 template<int P>
27 # struct MInt;
28 template<>
29 int MInt<0>::Mod = 998244353;
30 template<int V, int P>
31 constexpr MInt<P> CInv = MInt<P>(V).inv();
32 constexpr int P = 998244353;
33 using Z = MInt<0>;
34 int main() {
35 ios::sync_with_stdio(false);
36 cin.tie(nullptr);
37 int k, p;
38 cin >> k >> p;
39 Z::setMod(p);
40 Z ans;
41 for (int i = 1; i <= k; i++) {
42 string s = to_string(i);
43 s += string(s.rbegin(), s.rend());
44 ans += stoll(s);
45 }
46 cout << ans << "\n";
47 return 0;
48 }
You make m copies of this string, let the i-th copy be the string ti . Then you perform exactly one
operation on each of the copies: for the i-th copy, you sort its substring [li ; ri ] (the substring from the
li -th character to the ri -th character, both endpoints inclusive). Note that each operation affects only
one copy, and each copy is affected by only one operation.
Your task is to calculate the number of different strings among t1 , t2 , . . . , tm . Note that the initial string
s should be counted only if at least one of the copies stays the same after the operation.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 string s;
8 cin >> s;
9 set<pair<int, int>> S;
10 vector<int> nxt(n + 1, n), lst(n + 1, -1);
11 for (int i = n - 1; i >= 0; i--) {
12 nxt[i] = s[i] == '1' ? i : nxt[i + 1];
13 }
14 for (int i = 0; i < n; i++) {
15 lst[i + 1] = s[i] == '0' ? i : lst[i];
16 }
17 while (m--) {
18 int l, r;
19 cin >> l >> r;
20 l--;
21 l = nxt[l];
22 r = lst[r];
23 if (l > r) {
24 l = r = -1;
25 }
26 S.emplace(l, r);
27 }
28 cout << S.size() << "\n";
29 }
30 int main() {
31 ios::sync_with_stdio(false);
32 cin.tie(nullptr);
33 int t;
34 cin >> t;
35 while (t--) {
36 solve();
37 }
38 return 0;
39 }
DIO knows that the Stardust Crusaders have determined his location and will be coming to fight him.
To foil their plans he decides to send out some Stand users to fight them. Initially, he summoned n
Stand users with him, the i-th one having a strength of ai . Using his vampiric powers, he can do the
following as many times as he wishes:
Then he summons a new Stand user, with index m + 1 and strength given by:
am+1 = ai ⊕ ai+1 ⊕ . . . ⊕ am ,
Unfortunately for DIO, by using Hermit Purple’s divination powers, the Crusaders know that he is
plotting this, and they also know the strengths of the original Stand users. Help the Crusaders find the
maximum possible strength of a Stand user among all possible ways that DIO can summon.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector<int> s(n + 1);
12 int ans = 0;
13 for (int i = 0; i < n; i++) {
14 s[i + 1] = s[i] ^ a[i];
15 }
16 sort(s.begin(), s.end());
17 s.erase(unique(s.begin(), s.end()), s.end());
18 for (int i = 0; i < s.size(); i++) {
19 for (int j = 0; j < i; j++) {
20 ans = max(ans, s[i] ^ s[j]);
21 }
22 }
23 cout << ans << "\n";
24 }
25 int main() {
26 ios::sync_with_stdio(false);
27 cin.tie(nullptr);
28 int t;
29 cin >> t;
30 while (t--) {
31 solve();
32 }
33 return 0;
34 }
You are given an array a consisting of n zeros. You are also given a set of m not necessarily different
segments. Each segment is defined by two numbers li and ri (1 ≤ li ≤ ri ≤ n) and represents a
subarray ali , ali +1 , . . . , ari of the array a.
Let’s call the segment li , ri beautiful if the number of ones on this segment is strictly greater than the
number of zeros. For example, if a = [1, 0, 1, 0, 1], then the segment [1, 5] is beautiful (the number of
ones is 3, the number of zeros is 2), but the segment [3, 4] is not is beautiful (the number of ones is 1,
the number of zeros is 1).
You also have q changes. For each change you are given the number 1 ≤ x ≤ n, which means that you
must assign an element ax the value 1.
You have to find the first change after which at least one of m given segments becomes beautiful, or
report that none of them is beautiful after processing all q changes.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<int> l(m), r(m);
8 for (int i = 0; i < m; i++) {
9 cin >> l[i] >> r[i];
10 l[i]--;
11 }
12 int q;
13 cin >> q;
14 vector<int> x(q);
15 for (int i = 0; i < q; i++) {
16 cin >> x[i];
17 x[i]--;
18 }
19 int lo = 0, hi = q + 1;
20 while (lo < hi) {
The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially
appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus
n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each
other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.
The site of the University has already conducted a voting that estimated each sculpture’s characteristic
of ti - the degree of the sculpture’s attractiveness. The values of ti can be positive, negative or zero.
When the university rector came to evaluate the work, he said that this might be not the perfect
arrangement. He suggested to melt some of the sculptures so that:
the remaining sculptures form a regular polygon (the number of vertices should be between 3 and
n),
the sum of the ti values of the remaining sculptures is maximized.
Help the Vice Rector to analyze the criticism - find the maximum value of ti sum which can be obtained
in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 vector<int> t(n);
10 for (int i = 0; i < n; i++) {
11 cin >> t[i];
12 }
13 i64 ans = -1E18;
14 for (int x = 3; x <= n; x++) {
15 if (n % x) {
16 continue;
17 }
18 for (int i = 0; i < n/x; i++) {
19 i64 s = 0;
20 for (int j = i; j < n; j += n/x) {
21 s += t[j];
22 }
23 ans = max(ans, s);
24 }
25 }
26 cout << ans << "\n";
27 return 0;
28 }
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The
buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya
has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days.
According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of
money in bourles can Vasya get by the end of day n?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n, b;
8 cin >> n >> b;
9 vector<int> a(n);
10 for (int i = 0; i < n; i++) {
11 cin >> a[i];
12 }
13 int ans = b;
14 for (int i = 0; i < n; i++) {
15 for (int j = i+1; j < n; j++) {
16 ans = max(ans, b + (a[j] - a[i]) * (b / a[i]));
17 }
18 }
19 cout << ans << "\n";
20 return 0;
21 }
You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and
q.
For example, the string “Hello” for p = 2, q = 3 can be split to the two strings “Hel” and “lo” or to the
two strings “He” and “llo”.
Note it is allowed to split the string s to the strings only of length p or to the strings only of length q
(see the second sample test).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n, p, q;
8 cin >> n >> p >> q;
9 string s;
10 cin >> s;
11 for (int i = 0; i*p <= n; i++) {
12 if ((n - i*p) % q == 0) {
13 cout << i + (n - i*p) / q << "\n";
14 int j = 0;
15 while (j < i*p) {
16 cout << s.substr(j, p) << "\n";
17 j += p;
18 }
19 while (j < n) {
20 cout << s.substr(j, q) << "\n";
21 j += q;
22 }
23 return 0;
24 }
25 }
26 cout << -1 << "\n";
27 return 0;
28 }
In one operation, you can select several (one or more) positions in it such that no two selected positions
are adjacent to each other. Then you remove the letters on the selected positions from the string. The
resulting parts are concatenated without changing their order.
What is the smallest number of operations required to make all the letters in s the same?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 int n = s.size();
8 vector<int> p[26];
9 for (int i = 0; i < n; i++) {
10 p[s[i] - 'a'].push_back(i);
11 }
12 int ans = n;
13 for (int x = 0; x < 26; x++) {
14 int t = -1;
15 p[x].push_back(n);
16 int res = 0;
17 for (auto i : p[x]) {
18 int len = i - t - 1;
19 if (len) {
20 res = max(res, __lg(len) + 1);
21 }
22 t = i;
23 }
24 ans = min(ans, res);
25 }
26 cout << ans << "\n";
27 }
28 int main() {
29 ios::sync_with_stdio(false);
30 cin.tie(nullptr);
31 int t;
32 cin >> t;
33 while (t--) {
34 solve();
35 }
36 return 0;
37 }
After a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it N rows with M
trees each were planted and the rows were so neat that one could map it on a system of coordinates so
that the j-th tree in the i-th row would have the coordinates of (i, j). However a terrible thing happened
and the young forest caught fire. Now we must find the coordinates of the tree that will catch fire last
to plan evacuation.
The burning began in K points simultaneously, which means that initially K trees started to burn. Every
minute the fire gets from the burning trees to the ones that arent burning and that the distance from
them to the nearest burning tree equals to 1.
Find the tree that will be the last to start burning. If there are several such trees, output any.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
As you know, any problem that does not require the use of complex data structures is considered
constructive. You are offered to solve one of such problems.
You are given an array a of n non-negative integers. You are allowed to perform the following operation
exactly once: choose some non-empty subsegment al , al+1 , . . . , ar of the array a and a non-negative
integer k, and assign value k to all elements of the array on the chosen subsegment.
The task is to find out whether MEX(a) can be increased by exactly one by performing such an
operation. In other words, if before the operation MEX(a) = m held, then after the operation it must
hold that MEX(a) = m + 1.
Recall that MEX of a set of integers c1 , c2 , . . . , ck is defined as the smallest non-negative integer x
which does not occur in the set c.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 vector<int> f(n + 2);
9 for (int i = 0; i < n; i++) {
10 cin >> a[i];
11 if (a[i] <= n + 1) {
12 f[a[i]] = 1;
13 }
14 }
15 int m = 0;
16 while (f[m]) {
17 m++;
18 }
19 if (!f[m + 1]) {
20 if (m < n) {
21 cout << "Yes\n";
22 } else {
23 cout << "No\n";
24 }
25 return;
26 }
27 int l = 0, r = n - 1;
28 while (a[l] != m + 1) {
29 l++;
30 }
31 while (a[r] != m + 1) {
32 r--;
33 }
34 f.assign(n + 2, 0);
35 for (int i = l; i <= r; i++) {
36 a[i] = m;
37 }
38 for (auto x : a) {
39 if (x <= n + 1) {
40 f[x] = 1;
41 }
42 }
43 int newm = 0;
44 while (f[newm]) {
45 newm++;
46 }
47 if (newm == m + 1) {
48 cout << "Yes\n";
49 } else {
50 cout << "No\n";
51 }
52 }
53 int main() {
54 ios::sync_with_stdio(false);
55 cin.tie(nullptr);
56 int t;
57 cin >> t;
58 while (t--) {
59 solve();
60 }
61 return 0;
62 }
162: Accounting
A long time ago in some far country lived king Copa. After the recent king’s reform, he got so large
powers that started to keep the books by himself.
The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th
year (these numbers can be negative - it means that there was a loss in the correspondent year).
King wants to show financial stability. To do this, he needs to find common coefficient X - the coefficient
of income growth during one year. This coefficient should satisfy the equation:
Surely, the king is not going to do this job by himself, and demands you to find such number X.
It is necessary to point out that the fractional numbers are not used in kingdom’s economy. That’s why
all input numbers as well as coefficient X must be integers. The number X may be zero or negative.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int A, B, n;
8 cin >> A >> B >> n;
9 if (B == 0) {
10 cout << 0 << "\n";
11 return 0;
12 }
13 if (A == 0) {
14 cout << "No solution\n";
15 return 0;
16 }
17 int v = B / A, x;
18 if (v < 0) {
19 v = -v;
20 if (n % 2 == 0) {
21 cout << "No solution\n";
22 return 0;
23 }
24 x = pow(v, 1. / n) + .5;
25 x = -x;
26 } else {
27 x = pow(v, 1. / n) + .5;
28 }
29 for (int i = 0; i < n; i++) {
30 A *= x;
31 }
32 if (A != B) {
33 cout << "No solution\n";
34 } else {
35 cout << x << "\n";
36 }
37 return 0;
38 }
163: IQ test
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given
n numbers differs from the others. Bob observed that one number usually differs from the others in
evenness. Help Bob - to check his answers, he needs a program that among the given n numbers finds
one that is different in evenness.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 vector<int> a(n);
10 int cnt[2] {};
11 for (int i = 0; i < n; i++) {
12 cin >> a[i];
13 cnt[a[i] % 2] += 1;
14 }
15 for (int i = 0; i < n; i++) {
16 if (cnt[a[i] % 2] == 1) {
17 cout << i + 1 << "\n";
18 }
19 }
20 return 0;
21 }
Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly
and drew its plan: Bob’s office room is a rectangular room n m meters. Each square meter of the room
is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed
so, that its sides are parallel to the office walls. Bob doesn’t want to change or rearrange anything,
that’s why all the squares that will be occupied by the table should be initially free. Bob wants the new
table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the
maximum possible perimeter of a bargaining table for his office.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n, m;
8 cin >> n >> m;
9 vector<string> s(n);
10 for (int i = 0; i < n; i++) {
11 cin >> s[i];
12 }
13 int ans = 0;
14 for (int x1 = 0; x1 < n; x1++) {
15 for (int x2 = x1; x2 < n; x2++) {
16 int len = 0;
17 for (int i = 0; i < m; i++) {
18 bool ok = true;
19 for (int j = x1; j <= x2; j++) {
20 if (s[j][i] == '1') {
21 ok = false;
22 }
23 }
24 if (ok) {
25 len += 1;
26 ans = max(ans, (len + x2 - x1 + 1) * 2);
27 } else {
28 len = 0;
29 }
30 }
31 }
32 }
33 cout << ans << "\n";
34 return 0;
35 }
165: Triangle
At a geometry lesson Bob learnt that a triangle is called right-angled if it is nondegenerate and one
of its angles is right. Bob decided to draw such a triangle immediately: on a sheet of paper he drew
three points with integer coordinates, and joined them with segments of straight lines, then he showed
the triangle to Peter. Peter said that Bob’s triangle is not right-angled, but is almost right-angled: the
triangle itself is not right-angled, but it is possible to move one of the points exactly by distance 1 so,
that all the coordinates remain integer, and the triangle become right-angled. Bob asks you to help
him and find out if Peter tricks him. By the given coordinates of the triangle you should find out if it is
right-angled, almost right-angled, or neither of these.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 template<class T>
5 # struct Point;
6 template<class T>
7 T dot(Point<T> a, Point<T> b) {
8 return a.x * b.x + a.y * b.y;
9 }
10 template<class T>
11 T cross(Point<T> a, Point<T> b) {
12 return a.x * b.y - a.y * b.x;
13 }
14 template<class T>
15 T square(Point<T> p) {
16 return dot(p, p);
17 }
18 template<class T>
19 double length(Point<T> p) {
20 return sqrt(double(square(p)));
21 }
22 long double length(Point<long double> p) {
23 return sqrt(square(p));
24 }
25 template<class T>
26 # struct Line;
27 template<class T>
28 Point<T> rotate(Point<T> a) {
218 ps.pop_back();
219 ls.pop_back();
220 }
221 while (!ps.empty() && !pointOnLineLeft(ps[0], l)) {
222 ps.pop_front();
223 ls.pop_front();
224 }
225 if (cross(l.b - l.a, ls.back().b - ls.back().a) == 0) {
226 if (dot(l.b - l.a, ls.back().b - ls.back().a) > 0) {
227 if (!pointOnLineLeft(ls.back().a, l)) {
228 assert(ls.size() == 1);
229 ls[0] = l;
230 }
231 continue;
232 }
233 return {};
234 }
235 ps.push_back(lineIntersection(ls.back(), l));
236 ls.push_back(l);
237 }
238 while (!ps.empty() && !pointOnLineLeft(ps.back(), ls[0])) {
239 ps.pop_back();
240 ls.pop_back();
241 }
242 if (ls.size() <= 2) {
243 return {};
244 }
245 ps.push_back(lineIntersection(ls[0], ls.back()));
246 return vector(ps.begin(), ps.end());
247 }
248 const int dx[] = {0, 0, -1, 1};
249 const int dy[] = {-1, 1, 0, 0};
250 bool check(auto p) {
251 if (cross(p[1] - p[0], p[2] - p[0]) == 0) {
252 return false;
253 }
254 for (int i = 0; i < 3; i++) {
255 if (dot(p[(i + 1) % 3] - p[i], p[(i + 2) % 3] - p[i]) == 0) {
256 return true;
257 }
258 }
259 return false;
260 }
261 int main() {
262 ios::sync_with_stdio(false);
263 cin.tie(nullptr);
264 array<Point<int>, 3> p;
265 for (int i = 0; i < 3; i++) {
266 cin >> p[i].x >> p[i].y;
267 }
268 if (check(p)) {
269 cout << "RIGHT\n";
270 return 0;
271 }
272 for (int i = 0; i < 3; i++) {
273 for (int j = 0; j < 4; j++) {
274 auto q = p;
275 q[i].x += dx[j];
276 q[i].y += dy[j];
277 if (check(q)) {
278 cout << "ALMOST\n";
279 return 0;
280 }
281 }
282 }
283 cout << "NEITHER\n";
284 return 0;
285 }
You have an integer array a of length n. There are two kinds of operations you can make.
Insert an arbitrary positive integer x to any position of a (to the front, to the back, or between any two
consecutive elements). This operation costs d.
You want to make the final array a permutation of any positive length. Please output the minimum
cost of doing that. Note that you can make the array empty during the operations, but the final array
must contain at least one integer.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For
example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array),
and [1, 3, 4] is also not a permutation (n = 3 but there is 4 in the array).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, c, d;
6 cin >> n >> c >> d;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 sort(a.begin(), a.end());
12 i64 ans = 1LL * c * n + d;
13 int t = 0;
14 for (int i = 0; i < n; i++) {
15 if (i == 0 || a[i] != a[i - 1]) {
16 t += 1;
17 }
18 ans = min(ans, 1LL * c * n + 1LL * d * a[i] - 1LL * (c + d) * t);
19 }
20 cout << ans << "\n";
21 }
22 int main() {
23 ios::sync_with_stdio(false);
24 cin.tie(nullptr);
25 int t;
26 cin >> t;
27 while (t--) {
28 solve();
29 }
30 return 0;
31 }
While James is gone on business, Vesper takes her time and explores what the legendary Casino Royale
has to offer to people who are fond of competitive programming.
Her attention was grabbed by the very new “Pull Your Luck” roulette which functions in a pretty peculiar
way. The roulette’s wheel consists of n sectors number from 0 to n − 1. There is no ball and the winning
sector is determined by a static arrow pointing to one of the sectors. Sectors’ indexes go in the natural
order and the wheel always spins in the direction of indexes increment. That means that sector i + 1
goes right after sector i for all i from 0 to n − 2, and sector 0 goes right after sector n − 1.
After a bet is made, the player is allowed to pull the triggering handle herself and cause the wheel to
spin. If the player’s initial pull is made with the force equal to positive integer f , the wheel will spin
for f seconds. During the first second it will advance f sectors, the next second it will advance f − 1
sectors, then f − 2 sectors, and so on until it comes to a complete stop. After the wheel comes to a
complete stop, the sector which the arrow is pointing to is the winning one.
The roulette’s arrow currently points at sector x. Vesper knows that she can pull the handle with any
integer force from 1 to p inclusive. Note that it is not allowed to pull the handle with force 0, i. e. not
pull it all. The biggest prize is awarded if the winning sector is 0. Now Vesper wonders if she can make
sector 0 win by pulling the triggering handle exactly once?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, x, p;
6 cin >> n >> x >> p;
This is a complex version of the problem. This version has no additional restrictions on the number
k.
The chief wizard of the Wizengamot once caught the evil wizard Drahyrt, but the evil wizard has returned
and wants revenge on the chief wizard. So he stole spell s from his student Harry.
Dragirt, using ancient magic, can swap letters at a distance k or k + 1 in spell as many times as he wants.
In other words, Drahyrt can change letters in positions i and j in spell s if |i − j| = k or |i − j| = k + 1.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 string s, t;
8 cin >> s >> t;
9 int cnt[26] {};
10 for (int i = 0; i < n; i++) {
11 if (i - k < 0 && i + k >= n) {
12 if (s[i] != t[i]) {
13 cout << "NO\n";
14 return;
15 }
16 } else {
17 cnt[s[i] - 'a'] += 1;
18 cnt[t[i] - 'a'] -= 1;
19 }
20 }
21 for (int i = 0; i < 26; i++) {
22 if (cnt[i] != 0) {
23 cout << "NO\n";
24 return;
25 }
26 }
27 cout << "YES\n";
28 }
29 int main() {
30 ios::sync_with_stdio(false);
31 cin.tie(nullptr);
32 int t;
33 cin >> t;
34 while (t--) {
35 solve();
36 }
37 return 0;
38 }
The chief wizard of the Wizengamot once caught the evil wizard Drahyrt, but the evil wizard has returned
and wants revenge on the chief wizard. So he stole spell s from his student Harry.
Drahyrt, using ancient magic, can swap letters at a distance k or k + 1 in spell as many times as he
wants. In this version of the problem, you can swap letters at a distance of 3 or 4. In other words,
Drahyrt can change letters in positions i and j in spell s if |i − j| = 3 or |i − j| = 4.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 string s, t;
8 cin >> s >> t;
9 int cnt[26] {};
10 for (int i = 0; i < n; i++) {
11 if (i - k < 0 && i + k >= n) {
12 if (s[i] != t[i]) {
13 cout << "NO\n";
14 return;
15 }
16 } else {
17 cnt[s[i] - 'a'] += 1;
18 cnt[t[i] - 'a'] -= 1;
19 }
20 }
21 for (int i = 0; i < 26; i++) {
22 if (cnt[i] != 0) {
23 cout << "NO\n";
24 return;
25 }
26 }
27 cout << "YES\n";
28 }
29 int main() {
30 ios::sync_with_stdio(false);
31 cin.tie(nullptr);
32 int t;
33 cin >> t;
34 while (t--) {
35 solve();
36 }
37 return 0;
38 }
ChthollyNotaSeniorious received a special gift from AquaMoon: n binary arrays of length m. AquaMoon
tells him that in one operation, he can choose any two arrays and any position pos from 1 to m, and
swap the elements at positions pos in these arrays.
He is fascinated with this game, and he wants to find the minimum number of operations needed to
make the numbers of 1s in all arrays the same. He has invited you to participate in this interesting
game, so please try to find it!
If it is possible, please output specific exchange steps in the format described in the output section.
Otherwise, please output −1.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 int tot = 0;
8 vector a(n, vector<int>(m));
9 vector<int> sum(n);
10 for (int i = 0; i < n; i++) {
11 for (int j = 0; j < m; j++) {
12 cin >> a[i][j];
13 tot += a[i][j];
14 sum[i] += a[i][j];
15 }
16 }
17 if (tot % n != 0) {
18 cout << -1 << "\n";
19 return;
20 }
21 vector<tuple<int, int, int>> ans;
22 for (int j = 0; j < m; j++) {
23 vector<int> zero, one;
24 for (int i = 0; i < n; i++) {
25 if (a[i][j] == 0 && sum[i] < tot / n) {
26 zero.push_back(i);
27 }
28 if (a[i][j] == 1 && sum[i] > tot / n) {
29 one.push_back(i);
30 }
31 }
32 for (int k = 0; k < min(zero.size(), one.size()); k++) {
33 int i0 = zero[k];
34 int i1 = one[k];
35 a[i0][j] = 1;
36 a[i1][j] = 0;
37 sum[i0]++;
38 sum[i1]--;
39 ans.emplace_back(i0, i1, j);
40 }
41 }
42 cout << ans.size() << "\n";
43 for (auto [x, y, z] : ans) {
44 cout << x + 1 << " " << y + 1 << " " << z + 1 << "\n";
45 }
46 }
47 int main() {
48 ios::sync_with_stdio(false);
49 cin.tie(nullptr);
50 int t;
51 cin >> t;
52 while (t--) {
53 solve();
54 }
55 return 0;
56 }
constructive algorithms
Polycarp is designing a level for a game. The level consists of n segments on the number line, where
the i-th segment starts at the point with coordinate li and ends at the point with coordinate ri .
The player starts the level at the point with coordinate 0. In one move, they can move to any point
that is within a distance of no more than k. After their i-th move, the player must land within the i-th
segment, that is, at a coordinate x such that li ≤ x ≤ ri . This means:
After the first move, they must be inside the first segment (from l1 to r1 );
After the second move, they must be inside the second segment (from l2 to r2 );
...
After the n-th move, they must be inside the n-th segment (from ln to rn ).
The level is considered completed if the player reaches the n-th segment, following the rules described
above. After some thought, Polycarp realized that it is impossible to complete the level with some
values of k.
Polycarp does not want the level to be too easy, so he asks you to determine the minimum integer k
with which it is possible to complete the level.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> l(n), r(n);
8 for (int i = 0; i < n; i++) {
9 cin >> l[i] >> r[i];
10 }
11 int ans = *ranges::partition_point(ranges::iota_view(0, int(1E9) + 1),
12 [&](int k) {
13 int L = 0, R = 0;
14 for (int i = 0; i < n; i++) {
15 L -= k;
16 R += k;
17 L = max(L, l[i]);
18 R = min(R, r[i]);
19 if (L > R) {
20 return true;
21 }
22 }
23 return false;
24 });
25 cout << ans << "\n";
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
You are given a string s made up of characters A and B. Initially you have no coins. You can perform
two types of operations:
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 int ans = 0;
8 int n = s.size();
9 for (int i = 0, j = -1; i <= n; i++) {
10 if (i == n || s[i] == 'C') {
11 int min = n;
12 for (int x = j + 1, y = j; x <= i; x++) {
13 if (x < i && s[x] == 'A') {
14 ans++;
15 } else {
16 min = min(min, x - y - 1);
17 y = x;
18 }
19 }
20 ans -= min;
21 }
22 }
23 cout << ans << "\n";
24 }
25 int main() {
26 ios::sync_with_stdio(false);
27 cin.tie(nullptr);
28 int t;
29 cin >> t;
30 while (t--) {
31 solve();
32 }
33 return 0;
34 }
salyg1n gave Alice a set S of n distinct integers s1 , s2 , . . . , sn (0 ≤ si ≤ 109 ). Alice decided to play a
game with this set against Bob. The rules of the game are as follows:
In one move, Alice adds one number x (0 ≤ x ≤ 109 ) to the set S. The set S must not contain the
number x at the time of the move.
In one move, Bob removes one number y from the set S. The set S must contain the number y at the
time of the move. Additionally, the number y must be strictly smaller than the last number added by
Alice.
The game ends when Bob cannot make a move or after 2 · n + 1 moves (in which case Alice’s move will
be the last one).
The result of the game is MEX †(S) (S at the end of the game).
Alice aims to maximize the result, while Bob aims to minimize it.
Let R be the result when both players play optimally. In this problem, you play as Alice against the jury
program playing as Bob. Your task is to implement a strategy for Alice such that the result of the game
is always at least R.
† MEX of a set of integers c1 , c2 , . . . , ck is defined as the smallest non-negative integer x which does
not occur in the set c. For example, MEX({0, 1, 2, 4}) = 3.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> cnt(n + 1);
8 for (int i = 0; i < n; i++) {
9 int x;
10 cin >> x;
11 if (x <= n) {
12 cnt[x]++;
13 }
14 }
15 int mex = 0;
16 while (cnt[mex]) {
17 mex++;
18 }
19 while (true) {
20 cout << mex << endl;
21 int y;
22 cin >> y;
23 if (y == -1) {
24 break;
25 }
26 mex = y;
27 }
28 }
29 int main() {
30 ios::sync_with_stdio(false);
31 cin.tie(nullptr);
32 int t;
33 cin >> t;
34 while (t--) {
35 solve();
36 }
37 return 0;
38 }
Madoka as a child was an extremely capricious girl, and one of her favorite pranks was drawing on
her wall. According to Madoka’s memories, the wall was a table of n rows and m columns, consisting
only of zeroes and ones. The coordinate of the cell in the i-th row and the j-th column (1 ≤ i ≤ n,
1 ≤ j ≤ m) is (i, j).
One day she saw a picture “Mahou Shoujo Madoka Magica” and decided to draw it on her wall. Initially,
the Madoka’s table is a table of size n × m filled with zeroes. Then she applies the following operation
any number of times:
Madoka selects any rectangular subtable of the table and paints it in a chess coloring (the upper left
corner of the subtable always has the color 0). Note that some cells may be colored several times. In
this case, the final color of the cell is equal to the color obtained during the last repainting.
For better understanding of the statement, we recommend you to read the explanation of the first
test.
Help Madoka and find some sequence of no more than n · m operations that allows you to obtain the
picture she wants, or determine that this is impossible.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<string> s(n);
There is an n × m board divided into cells. There are also some dominoes on this board. Each domino
covers two adjacent cells (that is, two cells that share a side), and no two dominoes overlap.
Piet thinks that this board is too boring and it needs to be painted. He will paint the cells of the
dominoes black and white. He calls the painting beautiful if all of the following conditions hold:
for each domino, one of its cells is painted white and the other is painted black;
for each row, the number of black cells in this row equals the number of white cells in this row;
for each column, the number of black cells in this column equals the number of white cells in this
column.
Note that the cells that are not covered by dominoes are not painted at all, they are counted as neither
black nor white.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<string> s(n);
8 for (int i = 0; i < n; i++) {
9 cin >> s[i];
10 }
11 vector<vector<array<int, 2>>> adj(n + m);
12 for (int i = 0; i < n; i++) {
13 for (int j = 0; j < m; j++) {
14 if (s[i][j] == 'U') {
15 adj[i].push_back({i + 1, j});
16 adj[i + 1].push_back({i, j});
17 }
18 if (s[i][j] == 'L') {
19 adj[n + j].push_back({n + j + 1, i});
20 adj[n + j + 1].push_back({n + j, i});
21 }
22 }
23 }
24 for (int i = 0; i < n + m; i++) {
25 if (adj[i].size() % 2) {
26 cout << "-1\n";
27 return;
28 }
29 }
30 auto dfs = [&](auto self, int x, int y, int z) -> void {
31 while (!adj[x].empty()) {
32 auto [i, j] = adj[x].back();
33 adj[x].pop_back();
34 if ((x < n ? s[x][j] : s[j][x - n]) == '.') {
35 continue;
36 }
37 if (x < n) {
38 s[x][j] = s[i][j] = '.';
39 } else {
40 s[j][x - n] = s[j][i - n] = '.';
41 }
42 self(self, i, x, j);
43 }
44 if (y != -1) {
45 if (x < n) {
46 s[x][z] = 'W';
47 s[y][z] = 'B';
48 } else {
49 s[z][x - n] = 'W';
50 s[z][y - n] = 'B';
51 }
52 }
53 };
54 for (int i = 0; i < n + m; i++) {
Recently, Kolya found out that a new movie theatre is going to be opened in his city soon, which will
show a new movie every day for n days. So, on the day with the number 1 ≤ i ≤ n, the movie theatre
will show the premiere of the i-th movie. Also, Kolya found out the schedule of the movies and assigned
the entertainment value to each movie, denoted by ai .
However, the longer Kolya stays without visiting a movie theatre, the larger the decrease in entertain-
ment value of the next movie. That decrease is equivalent to d · cnt, where d is a predetermined value
and cnt is the number of days since the last visit to the movie theatre. It is also known that Kolya
managed to visit another movie theatre a day before the new one opened - the day with the number 0.
So if we visit the movie theatre the first time on the day with the number i, then cnt - the number of
days since the last visit to the movie theatre will be equal to i.
For example, if d = 2 and a = [3, 2, 5, 4, 6], then by visiting movies with indices 1 and 3, cnt value
for the day 1 will be equal to 1 − 0 = 1 and cnt value for the day 3 will be 3 − 1 = 2, so the total
entertainment value of the movies will be a1 − d · 1 + a3 − d · 2 = 3 − 2 · 1 + 5 − 2 · 2 = 2.
Unfortunately, Kolya only has time to visit at most m movies. Help him create a plan to visit the cinema
in such a way that the total entertainment value of all the movies he visits is maximized.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m, d;
6 cin >> n >> m >> d;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 i64 ans = 0;
12 i64 sum = 0;
13 priority_queue<int, vector<int>, greater<>> h;
14 for (int i = 0; i < n; i++) {
15 if (a[i] > 0) {
16 h.push(a[i]);
17 sum += a[i];
18 }
19 if (h.size() > m) {
20 sum -= h.top();
21 h.pop();
22 }
23 ans = max(ans, sum - 1LL * (i + 1) * d);
24 }
25 cout << ans << "\n";
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
The row-major order of an r × c grid of characters A is the string obtained by concatenating all the
rows, i.e.
A11 A12 . . . A1c A21 A22 . . . A2c . . . Ar1 Ar2 . . . Arc .
A grid of characters A is bad if there are some two adjacent cells (cells sharing an edge) with the same
character.
You are given a positive integer n. Consider all strings s consisting of only lowercase Latin letters such
that they are not the row-major order of any bad grid. Find any string with the minimum number of
You have a sequence a1 , a2 , . . . , an of length n, each element of which is either 0 or 1, and a sequence
b, which is initially empty.
You are going to perform n operations. On each of them you will increase the length of b by 1.
On the i-th operation you choose an integer p between 0 and i − 1. You insert 0 in the sequence b on
position p + 1 (after the first p elements), and then you invert the first p elements of b.
More formally: let’s denote the sequence b before the i-th (1 ≤ i ≤ n) operation as b1 , b2 , . . . , bi−1 .
On the i-th operation you choose an integer p between 0 and i − 1 and replace b with
b1 , b2 , . . . , bp , 0, bp+1 , bp+2 , . . . , bi−1 . Here, x denotes the binary inversion. Hence, 0 = 1 and
1 = 0.
Determine if there exists a sequence of operations that makes b equal to a. If such sequence of opera-
tions exists, find it.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 if (a.back() != 0) {
12 cout << "NO\n";
13 return;
14 }
15 cout << "YES\n";
16 vector<int> ans;
17 for (int i = 0, j = -1; i < n; i++) {
18 if (a[i] == 0) {
19 ans.push_back(i - j - 1);
20 for (int k = j + 1; k < i; k++) {
21 ans.push_back(0);
22 }
23 j = i;
24 }
25 }
26 reverse(ans.begin(), ans.end());
27 for (int i = 0; i < n; i++) {
28 cout << ans[i] << " \n"[i == n - 1];
29 }
30 }
31 int main() {
32 ios::sync_with_stdio(false);
33 cin.tie(nullptr);
34 int t;
35 cin >> t;
36 while (t--) {
37 solve();
38 }
39 return 0;
40 }
You are given integers n and m. Fill an n by m grid with the integers 1 through n · m, in such a way that
for any two adjacent cells in the grid, the absolute difference of the values in those cells is not a prime
number. Two cells in the grid are considered adjacent if they share a side.
It can be shown that under the given constraints, there is always a solution.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector a(n, vector<int>(m));
8 if (m % 2 == 0) {
9 for (int i = 0; i < n; i++) {
10 for (int j = 0; j < m; j++) {
11 a[i][j] = i * m + j + 1;
12 }
13 }
14 } else {
15 for (int i = 0; i < n; i++) {
16 for (int j = 0; j < m; j++) {
17 a[i][j] = i * m + (i + j) % m + 1;
18 }
19 }
20 }
21 for (int i = 0; i < n; i++) {
22 for (int j = 0; j < m; j++) {
23 cout << a[i][j] << " \n"[j == m - 1];
24 }
25 }
26 }
27 int main() {
28 ios::sync_with_stdio(false);
29 cin.tie(nullptr);
30 int t;
31 cin >> t;
32 while (t--) {
33 solve();
34 }
35 return 0;
36 }
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic
expression by inserting characters “1” and “+” between the original characters of the sequence. For
example:
the bracket sequences “()()” and “(())” are regular (the resulting expressions are: “(1)+(1)” and
“((1+1)+1)”);
if the order of the characters in this sequence is reversed, it becomes a regular bracket sequence.
For example, the bracket sequences “()()”, “(())”, “)))(((”, “))()((” are beautiful.
You are given a bracket sequence s. You have to color it in such a way that:
for every color, there is at least one bracket colored into that color;
for every color, if you write down the sequence of brackets having that color in the order they appear,
you will get a beautiful bracket sequence.
Color the given bracket sequence s into the minimum number of colors according to these constraints,
or report that it is impossible.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 int c = count(s.begin(), s.end(), '(');
10 if (2 * c != n) {
11 cout << -1 << "\n";
12 return;
13 }
14 vector<int> ans(n, 2);
15 vector<int> a;
16 for (int i = 0; i < n; i++) {
17 if (s[i] == '(') {
18 a.push_back(i);
19 } else if (!a.empty()) {
20 ans[i] = 1;
21 ans[a.back()] = 1;
22 a.pop_back();
23 }
24 }
25 if (count(ans.begin(), ans.end(), 2)) {
26 a.clear();
27 ans.assign(n, 2);
28 for (int i = 0; i < n; i++) {
29 if (s[i] == ')') {
30 a.push_back(i);
31 } else if (!a.empty()) {
32 ans[i] = 1;
33 ans[a.back()] = 1;
34 a.pop_back();
35 }
36 }
37 }
38 cout << *max_element(ans.begin(), ans.end()) << "\n";
39 for (int i = 0; i < n; i++) {
40 cout << ans[i] << " \n"[i == n - 1];
41 }
42 }
43 int main() {
44 ios::sync_with_stdio(false);
45 cin.tie(nullptr);
46 int t;
47 cin >> t;
48 while (t--) {
49 solve();
50 }
51 return 0;
52 }
181: Flipper
A permutation is an array consisting of n distinct integers from 1 to n in any order. For example,
{2, 3, 1, 5, 4} is a permutation, while {1, 2, 2} is not (since 2 appears twice), and {1, 3, 4} is also not a
permutation (as n = 3, but the array contains 4).
To the permutation p, you need to apply the following operation exactly once:
Then you swap the prefix and suffix: [r + 1, n] and [1, l − 1] (note that these segments may be empty).
For example, given n = 5, p = {2, 3, 1, 5, 4}, if you choose the segment [l = 2, r = 3], after reversing
the segment p = {2, 1, 3, 5, 4}, then you swap the segments [4, 5] and [1, 1]. Thus, p = {5, 4, 1, 3, 2}. It
can be shown that this is the maximum possible result for the given permutation.
You need to output the lexicographically maximum permutation that can be obtained by applying the
operation described exactly once.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> p(n);
8 for (int i = 0; i < n; i++) {
9 cin >> p[i];
10 }
11 vector ans(p.rbegin(), p.rend());
12 int x = find(p.begin(), p.end(), n) - p.begin();
13 if (x == 0 && n > 1) {
14 x = find(p.begin(), p.end(), n - 1) - p.begin();
15 }
16 for (int i = 0; i < n; i++) {
17 auto q = p;
18 reverse(q.begin() + i, q.end());
19 rotate(q.begin(), q.begin() + i, q.end());
20 ans = max(ans, q);
21 }
22 for (int i = 0; i < x; i++) {
23 auto q = p;
24 reverse(q.begin() + i, q.begin() + x);
25 rotate(q.begin(), q.begin() + i, q.end());
26 rotate(q.begin(), q.begin() + x - i, q.end() - i);
27 ans = max(ans, q);
28 }
29 for (int i = 0; i < n; i++) {
30 cout << ans[i] << " \n"[i == n - 1];
31 }
32 }
33 int main() {
34 ios::sync_with_stdio(false);
35 cin.tie(nullptr);
36 int t;
37 cin >> t;
38 while (t--) {
39 solve();
40 }
41 return 0;
42 }
Not so long ago as a result of combat operations the main Berland place of interest - the magic
clock - was damaged. The cannon’s balls made several holes in the clock, that’s why the residents
are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane,
where the origin corresponds to the clock center. The clock was painted two colors as is shown in the
picture:
The picture shows only the central part of the clock. This coloring naturally extends to infinity.
The balls can be taken to be points on the plane. Your task is to find the color of the area, damaged by
the given ball.
All the points located on the border of one of the areas have to be considered painted black.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int x, y;
8 cin >> x >> y;
9 if (!x || !y) {
10 cout << "black\n";
11 } else {
12 int z = x * x + y * y;
13 int w = sqrt(z);
14 if (w * w == z || ((w % 2) ^ (x < 0) ^ (y < 0)) == 0) {
15 cout << "black\n";
16 } else {
17 cout << "white\n";
18 }
19 }
20 return 0;
21 }
Li Ming and Li Hua are playing a game. Li Hua has a chessboard of size n × m. Denote (r, c) (1 ≤ r ≤
n, 1 ≤ c ≤ m) as the cell on the r-th row from the top and on the c-th column from the left. Li Ming put
a king on the chessboard and Li Hua needs to guess its position.
Li Hua can ask Li Ming no more than 3 questions. In each question, he can choose a cell and ask the
minimum steps needed to move the king to the chosen cell. Each question is independent, which
means the king doesn’t actually move.
A king can move from (x, y) to (x′ , y ′ ) if and only if max{|x − x′ |, |y − y ′ |} = 1 (shown in the following
picture).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int query(int r, int c) {
5 cout << "? " << r << " " << c << endl;
6 int ans;
7 cin >> ans;
8 return ans;
9 }
10 void solve() {
11 int n, m;
12 cin >> n >> m;
13 int a = query(1, 1);
14 int b = query(n, m);
15 int x, y;
16 if (a + b == n - 1) {
17 x = 1 + a;
18 y = 1 + query(x, 1);
19 } else if (a + b == m - 1) {
20 y = 1 + a;
21 x = 1 + query(1, y);
22 } else {
23 if (1 + a <= n && m - b >= 1 && query(1 + a, m - b) == 0) {
24 x = 1 + a;
25 y = m - b;
26 } else {
27 x = n - b;
28 y = 1 + a;
29 }
30 }
31 cout << "! " << x << " " << y << endl;
32 }
33 int main() {
34 ios::sync_with_stdio(false);
35 cin.tie(nullptr);
36 int t;
37 cin >> t;
38 while (t--) {
39 solve();
40 }
41 return 0;
42 }
Suppose you have n boxes. The i-th box contains infinitely many balls of color i. Sometimes you need
to get a ball with some specific color; but you’re too lazy to do it yourself.
You have bought two robots to retrieve the balls for you. Now you have to program them. In order to
program the robots, you have to construct two lists [a1 , a2 , . . . , ak ] and [b1 , b2 , . . . , bn−k ], where the
list a represents the boxes assigned to the first robot, and the list b represents the boxes assigned to
the second robot. Every integer from 1 to n must be present in exactly one of these lists.
When you request a ball with color x, the robots work as follows. Each robot looks through the boxes
that were assigned to that robot, in the order they appear in the list. The first robot spends s1 seconds
analyzing the contents of a box; the second robot spends s2 . As soon as one of the robots finds the
box with balls of color x (and analyzes its contents), the search ends. The search time is the number of
seconds from the beginning of the search until one of the robots finishes analyzing the contents of the
x-th box. If a robot analyzes the contents of all boxes assigned to it, it stops searching.
For example, suppose s1 = 2, s2 = 3, a = [4, 1, 5, 3, 7], b = [2, 6]. If you request a ball with color 3, the
following happens:
initially, the first robot starts analyzing the box 4, and the second robot starts analyzing the box 2;
at the end of the 2-nd second, the first robot finishes analyzing the box 4. It is not the box you need, so
the robot continues with the box 1;
at the end of the 3-rd second, the second robot finishes analyzing the box 2. It is not the box you need,
so the robot continues with the box 6;
at the end of the 4-th second, the first robot finishes analyzing the box 1. It is not the box you need, so
the robot continues with the box 5;
at the end of the 6-th second, the first robot finishes analyzing the box 5. It is not the box you need, so
the robot continues with the box 3. At the same time, the second robot finishes analyzing the box 6. It
is not the box you need, and the second robot has analyzed all the boxes in its list, so that robot stops
searching;
at the end of the 8-th second, the first robot finishes analyzing the box 3. It is the box you need, so the
search ends;
You know that you are going to request a ball of color 1 r1 times, a ball of color 2 r2 times, and so on.
You want to construct the lists a and b for the robots in such a way that the total search time over all
requests is the minimum possible.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, s1, s2;
6 cin >> n >> s1 >> s2;
7 vector<int> r(n);
8 for (int i = 0; i < n; i++) {
9 cin >> r[i];
10 }
11 vector<int> p(n);
12 iota(p.begin(), p.end(), 0);
13 sort(p.begin(), p.end(), [&](int i, int j) {
14 return r[i] > r[j];
15 });
16 vector<int> a, b;
17 for (auto i : p) {
18 if ((a.size() + 1) * s1 < (b.size() + 1) * s2) {
19 a.push_back(i + 1);
20 } else {
21 b.push_back(i + 1);
22 }
23 }
24 cout << a.size();
25 for (auto x : a) {
26 cout << " " << x;
27 }
28 cout << "\n";
29 cout << b.size();
30 for (auto x : b) {
31 cout << " " << x;
32 }
33 cout << "\n";
34 }
35 int main() {
36 ios::sync_with_stdio(false);
37 cin.tie(nullptr);
38 int t;
39 cin >> t;
40 while (t--) {
41 solve();
42 }
43 return 0;
44 }
The girl Umka loves to travel and participate in math olympiads. One day she was flying by plane to
the next olympiad and out of boredom explored a huge checkered sheet of paper.
1, n = 0;
Denote the n-th Fibonacci number as Fn = 1, n = 1;
Fn−2 + Fn−1 , n ≥ 2.
A checkered rectangle with a height of Fn and a width of Fn+1 is called a Fibonacci rectangle of order
n.
Umka has a Fibonacci rectangle of order n. Someone colored a cell in it at the intersection of the row x
and the column y.
It is necessary to cut this rectangle exactly into n + 1 squares in such way that
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 i64 F[50];
5 void solve() {
6 int n;
7 i64 x, y;
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 if (a == vector(n, 0)) {
12 cout << "NO\n";
13 return;
14 }
15 cout << "YES\n";
16 i64 s = 0;
17 int i = 0, j = n - 1;
18 sort(a.begin(), a.end());
19 vector<int> ans;
20 while (i <= j) {
21 if (s <= 0) {
22 s += a[j];
23 ans.push_back(a[j--]);
24 } else {
25 s += a[i];
26 ans.push_back(a[i++]);
27 }
28 }
29 for (int i = 0; i < n; i++) {
30 cout << ans[i] << " \n"[i == n - 1];
31 }
32 }
33 int main() {
34 ios::sync_with_stdio(false);
35 cin.tie(nullptr);
36 int t;
37 cin >> t;
38 while (t--) {
39 solve();
40 }
41 return 0;
42 }
For an array a = [a1 , a2 , . . . , an ], let’s denote its subarray a[l, r] as the array [al , al+1 , . . . , ar ].
a[1, 1] = [1];
a[2, 2] = [−3];
a[3, 3] = [1].
You are given two integers n and k. Construct an array a consisting of n integers such that:
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 int x = 0;
8 while ((x + 1) * (x + 2) / 2 <= k) {
9 x += 1;
10 }
11 vector<int> a(n);
12 for (int i = 0; i < n; i++) {
13 if (i < x) {
14 a[i] = 2;
15 } else if (i == x) {
16 a[i] = -2 * x - 1 + 2 * (k - x * (x + 1) / 2);
17 } else {
18 a[i] = -1000;
19 }
20 cout << a[i] << " \n"[i == n - 1];
21 }
22 }
23 int main() {
24 ios::sync_with_stdio(false);
25 cin.tie(nullptr);
26 int t;
27 cin >> t;
28 while (t--) {
29 solve();
30 }
31 return 0;
32 }
For some positive integer m, YunQian considers an array q of 2m (possibly negative) integers good, if
and only if for every possible subsequence of q that has length m, the product of the m elements in
the subsequence is equal to the sum of the m elements that are not in the subsequence. Formally, let
U = {1, 2, . . . , 2m}. For all sets S ⊆ U such that |S| = m, qi .
Q P
qi =
i∈S i∈U \S
k
Define the distance between two arrays a and b both of length k to be |ai − bi |.
P
i=1
Find the minimum distance between p and q over all good arrays q of length 2n. It can be shown for all
positive integers n, at least one good array exists. Note that you are not required to construct the array
q that achieves this minimum distance.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> p(2 * n);
8 for (int i = 0; i < 2 * n; i++) {
9 cin >> p[i];
10 }
11 if (n == 1) {
12 cout << abs(p[0] - p[1]) << "\n";
13 return;
14 }
15 i64 ans = 0;
16 for (int i = 0; i < 2 * n; i++) {
17 ans += abs(p[i]);
18 }
19 if (n == 2) {
20 i64 res = 0;
21 for (int i = 0; i < 2 * n; i++) {
22 res += abs(p[i] - 2);
23 }
24 ans = min(ans, res);
25 }
26 if (n % 2 == 0) {
27 i64 res = 0;
28 for (int i = 0; i < 2 * n; i++) {
29 res += abs(p[i] + 1);
30 }
31 for (int i = 0; i < 2 * n; i++) {
32 ans = min(ans, res - abs(p[i] + 1) + abs(p[i] - n));
33 }
34 }
35 cout << ans << "\n";
36 }
37 int main() {
38 ios::sync_with_stdio(false);
39 cin.tie(nullptr);
40 int t;
41 cin >> t;
42 while (t--) {
43 solve();
44 }
45 return 0;
46 }
ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n n magic grid on
the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty,
and to enter Udayland, they need to fill a positive integer into the empty cell.
Chris tried filling in random numbers but it didn’t work. ZS the Coder realizes that they need to fill in a
positive integer such that the numbers in the grid form a magic square. This means that he has to fill in
a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (),
and the two long diagonals of the grid (the main diagonal - and the secondary diagonal - ) are equal.
Chris doesn’t know what number to fill in. Can you help Chris find the correct positive integer to fill in
or determine that it is impossible?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 vector a(n, vector<i64>(n));
10 int r, c;
11 for (int i = 0; i < n; i++) {
Kirill wants to weave the very beautiful blanket consisting of n × m of the same size square patches of
some colors. He matched some non-negative integer to each color. Thus, in our problem, the blanket
can be considered a B matrix of size n × m consisting of non-negative integers.
Kirill considers that the blanket is very beautiful, if for each submatrix A of size 4 × 4 of the matrix B is
true:
Kirill asks you to help her weave a very beautiful blanket, and as colorful as possible!
Your task is to generate a matrix B of size n × m, which corresponds to a very beautiful blanket and in
which the number of different numbers maximized.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 cout << n * m << "\n";
8 for (int i = 0; i < n; i++) {
9 for (int j = 0; j < m; j++) {
10 cout << (i << 10) + j << " \n"[j == m - 1];
11 }
12 }
13 }
14 int main() {
15 ios::sync_with_stdio(false);
16 cin.tie(nullptr);
17 int t;
18 cin >> t;
19 while (t--) {
20 solve();
21 }
22 return 0;
23 }
dp
Keksic keeps getting left on seen by Anji. Through a mutual friend, he’s figured out that Anji really likes
binary trees and decided to solve her problem in order to get her attention.
Anji has given Keksic a binary tree with n vertices. Vertex 1 is the root and does not have a parent. All
other vertices have exactly one parent. Each vertex can have up to 2 children, a left child, and a right
child. For each vertex, Anji tells Keksic index of both its left and its right child or tells him that they do
not exist.
Additionally, each of the vertices has a letter si on it, which is either ‘U’, ‘L’ or ‘R’.
Keksic begins his journey on the root, and in each move he does the following:
If the letter on his current vertex is ‘U’, he moves to its parent. If it doesn’t exist, he does nothing.
If the letter on his current vertex is ‘L’, he moves to its left child. If it doesn’t exist, he does nothing.
If the letter on his current vertex is ‘R’, he moves to its right child. If it doesn’t exist, he does nothing.
You are interested in the minimal number of operations he needs to do before his journey, such that
when he starts his journey, he will reach a leaf at some point. A leaf is a vertex that has no children. It
does not matter which leaf he reaches. Note that it does not matter whether he will stay in the leaf, he
just needs to move to it. Additionally, note that it does not matter how many times he needs to move
before reaching a leaf.
Help Keksic solve Anji’s tree so that he can win her heart, and make her come to aak.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 vector<int> l(n), r(n);
10 for (int i = 0; i < n; i++) {
11 cin >> l[i] >> r[i];
12 l[i]--, r[i]--;
13 }
14 auto dfs = [&](auto self, int x) -> int {
15 if (l[x] == -1 && r[x] == -1) {
16 return 0;
17 }
18 int ans = n;
19 if (l[x] != -1) {
20 ans = self(self, l[x]) + (s[x] != 'L');
21 }
22 if (r[x] != -1) {
23 ans = min(ans, self(self, r[x]) + (s[x] != 'R'));
24 }
25 return ans;
26 };
27 int ans = dfs(dfs, 0);
28 cout << ans << "\n";
29 }
30 int main() {
31 ios::sync_with_stdio(false);
32 cin.tie(nullptr);
33 int t;
34 cin >> t;
35 while (t--) {
36 solve();
37 }
38 return 0;
39 }
A sequence is called beautiful if it has the form of a series of blocks, each starting with its length, i.e., first
comes the length of the block, and then its elements. For example, the sequences [3, 3, 4, 5, 2, 6, 1]
and [1, 8, 4, 5, 2, 6, 1] are beautiful (different blocks are colored differently), while [1], [1, 4, 3],
[3, 2, 1] are not.
In one operation, you can remove any element from the sequence. What is the minimum number of
operations required to make the given sequence beautiful?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector<int> dp(n + 1, n);
12 dp[n] = 0;
13 for (int i = n - 1; i >= 0; i--) {
14 dp[i] = dp[i + 1] + 1;
15 if (i + a[i] < n) {
Alice and Bob are playing a game. They have a permutation p of size n (a permutation of size n is an
array of size n where each element from 1 to n occurs exactly once). They also have a chip, which can
be placed on any element of the permutation.
Alice and Bob make alternating moves: Alice makes the first move, then Bob makes the second move,
then Alice makes the third move, and so on. During the first move, Alice chooses any element of the
permutation and places the chip on that element. During each of the next moves, the current player
has to move the chip to any element that is simultaneously to the left and strictly less than the current
element (i. e. if the chip is on the i-th element, it can be moved to the j-th element if j < i and pj < pi ).
If a player cannot make a move (it is impossible to move the chip according to the rules of the game),
that player wins the game.
Let’s say that the i-th element of the permutation is lucky if the following condition holds:
if Alice places the chip on the i-th element during her first move, she can win the game no matter how
Bob plays (i. e. she has a winning strategy).
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
Alchemist Nastya loves mixing potions. There are a total of n types of potions, and one potion of type i
can be bought for ci coins.
Any kind of potions can be obtained in no more than one way, by mixing from several others. The
potions used in the mixing process will be consumed. Moreover, no potion can be obtained from itself
through one or more mixing processes.
1 ≤ i ≤ n, the minimum number of coins she needs to spend to obtain a potion of type i next.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> c(n);
8 for (int i = 0; i < n; i++) {
9 cin >> c[i];
10 }
11 vector<bool> have(n);
12 for (int i = 0; i < k; i++) {
13 int x;
14 cin >> x;
15 x--;
16 have[x] = true;
17 }
18 vector<bool> vis(n);
19 vector<vector<int>> ing(n);
20 for (int i = 0; i < n; i++) {
21 int m;
22 cin >> m;
23 while (m--) {
24 int x;
25 cin >> x;
26 x--;
27 ing[i].push_back(x);
28 }
29 }
30 auto rec = [&](auto self, int x) -> int {
31 if (vis[x]) {
32 return c[x];
33 }
34 if (have[x]) {
35 c[x] = 0;
36 }
37 if (!ing[x].empty()) {
38 i64 res = 0;
39 for (auto y : ing[x]) {
40 res += self(self, y);
41 }
42 c[x] = min(1LL * c[x], res);
43 }
44 vis[x] = true;
45 return c[x];
46 };
47 for (int i = 0; i < n; i++) {
48 cout << rec(rec, i) << " \n"[i == n - 1];
49 }
50 }
51 int main() {
52 ios::sync_with_stdio(false);
53 cin.tie(nullptr);
54 int t;
55 cin >> t;
56 while (t--) {
57 solve();
58 }
59 return 0;
60 }
Monocarp finally got the courage to register on ForceCoders. He came up with a handle but is still
thinking about the password.
He wants his password to be as strong as possible, so he came up with the following criteria:
the password should not appear in the password database (given as a string s) as a subsequence (not
necessarily contiguous).
Monocarp also came up with two strings of length m: l and r, both consisting only of digits from 0 to 9.
He wants the i-th digit of his password to be between li and ri , inclusive.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 int m;
8 cin >> m;
9 string l, r;
10 cin >> l >> r;
11 int p = 0;
12 for (int i = 0; i < m; i++) {
13 int q = p;
14 for (char x = l[i]; x <= r[i]; x++) {
15 if (s.find(x, p) == -1) {
16 cout << "YES\n";
17 return;
18 }
19 q = max(q, int(s.find(x, p)) + 1);
20 }
21 p = q;
22 }
23 cout << "NO\n";
24 }
25 int main() {
26 ios::sync_with_stdio(false);
27 cin.tie(nullptr);
28 int t;
29 cin >> t;
30 while (t--) {
31 solve();
32 }
33 return 0;
34 }
Tenzing has n balls arranged in a line. The color of the i-th ball from the left is ai .
remove ai , ai+1 , . . . , aj from the array (and decrease the indices of all elements to the right of aj by
j − i + 1).
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 a[i]--;
11 }
12 vector<int> dp(n + 1), f(n, -1E9);
13 for (int i = 0; i < n; i++) {
14 dp[i + 1] = max(dp[i], f[a[i]] + i + 1);
15 f[a[i]] = max(f[a[i]], dp[i] - i);
16 }
17 cout << dp[n] << "\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
Copil Copac is given a list of n − 1 edges describing a tree of n vertices. He decides to draw it using the
following algorithm:
Step 1: For every edge in the input, in order: if the edge connects an already drawn vertex u to an
undrawn vertex v, he will draw the undrawn vertex v and the edge. After checking every edge, go to
step 2.
Step 2: If all the vertices are drawn, terminate the algorithm. Else, go to step 1.
The number of readings is defined as the number of times Copil Copac performs step 1.
Find the number of readings needed by Copil Copac to draw the tree.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<vector<pair<int, int>>> adj(n);
8 vector<int> f(n), e(n);
9 e[0] = n;
10 for (int i = 0; i < n - 1; i++) {
11 int u, v;
12 cin >> u >> v;
13 u--, v--;
14 adj[u].emplace_back(v, i);
15 adj[v].emplace_back(u, i);
16 }
17 function<void(int, int)> dfs = [&](int x, int p) {
18 for (auto [y, i] : adj[x]) {
19 if (y == p) {
20 continue;
21 }
22 e[y] = i;
23 f[y] = f[x] + (i < e[x]);
24 dfs(y, x);
25 }
26 };
27 dfs(0, -1);
28 auto ans = *max_element(f.begin(), f.end());
29 cout << ans << "\n";
30 }
31 int main() {
32 ios::sync_with_stdio(false);
33 cin.tie(nullptr);
34 int t;
35 cin >> t;
36 while (t--) {
37 solve();
38 }
39 return 0;
40 }
There are n knights sitting at the Round Table at an equal distance from each other. Each of them is
either in a good or in a bad mood.
Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate
if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be
located. Otherwise, the next month will bring misfortunes.
A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem
we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.
On a picture below some examples of such polygons are present. Green points mean knights in a good
mood. Red points mean ones in a bad mood.
King Arthur knows the knights’ moods. Help him find out if the next month will be fortunate or not.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 vector<int> a(n);
10 for (int i = 0; i < n; i++) {
11 cin >> a[i];
12 }
13 vector<bool> check(n+1);
14 for (int i = 3; i <= n; i++) {
15 if (check[i]) {
16 continue;
17 }
18 if (n % i) {
19 continue;
20 }
21 for (int j = i; j <= n; j += i) {
22 check[j] = true;
23 }
24 for (int k = 0; k < n/i; k++) {
25 bool ok = true;
26 for (int x = k; x < n; x += n/i) {
27 if (!a[x]) {
28 ok = false;
29 }
30 }
31 if (ok) {
32 cout << "YES\n";
33 return 0;
34 }
35 }
36 }
37 cout << "NO\n";
38 return 0;
39 }
Anfisa the monkey learns to type. She is yet unfamiliar with the “space” key and can only type in
lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great
to divide what she has written into k lines not shorter than a and not longer than b, for the text to
resemble human speech more. Help Anfisa.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int k, a, b;
8 cin >> k >> a >> b;
9 string s;
10 cin >> s;
11 int n = s.size();
12 if (n < a * k || n > b * k) {
13 cout << "No solution\n";
14 return 0;
15 }
16 for (int i = 0, j = 0; i < k; i++) {
17 int t = min(b, n - j - (k-i-1) * a);
18 cout << s.substr(j, t) << "\n";
19 j += t;
20 }
21 return 0;
22 }
In Japan, the number 4 reads like death, so Bob decided to build a live sequence. Living sequence a con-
tains all natural numbers that do not contain the digit 4. a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, . . .].
For example, the number 1235 is part of the sequence a, but the numbers 4321, 443 are not part of the
sequence a.
Bob realized that he does not know how to quickly search for a particular number by the position k in
the sequence, so he asks for your help.
For example, if Bob wants to find the number at position k = 4 (indexing from 1), you need to answer
ak = 5.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 i64 n;
6 cin >> n;
7 string s;
8 while (n) {
9 int x = n % 9;
10 s += '0' + (x < 4 ? x : x + 1);
11 n /= 9;
12 }
13 reverse(s.begin(), s.end());
14 cout << s << "\n";
15 }
16 int main() {
17 ios::sync_with_stdio(false);
18 cin.tie(nullptr);
19 int t;
20 cin >> t;
21 while (t--) {
22 solve();
23 }
24 return 0;
25 }
Vasiliy is fond of solving different tasks. Today he found one he wasn’t able to solve himself, so he asks
you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexico-
graphical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he
is allowed to do is to reverse any of them (first character becomes last, second becomes one before
last and so on).
To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount
of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if
none of them is a prefix of the other and at the first position where they differ character in A is smaller
than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence
being sorted lexicographically.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 constexpr i64 inf = 1E18;
5 int main() {
6 ios::sync_with_stdio(false);
7 cin.tie(nullptr);
8 int n;
9 cin >> n;
10 vector<int> c(n);
11 for (int i = 0; i < n; i++) {
12 cin >> c[i];
13 }
14 vector<array<string, 2>> s(n);
15 for (int i = 0; i < n; i++) {
16 cin >> s[i][0];
17 s[i][1] = string(s[i][0].rbegin(), s[i][0].rend());
18 }
19 array<i64, 2> dp{0, c[0]};
20 for (int i = 1; i < n; i++) {
21 array<i64, 2> g{inf, inf};
22 for (int x = 0; x < 2; x++) {
23 for (int y = 0; y < 2; y++) {
24 if (s[i - 1][x] <= s[i][y]) {
25 g[y] = min(g[y], dp[x] + c[i] * y);
26 }
27 }
28 }
29 dp = g;
30 }
31 auto ans = min(dp[0], dp[1]);
32 if (ans == inf) {
33 ans = -1;
34 }
35 cout << ans << "\n";
36 return 0;
37 }
Toxel likes arrays. Before traveling to the Paldea region, Serval gave him an array a as a gift. This array
has n pairwise distinct elements.
In order to get more arrays, Toxel performed m operations with the initial array. In the i-th operation,
he modified the pi -th element of the (i − 1)-th array to vi , resulting in the i-th array (the initial array a
is numbered as 0). During modifications, Toxel guaranteed that the elements of each array are still
pairwise distinct after each operation.
Finally, Toxel got m + 1 arrays and denoted them as A0 = a, A1 , . . . , Am . For each pair (i, j) (0 ≤
i < j ≤ m), Toxel defines its value as the number of distinct elements of the concatenation of Ai and
Aj . Now Toxel wonders, what is the sum of the values of all pairs? Please help him to calculate the
answer.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<int> f(n + m);
8 vector<int> a(n);
9 for (int i = 0; i < n; i++) {
10 cin >> a[i];
11 a[i]--;
12 f[a[i]] += m + 1;
13 }
14 for (int i = 0; i < m; i++) {
15 int p, v;
16 cin >> p >> v;
17 p--, v--;
18 f[a[p]] -= m - i;
19 a[p] = v;
20 f[a[p]] += m - i;
21 }
22 i64 ans = 1LL * m * (m + 1) * n;
23 for (int i = 0; i < n + m; i++) {
24 ans -= 1LL * f[i] * (f[i] - 1) / 2;
25 }
26 cout << ans << "\n";
27 }
28 int main() {
29 ios::sync_with_stdio(false);
30 cin.tie(nullptr);
31 int t;
32 cin >> t;
33 while (t--) {
34 solve();
35 }
36 return 0;
37 }
Little09 and his friends are playing a game. There are n players, and the temperature value of the
player i is i.
The types of environment are expressed as 0 or 1. When two players fight in a specific environment,
if its type is 0, the player with a lower temperature value in this environment always wins; if it is 1,
the player with a higher temperature value in this environment always wins. The types of the n − 1
environments form a binary string s with a length of n − 1.
If there are x players participating in the game, there will be a total of x − 1 battles, and the types of
the x − 1 environments will be the first x − 1 characters of s. While there is more than one player left
in the tournament, choose any two remaining players to fight. The player who loses will be eliminated
from the tournament. The type of the environment of battle i is si .
For each x from 2 to n, answer the following question: if all players whose temperature value does not
exceed x participate in the game, how many players have a chance to win?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 int suf = 0;
10 for (int x = 2; x <= n; x++) {
11 if (x > 2 && s[x - 2] != s[x - 3]) {
12 suf = 1;
13 } else {
14 suf++;
15 }
16 cout << x - suf << " \n"[x == n];
17 }
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
Please help him find the minimum possible value F he can get by choosing xi and yi optimally. It can
be shown that there is always at least one valid way to choose them.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 constexpr i64 inf = 1E18;
5 void solve() {
6 int n, s;
7 cin >> n >> s;
8 vector<int> a(n), x(n);
9 for (int i = 0; i < n; i++) {
10 cin >> a[i];
11 if (a[i] <= s) x[i] = 0;
12 else x[i] = s;
13 }
14 x[0] = 0, x[n - 1] = a[n - 1];
15 array<i64, 2> dp{inf, inf};
16 dp[0] = 0;
17 for (int i = 1; i < n; i++) {
18 array<i64, 2> g{inf, inf};
19 for (int j = 0; j < 2; j++) {
20 for (int k = 0; k < 2; k++) {
21 g[k] = min(g[k], dp[j] + 1LL * (j ? x[i - 1] : a[i - 1] - x[i - 1]) * (k ?
a[i] - x[i] : x[i]));
22 }
23 }
24 dp = g;
25 }
26 cout << dp[0] << "\n";
27 }
28 int main() {
29 ios::sync_with_stdio(false);
30 cin.tie(nullptr);
31 int t;
32 cin >> t;
33 while (t--) {
34 solve();
35 }
36 return 0;
37 }
206: Playoff
2n teams participate in a playoff tournament. The tournament consists of 2n − 1 games. They are held
as follows: in the first phase of the tournament, the teams are split into pairs: team 1 plays against
team 2, team 3 plays against team 4, and so on (so, 2n−1 games are played in that phase). When a team
loses a game, it is eliminated, and each game results in elimination of one team (there are no ties).
After that, only 2n−1 teams remain. If only one team remains, it is declared the champion; otherwise,
the second phase begins, where 2n−2 games are played: in the first one of them, the winner of the
game “1 vs 2” plays against the winner of the game “3 vs 4”, then the winner of the game “5 vs 6” plays
against the winner of the game “7 vs 8”, and so on. This process repeats until only one team remains.
The skill level of the i-th team is pi , where p is a permutation of integers 1, 2, . .. , 2n (a permutation is
an array where each element from 1 to 2n occurs exactly once).
You are given a string s which consists of n characters. These characters denote the results of games in
each phase of the tournament as follows:
if si is equal to 0, then during the i-th phase (the phase with 2n−i games), in each match, the team with
the lower skill level wins;
if si is equal to 1, then during the i-th phase (the phase with 2n−i games), in each match, the team with
the higher skill level wins.
Let’s say that an integer x is winning if it is possible to find a permutation p such that the team with
skill x wins the tournament. Find all winning integers.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 string s;
10 cin >> s;
11 int lt = 0, gt = 0;
12 for (int i = 0; i < n; i++) {
13 if (s[i] == '1') lt += lt + 1;
14 else gt += gt + 1;
15 }
16 for (int i = lt + 1; i <= (1 << n) - gt; i++) {
17 cout << i << " \n"[i == n - gt];
18 }
19 return 0;
20 }
Sir Monocarp Hamilton is planning to paint his wall. The wall can be represented as a grid, consisting
of 2 rows and m columns. Initially, the wall is completely white.
Monocarp wants to paint a black picture on the wall. In particular, he wants cell (i, j) (the j-th cell in
the i-th row) to be colored black, if ci,j = ‘B’, and to be left white, if ci,j = ‘W’. Additionally, he wants
each column to have at least one black cell, so, for each j, the following constraint is satisfied: c1,j , c2,j
or both of them will be equal to ‘B’.
In order for the picture to turn out smooth, Monocarp wants to place down a paint brush in some cell
(x1 , y1 ) and move it along the path (x1 , y1 ), (x2 , y2 ), . . . , (xk , yk ) so that:
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s[2];
8 cin >> s[0] >> s[1];
9 for (int t = 0; t < 2; t++) {
10 int x = t;
11 int ok = 1;
12 for (int i = 0; i < n; i++) {
13 if (s[x][i] != 'B') ok = 0;
14 if (s[!x][i] == 'B') x ^= 1;
15 }
16 if (ok) {
17 cout << "YES\n";
18 return;
19 }
20 }
21 cout << "NO\n";
22 }
23 int main() {
24 ios::sync_with_stdio(false);
25 cin.tie(nullptr);
26 int t;
27 cin >> t;
28 while (t--) solve();
29 return 0;
30 }
Hossam makes a big party, and he will invite his friends to the party.
Hossam has a list of m pairs of his friends that don’t know each other. Any pair not present in this list
are friends.
A subsegment of the queue starting from the friend a and ending at the friend b is [a, a + 1, a + 2, . . . , b].
A subsegment of the queue is called good when all pairs of that segment are friends.
Hossam wants to know how many pairs (a, b) there are (1 ≤ a ≤ b ≤ n), such that the subsegment
starting from the friend a and ending at the friend b is good.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
There are n astronauts working on some space station. An astronaut with the number i (1 ≤ i ≤ n)
has power ai .
An evil humanoid has made his way to this space station. The power of this humanoid is equal to h.
Also, the humanoid took with him two green serums and one blue serum.
When an astronaut with power ai is absorbed, this astronaut disappears, and power of the humanoid
increases by ⌊ a2i ⌋, that is, an integer part of a2i . For example, if a humanoid absorbs an astronaut with
power 4, its power increases by 2, and if a humanoid absorbs an astronaut with power 7, its power
increases by 3.
After using the green serum, this serum disappears, and the power of the humanoid doubles, so it
increases by 2 times.
After using the blue serum, this serum disappears, and the power of the humanoid triples, so it increases
by 3 times.
The humanoid is wondering what the maximum number of astronauts he will be able to absorb if he
acts optimally.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, h;
6 cin >> n >> h;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 sort(a.begin(), a.end());
12 array<array<i64, 2>, 3> dp {};
13 dp[2][1] = h;
14 int ans = 0;
15 for (int i = 0; i < n; i++) {
16 for (int x = 2; x >= 0; x--) {
17 for (int y = 1; y >= 0; y--) {
18 if (x) {
19 dp[x - 1][y] = max(dp[x - 1][y], 2 * dp[x][y]);
20 }
21 if (y) {
22 dp[x][y - 1] = max(dp[x][y - 1], 3 * dp[x][y]);
23 }
24 if (dp[x][y] > a[i]) {
25 dp[x][y] += a[i] / 2;
26 ans = i + 1;
27 }
28 }
29 }
30 }
31 cout << ans << "\n";
32 }
33 int main() {
34 ios::sync_with_stdio(false);
35 cin.tie(nullptr);
36 int t;
37 cin >> t;
38 while (t--) {
39 solve();
40 }
41 return 0;
42 }
You are given an array a1 , a2 , . . . , an of length n. You can perform the following operation multiple
times:
What is the maximum possible score of a that can be obtained by performing a sequence of such
operations?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 i64 s = 0;
12 int ans = 0;
13 int max = 0;
14 int first = 1;
15 map<i64, int> cnt;
16 for (int i = 0; i < n; i++) {
17 if (a[i] == 0) {
18 if (first) {
19 first = 0;
20 ans += cnt[0];
21 } else {
22 ans += max;
23 }
24 max = 0;
25 cnt.clear();
26 }
27 s += a[i];
28 max = max(max, ++cnt[s]);
29 }
30 if (first) {
31 first = 0;
32 ans += cnt[0];
33 } else {
34 ans += max;
35 }
36 cout << ans << "\n";
37 }
38 int main() {
39 ios::sync_with_stdio(false);
40 cin.tie(nullptr);
41 int t;
42 cin >> t;
43 while (t--) {
44 solve();
45 }
46 return 0;
47 }
greedy
Iulia has n glasses arranged in a line. The i-th glass has ai units of juice in it. Iulia drinks only from
odd-numbered glasses, while her date drinks only from even-numbered glasses.
To impress her date, Iulia wants to find a contiguous subarray of these glasses such that both Iulia and
her date will have the same amount of juice in total if only the glasses in this subarray are considered.
Please help her to do that.
More formally, find out if there exists two indices l, r such that 1 ≤ l ≤ r ≤ n, and al + al+2 + al+4 +
· · · + ar = al+1 + al+3 + · · · + ar−1 if l and r have the same parity and al + al+2 + al+4 + · · · + ar−1 =
al+1 + al+3 + · · · + ar otherwise.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<i64> s(n + 1);
8 set<i64> set{0LL};
9 for (int i = 0; i < n; i++) {
10 int a;
11 cin >> a;
12 s[i + 1] = s[i] + (i % 2 ? 1 : -1) * a;
13 set.insert(s[i + 1]);
14 }
15 if (set.size() != n + 1) {
16 cout << "YES\n";
17 } else {
18 cout << "NO\n";
19 }
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
You have an array of integers a1 , a2 , . . . , an of length n. On the i-th of the next d days you are going to
do exactly one of the following two actions:
Add 1 to each of the first bi elements of the array a (i.e., set aj := aj + 1 for each 1 ≤ j ≤ bi ).
Count the elements which are equal to their position (i.e., the aj = j). Denote the number of such
elements as c. Then, you add c to your score, and reset the entire array a to a 0-array of length n (i.e.,
set [a1 , a2 , . . . , an ] := [0, 0, . . . , 0]).
Your score is equal to 0 in the beginning. Note that on each day you should perform exactly one of the
actions above: you cannot skip a day or perform both actions on the same day.
What is the maximum score you can achieve at the end?
Since d can be quite large, the sequence b is given to you in the compressed format:
You are given a sequence of integers v1 , v2 , . . . , vk . The sequence b is a concatenation of infinitely many
copies of v: b = [v1 , v2 , . . . , vk , v1 , v2 , . . . , vk , . . .].
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k, d;
6 cin >> n >> k >> d;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector<int> v(k);
12 for (int i = 0; i < k; i++) {
13 cin >> v[i];
14 }
15 int ans = 0;
16 for (int i = 0; i < d && i < 2 * n + 1; i++) {
17 int res = 0;
18 for (int j = 0; j < n; j++) {
19 res += (a[j] == j + 1);
20 }
21 ans = max(ans, res + (d - 1 - i) / 2);
22 int b = v[i % k];
23 for (int j = 0; j < b; j++) {
24 a[j] += 1;
25 }
26 }
27 cout << ans << "\n";
28 }
29 int main() {
30 ios::sync_with_stdio(false);
31 cin.tie(nullptr);
32 int t;
33 cin >> t;
34 while (t--) {
35 solve();
36 }
37 return 0;
38 }
You have n intervals [l1 , r1 ], [l2 , r2 ], . . . , [ln , rn ], such that li < ri for each i, and all the endpoints of
the intervals are distinct.
The i-th interval has weight ci per unit length. Therefore, the weight of the i-th interval is ci · (ri − li ).
You don’t like large weights, so you want to make the sum of weights of the intervals as small as
possible. It turns out you can perform all the following three operations:
However, after performing all of the operations, the intervals must still be valid (i.e., for each i, li < ri
must hold).
What’s the minimum possible sum of weights of the intervals after performing the operations?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<pair<int, int>> a;
8 for (int i = 0; i < n; i++) {
9 int l;
10 cin >> l;
11 a.emplace_back(l, 1);
12 }
13 for (int i = 0; i < n; i++) {
14 int r;
15 cin >> r;
16 a.emplace_back(r, -1);
17 }
18 sort(a.begin(), a.end());
19 vector<int> c(n);
20 for (int i = 0; i < n; i++) {
21 cin >> c[i];
22 }
23 sort(c.begin(), c.end());
24 i64 ans = 0;
25 vector<int> len, stk;
26 for (auto [x, t] : a) {
27 if (t == 1) {
28 stk.push_back(x);
29 } else {
30 assert(!stk.empty());
31 len.push_back(x - stk.back());
32 stk.pop_back();
33 }
34 }
35 sort(len.begin(), len.end(), greater());
36 for (int i = 0; i < n; i++) {
37 ans += 1LL * c[i] * len[i];
38 }
39 cout << ans << "\n";
40 }
41 int main() {
42 ios::sync_with_stdio(false);
43 cin.tie(nullptr);
44 int t;
45 cin >> t;
46 while (t--) {
47 solve();
48 }
49 return 0;
50 }
The easy and hard versions of this problem differ only in the constraints on the number of test cases
and n. In the hard version, the number of test cases does not exceed 104 , and the sum of values of n
over all test cases does not exceed 2 · 105 . Furthermore, there are no additional constraints on n in a
single test case.
Recently, Alice and Bob were given marbles of n different colors by their parents. Alice has received
a1 marbles of color 1, a2 marbles of color 2,. . ., an marbles of color n. Bob has received b1 marbles of
color 1, b2 marbles of color 2, . . . , bn marbles of color n. All ai and bi are between 1 and 109 .
After some discussion, Alice and Bob came up with the following game: players take turns, starting
with Alice. On their turn, a player chooses a color i such that both players have at least one marble of
that color. The player then discards one marble of color i, and their opponent discards all marbles of
color i. The game ends when there is no color i such that both players have at least one marble of that
color.
The score in the game is the difference between the number of remaining marbles that Alice has and
the number of remaining marbles that Bob has at the end of the game. In other words, the score in the
game is equal to (A − B), where A is the number of marbles Alice has and B is the number of marbles
Bob has at the end of the game. Alice wants to maximize the score, while Bob wants to minimize it.
Calculate the score at the end of the game if both players play optimally.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n), b(n);
8 for (int i = 0; i < n; i++) {
The easy and hard versions of this problem differ only in the constraints on the number of test cases
and n. In the easy version, the number of test cases does not exceed 103 , and n does not exceed 6.
Recently, Alice and Bob were given marbles of n different colors by their parents. Alice has received
a1 marbles of color 1, a2 marbles of color 2,. . ., an marbles of color n. Bob has received b1 marbles of
color 1, b2 marbles of color 2, . . . , bn marbles of color n. All ai and bi are between 1 and 109 .
After some discussion, Alice and Bob came up with the following game: players take turns, starting
with Alice. On their turn, a player chooses a color i such that both players have at least one marble of
that color. The player then discards one marble of color i, and their opponent discards all marbles of
color i. The game ends when there is no color i such that both players have at least one marble of that
color.
The score in the game is the difference between the number of remaining marbles that Alice has and
the number of remaining marbles that Bob has at the end of the game. In other words, the score in the
game is equal to (A − B), where A is the number of marbles Alice has and B is the number of marbles
Bob has at the end of the game. Alice wants to maximize the score, while Bob wants to minimize it.
Calculate the score at the end of the game if both players play optimally.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n), b(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 0; i < n; i++) {
12 cin >> b[i];
13 }
14 vector<int> p(n);
15 iota(p.begin(), p.end(), 0);
16 sort(p.begin(), p.end(),
17 [&](int i, int j) {
18 return a[i] + b[i] > a[j] + b[j];
19 });
20 i64 ans = 0;
21 for (int i = 0; i < n; i++) {
22 int j = p[i];
23 if (i % 2 == 0) {
24 ans += a[j] - 1;
25 } else {
26 ans -= b[j] - 1;
27 }
28 }
29 cout << ans << "\n";
30 }
31 int main() {
32 ios::sync_with_stdio(false);
33 cin.tie(nullptr);
34 int t;
35 cin >> t;
36 while (t--) {
37 solve();
38 }
39 return 0;
40 }
In this problem, you are initially given an empty multiset. You have to process two types of queries:
GET w - say whether it is possible to take the sum of some subset of the current multiset and get a
value equal to w.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int m;
8 cin >> m;
9 array<int, 30> cnt{};
10 while (m--) {
11 int t, v;
12 cin >> t >> v;
13 if (t == 1) {
14 cnt[v] += 1;
15 } else {
16 for (int i = 29; i >= 0; i--) {
17 int x = min(v >> i, cnt[i]);
18 v -= x << i;
19 }
20 if (v == 0) {
21 cout << "YES\n";
22 } else {
23 cout << "NO\n";
24 }
25 }
26 }
27 return 0;
28 }
Given is a string s of length n. In one operation you can select the lexicographically largest† subsequence
of string s and cyclic shift it to the right‡ .
Your task is to calculate the minimum number of operations it would take for s to become sorted, or
report that it never reaches a sorted state.
† 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 ̸= 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.
‡ By cyclic shifting the string t t . . . t to the right, we get the string tm t1 . . . tm−1 .
1 2 m
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 vector<int> a;
10 for (int i = n - 1; i >= 0; i--) {
11 if (a.empty() || s[i] >= s[a.back()]) {
12 a.push_back(i);
13 }
14 }
15 reverse(a.begin(), a.end());
16 int j = 0;
17 while (j < a.size() && s[a[0]] == s[a[j]]) {
18 j += 1;
19 }
20 int ans = a.size() - j;
21 for (int i = 0; i < a.size() - 1 - i; i++) {
22 swap(s[a[i]], s[a[a.size() - 1 - i]]);
23 }
24 if (!is_sorted(s.begin(), s.end())) {
25 ans = -1;
26 }
27 cout << ans << "\n";
28 }
29 int main() {
30 ios::sync_with_stdio(false);
31 cin.tie(nullptr);
32 int t;
33 cin >> t;
34 while (t--) {
35 solve();
36 }
37 return 0;
38 }
You are given an integer array a1 , a2 , . . . , an (0 ≤ ai ≤ 109 ). In one operation, you can choose an
integer x (0 ≤ x ≤ 1018 ) and replace ai with ⌊ ai2+x ⌋ (⌊y⌋ denotes rounding y down to the nearest
integer) for all i from 1 to n. Pay attention to the fact that all elements of the array are affected on each
operation.
Print the smallest number of operations required to make all elements of the array equal.
If the number of operations is less than or equal to n, then print the chosen x for each operation. If
there are multiple answers, print any of them.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int min = *min_element(a.begin(), a.end());
12 int max = *max_element(a.begin(), a.end());
13 vector<int> ans;
14 while (min < max) {
15 int x = min % 2;
16 ans.push_back(x);
17 min = (min + x) / 2;
18 max = (max + x) / 2;
19 }
20 cout << ans.size() << "\n";
21 if (ans.size() <= n) {
22 for (auto x : ans) {
23 cout << x << " ";
24 }
25 cout << "\n";
26 }
27 }
28 int main() {
29 ios::sync_with_stdio(false);
30 cin.tie(nullptr);
31 int t;
32 cin >> t;
33 while (t--) {
34 solve();
35 }
36 return 0;
37 }
Theofanis easily gets obsessed with problems before going to sleep and often has nightmares about
them. To deal with his obsession he visited his doctor, Dr. Emix.
In his latest nightmare, he has an array a of size n and wants to divide it into non-empty subarrays†
such that every element is in exactly one of the subarrays.
For example, the array [1, −3, 7, −6, 2, 5] can be divided to [1][−3, 7][−6, 2][5].
The Cypriot value of such division is equal to Σki=1 i · sumi where k is the number of subarrays that we
divided the array into and sumi is the sum of the i-th subarray.
The Cypriot value of this division of the array [1][−3, 7][−6, 2][5] = 1·1+2·(−3+7)+3·(−6+2)+4·5 =
17.
Theofanis is wondering what is the maximum Cypriot value of any division of the array.
† An array b is a subarray of an array a if b can be obtained from a by deletion of several (possibly, zero or
all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular,
an array is a subarray of itself.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<i64> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = n - 2; i >= 0; i--) {
12 a[i] += a[i + 1];
13 }
14 i64 ans = a[0];
15 for (int i = 1; i < n; i++) {
You are given an integer array a1 , a2 , . . . , an , all its elements are distinct.
First, you are asked to insert one more integer an+1 into this array. an+1 should not be equal to any of
a1 , a2 , . . . , an .
Then, you will have to make all elements of the array equal. At the start, you choose a positive integer
x (x > 0). In one operation, you add x to exactly one element of the array. Note that x is the same for
all operations.
What’s the smallest number of operations it can take you to make all elements equal, after you choose
an+1 and x?
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 if (n == 1) {
12 cout << 1 << "\n";
13 return;
14 }
15 int g = 0;
16 for (int i = 1; i < n; i++) {
17 g = gcd(g, a[i] - a[i - 1]);
18 }
19 int max = *max_element(a.begin(), a.end());
20 set<int> s;
21 vector<int> cnt(n + 1);
22 i64 ans = 0;
23 int mex = 0;
24 for (int i = 0; i < n; i++) {
25 a[i] = (max - a[i]) / g;
26 if (a[i] <= n) {
27 cnt[a[i]] += 1;
28 }
29 ans += a[i];
30 }
31 while (cnt[mex]) {
32 mex++;
33 }
34 ans += mex;
35 cout << ans << "\n";
36 }
37 int main() {
38 ios::sync_with_stdio(false);
39 cin.tie(nullptr);
40 int t;
41 cin >> t;
42 while (t--) {
43 solve();
44 }
45 return 0;
46 }
Tree is a connected graph without cycles. It can be shown that any tree of n vertices has exactly n − 1
edges.
Leaf is a vertex in the tree with exactly one edge connected to it.
Distance between two vertices u and v in a tree is the minimum number of edges that must be passed
to come from vertex u to vertex v.
Alex’s birthday is coming up, and Timofey would like to gift him a tree of n vertices. However, Alex is a
very moody boy. Every day for q days, he will choose an integer, denoted by the integer chosen on the
i-th day by di . If on the i-th day there are not two leaves in the tree at a distance exactly di , Alex will be
disappointed.
Timofey decides to gift Alex a designer so that he can change his tree as he wants. Timofey knows that
Alex is also lazy (a disaster, not a human being), so at the beginning of every day, he can perform no
more than one operation of the following kind:
Choose vertices u, v1 , and v2 such that there is an edge between u and v1 and no edge between u and
v2 . Then remove the edge between u and v1 and add an edge between u and v2 . This operation cannot
be performed if the graph is no longer a tree after it.
Somehow Timofey managed to find out all the di . After that, he had another brilliant idea - just in case,
make an instruction manual for the set, one that Alex wouldn’t be disappointed.
Timofey is not as lazy as Alex, but when he saw the integer n, he quickly lost the desire to develop the
instruction and the original tree, so he assigned this task to you. It can be shown that a tree and a
sequence of operations satisfying the described conditions always exist.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, q;
6 cin >> n >> q;
7 int u = n;
8 int v1 = n - 1;
9 for (int i = 1; i < n; i++) {
10 cout << i << " " << i + 1 << "\n";
11 }
12 while (q--) {
13 int d;
14 cin >> d;
15 int v2 = d;
16 if (v1 == v2) {
17 cout << "-1 -1 -1\n";
18 } else {
19 cout << u << " " << v1 << " " << v2 << "\n";
20 v1 = v2;
21 }
22 }
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
To do this, Vlad can apply the following operation any number of times:
Extract the first element of the array and insert it at the end;
Swap that element with the previous one until it becomes the first or until it becomes strictly greater
than the previous one.
Note that both actions are part of the operation, and for one operation, you must apply both actions.
For example, if you apply the operation to the array [4, 3, 1, 2, 6, 4], it will change as follows:
[4, 3, 1, 2, 6, 4];
[3, 1, 2, 6, 4, 4];
[3, 1, 2, 6, 4, 4];
[3, 1, 2, 4, 6, 4].
Vlad doesn’t have time to perform all the operations, so he asks you to determine the minimum number
of operations required to sort the array or report that it is impossible.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 auto it = min_element(a.begin(), a.end());
12 if (is_sorted(it, a.end())) {
13 cout << it - a.begin() << "\n";
14 } else {
15 cout << -1 << "\n";
16 }
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
Milena has received an array of integers a1 , a2 , . . . , an of length n from a secret admirer. She thinks
that making it non-decreasing should help her identify the secret admirer.
She can use the following operation to make this array non-decreasing:
Select an element ai of array a and an integer x such that 1 ≤ x < ai . Then, replace ai by two elements
x and ai − x in array a. New elements (x and ai − x) are placed in the array a in this order instead of
ai .More formally, let a1 , a2 , . . . , ai , . . . , ak be an array a before the operation. After the operation, it
becomes equal to a1 , a2 , . . . , ai−1 , x, ai − x, ai+1 , . . . , ak . Note that the length of a increases by 1 on
each operation.
More formally, let a1 , a2 , . . . , ai , . . . , ak be an array a before the operation. After the operation, it
becomes equal to a1 , a2 , . . . , ai−1 , x, ai − x, ai+1 , . . . , ak . Note that the length of a increases by 1 on
each operation.
Milena can perform this operation multiple times (possibly zero). She wants you to determine the
minimum number of times she should perform this operation to make array a non-decreasing.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int lst = a[n - 1];
12 i64 ans = 0;
13 for (int i = n - 2; i >= 0; i--) {
14 int t = (a[i] - 1) / lst + 1;
15 ans += t - 1;
16 lst = a[i] / t;
17 }
18 cout << ans << "\n";
19 }
20 int main() {
21 ios::sync_with_stdio(false);
22 cin.tie(nullptr);
23 int t;
24 cin >> t;
25 while (t--) {
26 solve();
27 }
28 return 0;
29 }
A boy called Smilo is playing a new game! In the game, there are n hordes of monsters, and the i-th
horde contains ai monsters. The goal of the game is to destroy all the monsters. To do this, you have
two types of attacks and a combo counter x, initially set to 0:
The first type: you choose a number i from 1 to n, such that there is at least one monster left in the
horde with the number i. Then, you kill one monster from horde number i, and the combo counter x
increases by 1.
The second type: you choose a number i from 1 to n, such that there are at least x monsters left in
the horde with number i. Then, you use an ultimate attack and kill x monsters from the horde with
number i. After that, x is reset to zero.
Your task is to destroy all of the monsters, meaning that there should be no monsters left in any of the
hordes. Smilo wants to win as quickly as possible, so he wants to the minimum number of attacks
required to win the game.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
This is the easy version of the problem. The only difference is that in this version m = 1.
You are given two arrays of integers a1 , a2 , . . . , an and b1 , b2 , . . . , bn . Before applying any operations,
you can reorder the elements of each array as you wish. Then, in one operation, you will perform both
of the following actions, if the arrays are not empty:
Choose any element from array a and remove it (all remaining elements are shifted to a new array a),
Choose any element from array b and remove it (all remaining elements are shifted to a new array b).
Let k be the final size of both arrays. You need to find the minimum number of operations required to
satisfy ai < bi for all 1 ≤ i ≤ k.
This problem was too easy, so the problem author decided to make it more challenging. You are also
given a positive integer m. Now, you need to find the sum of answers to the problem for m pairs of
arrays (c[i], b), where 1 ≤ i ≤ m. Array c[i] is obtained from a as follows:
c[i]1 = i,
c[i]j = aj , for 2 ≤ j ≤ n.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 vector<int> a(n), b(n);
8 for (int i = 1; i < n; i++) {
9 cin >> a[i];
10 }
11 for (int i = 0; i < n; i++) {
12 cin >> b[i];
13 }
14 a[0] = 1;
15 sort(a.begin(), a.end());
16 sort(b.begin(), b.end());
17 int ans = 0;
18 for (int i = 0, j = 0; i < n; i++) {
19 while (j < n && a[i] >= b[j]) {
20 j++;
21 }
22 ans = max(ans, j - i);
23 }
24 cout << ans << "\n";
25 }
26 int main() {
27 ios::sync_with_stdio(false);
28 cin.tie(nullptr);
29 int t;
30 cin >> t;
31 while (t--) {
32 solve();
33 }
34 return 0;
35 }
Iva and Pav are a famous Serbian competitive programming couple. In Serbia, they call Pav “papuca”
and that’s why he will make all of Iva’s wishes come true.
Let’s define f (l, r) = al & al+1 & . . . & ar (here & denotes the bitwise AND operation).
Each query consists of 2 numbers, k and l, and she wants Pav to find the largest index r (l ≤ r ≤ n),
such that f (l, r) ≥ k.
Pav wants to solve this problem fast because he doesn’t want to upset Iva. He needs your help.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 vector nxt(n + 1, vector<int>(30, n));
12 for (int i = n - 1; i >= 0; i--) {
13 nxt[i] = nxt[i + 1];
14 for (int j = 0; j < 30; j++) {
15 if (~a[i] >> j & 1) {
16 nxt[i][j] = i;
17 }
18 }
19 }
20 int q;
21 cin >> q;
22 while (q--) {
23 int l, k;
24 cin >> l >> k;
25 l--;
26 int ans = l;
27 int res = n;
28 for (int i = 29; i >= 0; i--) {
29 if (k >> i & 1) {
30 res = min(res, nxt[l][i]);
31 } else {
32 ans = max(ans, min(res, nxt[l][i]));
33 }
34 }
35 ans = max(ans, res);
36 if (ans <= l) {
37 ans = -1;
38 }
39 cout << ans << " ";
40 }
41 }
42 int main() {
43 ios::sync_with_stdio(false);
44 cin.tie(nullptr);
45 int t;
46 cin >> t;
47 while (t--) {
48 solve();
49 }
50 return 0;
51 }
Next you will be given a positive integer k and two arrays, l and r of length k.
l1 = 1;
rk = n;
Now you will be given a positive integer q which represents the number of modifications you need to
do on s.
Reversing the substring [a, b] of a string s means to make s equal to s1 , s2 , . . . , sa−1 , sb , sb−1 , . . . , sa+1 , sa , sb+1 , sb+2 , . .
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 string s;
8 cin >> s;
9 vector<int> l(k), r(k);
10 for (int i = 0; i < k; i++) {
11 cin >> l[i];
12 l[i]--;
13 }
14 for (int i = 0; i < k; i++) {
15 cin >> r[i];
16 r[i]--;
17 }
18 int q;
19 cin >> q;
20 vector<int> f(n);
21 while (q--) {
22 int x;
23 cin >> x;
24 x--;
25 f[x] ^= 1;
26 }
27 for (int i = 0; i < k; i++) {
28 int rev = 0;
29 for (int j = l[i]; j <= l[i] + r[i] - j; j++) {
30 rev ^= f[j] ^ f[l[i] + r[i] - j];
31 if (rev) {
32 swap(s[j], s[l[i] + r[i] - j]);
33 }
34 }
35 }
36 cout << s << "\n";
37 }
38 int main() {
39 ios::sync_with_stdio(false);
40 cin.tie(nullptr);
41 int t;
42 cin >> t;
43 while (t--) {
44 solve();
45 }
46 return 0;
47 }
There are n cards stacked in a deck. Initially, ai is written on the i-th card from the top. The value
written on a card does not change.
You will play a game. Initially your score is 0. In each turn, you can do one of the following operations:
Choose an odd† positive integer i, which is not greater than the number of cards left in the deck.
Remove the i-th card from the top of the deck and add the number written on the card to your score.
The remaining cards will be reindexed starting from the top.
Choose an even‡ positive integer i, which is not greater than the number of cards left in the deck.
Remove the i-th card from the top of the deck. The remaining cards will be reindexed starting from the
top.
End the game. You can end the game whenever you want, you do not have to remove all cards from
the initial deck.
What is the maximum score you can get when the game ends?
† An integer i is odd, if there exists an integer k such that i = 2k + 1.
‡ An integer i is even, if there exists an integer k such that i = 2k.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 i64 ans = 0;
12 for (int i = 2; i < n; i++) {
13 ans += max(0, a[i]);
14 }
15 ans += max(0, a[0] + max(0, n > 1 ? a[1] : 0));
16 cout << ans << "\n";
17 }
18 int main() {
19 ios::sync_with_stdio(false);
20 cin.tie(nullptr);
21 int t;
22 cin >> t;
23 while (t--) {
24 solve();
25 }
26 return 0;
27 }
You have n sets of integers S1 , S2 , . . . , Sn . We call a set S attainable, if it is possible to choose some
(possibly, none) of the sets S1 , S2 , . . . , Sn so that S is equal to their union† . If you choose none of
S1 , S2 , . . . , Sn , their union is an empty set.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 i64 Or = 0;
8 vector<i64> a(n);
9 int ans = 0;
10 for (int i = 0; i < n; i++) {
11 int k;
12 cin >> k;
13 while (k--) {
14 int x;
15 cin >> x;
16 a[i] |= 1LL << x;
17 }
18 Or |= a[i];
19 }
20 for (int i = 1; i <= 50; i++) {
21 if (Or >> i & 1) {
22 i64 v = 0;
23 for (int j = 0; j < n; j++) {
24 if (~a[j] >> i & 1) {
25 v |= a[j];
26 }
27 }
28 ans = max(ans, __builtin_popcountll(v));
29 }
30 }
31 cout << ans << "\n";
32 }
33 int main() {
34 ios::sync_with_stdio(false);
35 cin.tie(nullptr);
36 int t;
37 cin >> t;
38 while (t--) {
39 solve();
40 }
41 return 0;
42 }
You are given a binary string s. A binary string is a string consisting of characters 0 and/or 1.
You can perform the following operation on s any number of times (even zero):
You have to make s alternating, i. e. after you perform the operations, every two adjacent characters in
s should be different.
the number of different shortest sequences of operations that make s alternating. Two sequences
of operations are different if in at least one operation, the chosen integer i is different in these two
sequences.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 template<class T>
5 constexpr T power(T a, i64 b) {
6 T res = 1;
7 for (; b; b /= 2, a *= a) {
8 if (b % 2) {
9 res *= a;
10 }
11 }
12 return res;
13 }
14 constexpr i64 mul(i64 a, i64 b, i64 p) {
15 i64 res = a * b - i64(1.L * a * b / p) * p;
16 res %= p;
17 if (res < 0) {
18 res += p;
19 }
20 return res;
21 }
22 template<i64 P>
23 # struct MLong;
24 template<>
25 i64 MLong<0LL>::Mod = i64(1E18) + 9;
26 template<int P>
27 # struct MInt;
28 template<>
29 int MInt<0>::Mod = 998244353;
30 template<int V, int P>
31 constexpr MInt<P> CInv = MInt<P>(V).inv();
32 constexpr int P = 998244353;
33 using Z = MInt<P>;
34 void solve() {
35 string s;
36 cin >> s;
37 int n = s.size();
38 Z ways = 1;
39 int ans = 0;
40 for (int l = 0, r = 0; l < n; l = r) {
41 while (r < n && s[l] == s[r]) {
42 r++;
43 }
44 ans += r - l - 1;
45 ways *= r - l;
46 }
47 for (int i = 1; i <= ans; i++) {
48 ways *= i;
49 }
50 cout << ans << " " << ways << "\n";
51 }
52 int main() {
53 ios::sync_with_stdio(false);
54 cin.tie(nullptr);
55 int t;
56 cin >> t;
57 while (t--) {
58 solve();
59 }
60 return 0;
61 }
implementation
An anonymous informant has told you that the array b was obtained as follows: initially, there existed
an array a1 , a2 , . . . , an , after which the following two-component operation was performed k times:
Then, the array a was cyclically shifted to the left‡ exactly x times.
As a result of k such operations, the array b1 , b2 , . . . , bn was obtained. You want to check if the words
of the anonymous informant can be true or if they are guaranteed to be false.
† A number x is called a fixed point of the array a , a , . . . , a if 1 ≤ x ≤ n and ax = x.
1 2 n
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, k;
6 cin >> n >> k;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 int x = n - 1;
12 for (int i = 0; i < min(n, k); i++) {
13 if (a[x] > n) {
14 cout << "No\n";
15 return;
16 }
17 x = (x - a[x] + n) % n;
18 }
19 cout << "Yes\n";
20 }
21 int main() {
22 ios::sync_with_stdio(false);
23 cin.tie(nullptr);
24 int t;
25 cin >> t;
26 while (t--) {
27 solve();
28 }
29 return 0;
30 }
Recall that string a is lexicographically smaller than string b if a is a prefix of b (and a ̸= b), or there
exists an index i (1 ≤ i ≤ min(|a|, |b|)) such that ai < bi , and for any index j (1 ≤ j < i) aj = bj .
si , a character is removed from string si−1 in such a way that string si is lexicographically minimal.
You need to output the character in position pos of the string S (i. e. the character Spos ).
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 string s;
6 cin >> s;
7 int n = s.size();
8 i64 pos;
9 cin >> pos;
10 pos--;
11 int x, y;
12 for (int i = 0; i < n; i++) {
13 int len = n - i;
14 if (pos < len) {
15 x = i;
16 y = pos;
17 break;
18 }
19 pos -= len;
20 }
21 string t;
22 for (auto c : s) {
23 while (x > 0 && !t.empty() && c < t.back()) {
24 t.pop_back();
25 x--;
26 }
27 t += c;
28 }
29 cout << t[y];
30 }
31 int main() {
32 ios::sync_with_stdio(false);
33 cin.tie(nullptr);
34 cout << fixed << setprecision(10);
35 int t;
36 cin >> t;
37 while (t--) {
38 solve();
39 }
40 cout << "\n";
41 return 0;
42 }
Zhongkao examination is over, and Daniel would like to do some puzzle games. He is going to fill in the
matrix M using permutations of length m. That is, each row of M must be a permutation of length
m† .
Define the value of the i-th column in M as vi = MEX(M1,i , M2,i , . . . , Mn,i )‡ . Since Daniel likes
diversity, the beauty of M is s = MEX(v1 , v2 , · · · , vm ).
You have to help Daniel fill in the matrix M and maximize its beauty.
†A permutation of length m is an array consisting of m distinct integers from 0 to m − 1 in arbitrary
order. For example, [1, 2, 0, 4, 3] is a permutation, but [0, 1, 1] is not a permutation (1 appears twice in
the array), and [0, 1, 3] is also not a permutation (m − 1 = 2 but there is 3 in the array).
‡ The MEX of an array is the smallest non-negative integer that does not belong to the array. For
example, MEX(2, 2, 1) = 0 because 0 does not belong to the array, and MEX(0, 3, 1, 2) = 4 because
0, 1, 2 and 3 appear in the array, but 4 does not.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> n >> m;
7 cout << (m == 1 ? 0 : m == 2 ? 2 : min(n + 1, m)) << "\n";
8 for (int i = 0; i < n; i++) {
9 vector<int> a(m);
10 iota(a.begin(), a.end(), 0);
11 int p = max(1, m - i - 1);
12 reverse(a.begin(), a.begin() + p);
13 reverse(a.begin() + p, a.end());
14 for (int j = 0; j < m; j++) {
15 cout << a[j] << " \n"[j == m - 1];
16 }
17 }
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
Ashish has a string s of length n containing only characters ‘a’, ‘b’ and ‘c’.
He wants to find the length of the smallest substring, which satisfies the following conditions:
Ashish is busy planning his next Codeforces round. Help him solve the problem.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or
all) characters from the beginning and several (possibly, zero or all) characters from the end.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 string s;
8 cin >> s;
9 int ans = n + 1;
10 for (int i = 0; i < n; i++) {
11 int cnt[3] {};
12 for (int j = i; j <= i + 6 && j < n; j++) {
13 cnt[s[j] - 'a']++;
14 if (j > i && cnt[0] > cnt[1] && cnt[0] > cnt[2]) {
15 ans = min(ans, j - i + 1);
16 }
17 }
18 }
19 if (ans > n) {
20 ans = -1;
21 }
22 cout << ans << "\n";
23 }
24 int main() {
25 ios::sync_with_stdio(false);
26 cin.tie(nullptr);
27 int t;
28 cin >> t;
29 while (t--) {
30 solve();
31 }
32 return 0;
33 }
Daniel is watching a football team playing a game during their training session. They want to improve
their passing skills during that session.
The game involves n players, making multiple passes towards each other. Unfortunately, since the
balls were moving too fast, after the session Daniel is unable to know how many balls were involved
during the game. The only thing he knows is the number of passes delivered by each player during all
the session.
Find the minimum possible amount of balls that were involved in the game.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> a(n);
8 for (int i = 0; i < n; i++) {
9 cin >> a[i];
10 }
11 i64 sum = accumulate(a.begin(), a.end(), 0LL);
12 int max = *max_element(a.begin(), a.end());
13 int ans;
14 if (max == 0) {
15 ans = 0;
16 } else if (2 * max <= sum + 1) {
17 ans = 1;
18 } else {
19 ans = 2 * max - sum;
20 }
21 cout << ans << "\n";
22 }
23 int main() {
24 ios::sync_with_stdio(false);
25 cin.tie(nullptr);
26 int t;
27 cin >> t;
28 while (t--) {
29 solve();
30 }
31 return 0;
32 }
Monocarp had an array a consisting of integers. Initially, this array was empty.
choose an integer and append it to the end of the array. Each time Monocarp performed a query of
this type, he wrote out a character +;
remove the last element from the array. Each time Monocarp performed a query of this type, he wrote
out a character -. Monocarp never performed this query on an empty array;
check if the array is sorted in non-descending order, i.,e. a1 ≤ a2 ≤ · · · ≤ ak , where k is the number of
elements in the array currently. Every array with less than 2 elements is considered sorted. If the array
was sorted by the time Monocarp was performing that query, he wrote out a character 1. Otherwise,
he wrote out a character 0.
You are given a sequence s of q characters 0, 1, + and/or -. These are the characters that were written
out by Monocarp, given in the exact order he wrote them out.
You have to check if this sequence is consistent, i. e. it was possible for Monocarp to perform the
queries so that the sequence of characters he wrote out is exactly s.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experi-
enced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some
passages can connect a room to itself and since the passages are built on different depths they do not
intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in
and then reaches the room on the other end of the passage in exactly one minute. When he enters a
room at minute i, he makes a note in his logbook with number ti:
If Petya has visited this room before, he writes down the minute he was in this room last time;
Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.
Initially, Petya was in one of the rooms at minute 0, he didn’t write down number t0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya
found his logbook and now he is curious: what is the minimum possible number of rooms in Paris
catacombs according to Petya’s logbook?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 int n;
8 cin >> n;
9 vector<int> cnt(n);
10 for (int i = 0; i < n; i++) {
11 int t;
12 cin >> t;
13 cnt[t]++;
14 }
15 int ans = n;
16 for (int i = 1; i < n; i++) {
17 if (cnt[i] > 0) {
18 ans--;
19 }
20 }
21 cout << ans << "\n";
22 return 0;
23 }
You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each
substring of s with length at least k contains this character c.
You have to find minimum k such that there exists at least one k-dominant character.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 int main() {
5 ios::sync_with_stdio(false);
6 cin.tie(nullptr);
7 string s;
8 cin >> s;
9 const int n = s.size();
10 vector<int> p[26];
11 for (int i = 0; i < 26; i++) {
12 p[i].push_back(-1);
13 }
14 for (int i = 0; i < n; i++) {
15 p[s[i] - 'a'].push_back(i);
16 }
17 for (int i = 0; i < 26; i++) {
18 p[i].push_back(n);
19 }
20 int ans = n;
21 for (int i = 0; i < 26; i++) {
22 int res = 0;
23 for (int j = 1; j < p[i].size(); j++) {
24 res = max(res, p[i][j] - p[i][j - 1]);
25 }
26 ans = min(ans,res);
27 }
28 cout << ans << "\n";
29 return 0;
30 }
Your friends have an array of n elements, calculated its array of prefix sums and passed it to you,
accidentally losing one element during the transfer. Your task is to find out if the given array can
matches permutation.
A permutation of n elements is an array of n numbers from 1 to n such that each number occurs exactly
one times in it.
For example, the original permutation was [1, 5, 2, 4, 3]. Its array of prefix sums - [1, 6, 8, 12, 15]. Having
lost one element, you can get, for example, arrays [6, 8, 12, 15] or [1, 6, 8, 15].
It can also be shown that the array [1, 2, 100] does not correspond to any permutation.
Problem: link
Tutorial: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<i64> a(n);
8 for (int i = 1; i < n; i++) {
9 cin >> a[i];
10 }
11 if (a[n - 1] > 1LL * n * (n + 1) / 2) {
12 cout << "NO\n";
13 return;
14 }
15 vector<int> cnt(2 * n + 1);
16 for (int i = 1; i < n; i++) {
17 if (a[i] - a[i - 1] > 2 * n) {
18 cout << "NO\n";
19 return;
20 }
21 cnt[a[i] - a[i - 1]]++;
22 }
23 if (a[n - 1] < 1LL * n * (n + 1) / 2) {
24 for (int i = 1; i <= 2 * n; i++) {
25 if (cnt[i] > (i <= n)) {
26 cout << "NO\n";
27 return;
28 }
29 }
30 cout << "YES\n";
31 return;
32 }
33 int x = find(cnt.begin() + 1, cnt.end(), 0) - cnt.begin();
34 int y;
35 for (int i = 1; i <= 2 * n; i++) {
36 if (cnt[i] > (i <= n)) {
37 y = i;
38 break;
39 }
40 }
41 if (y <= x) {
42 cout << "NO\n";
43 return;
44 }
45 cnt[y]--;
46 cnt[x]++;
47 cnt[y - x]++;
48 for (int i = 1; i <= n; i++) {
49 if (cnt[i] != 1) {
50 cout << "NO\n";
51 return;
52 }
53 }
54 cout << "YES\n";
55 }
56 int main() {
57 ios::sync_with_stdio(false);
58 cin.tie(nullptr);
59 int t;
60 cin >> t;
61 while (t--) {
62 solve();
63 }
64 return 0;
65 }
A compass points directly toward the morning star. It can only point in one of eight directions: the four
cardinal directions (N, S, E, W) or some combination (NW, NE, SW, SE). Otherwise, it will break.
There are n distinct points with integer coordinates on a plane. How many ways can you put a compass
at one point and the morning star at another so that the compass does not break?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 map<int, int> f[4];
8 i64 ans = 0;
9 for (int i = 0; i < n; i++) {
10 int x, y;
11 cin >> x >> y;
12 ans += f[0][x]++;
13 ans += f[1][y]++;
14 ans += f[2][x + y]++;
15 ans += f[3][x - y]++;
16 }
17 cout << ans * 2 << "\n";
18 }
19 int main() {
20 ios::sync_with_stdio(false);
21 cin.tie(nullptr);
22 int t;
23 cin >> t;
24 while (t--) {
25 solve();
26 }
27 return 0;
28 }
Mihai and Slavic were looking at a group of n frogs, numbered from 1 to n, all initially located at point
0. Frog i has a hop length of ai .
Each second, frog i hops ai units forward. Before any frogs start hopping, Slavic and Mihai can place
exactly one trap in a coordinate in order to catch all frogs that will ever pass through the corresponding
coordinate.
However, the children can’t go far away from their home so they can only place a trap in the first n
points (that is, in a point with a coordinate between 1 and n) and the children can’t place a trap in
point 0 since they are scared of frogs.
Can you help Slavic and Mihai find out what is the maximum number of frogs they can catch using a
trap?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> cnt(n + 1);
8 for (int i = 0; i < n; i++) {
9 int a;
10 cin >> a;
11 if (a <= n) {
12 cnt[a]++;
13 }
14 }
15 for (int i = n; i >= 1; i--) {
242: Particles
You have discovered n mysterious particles on a line with integer charges of c1 , . . . , cn . You have a
device that allows you to perform the following operation:
Choose a particle and remove it from the line. The remaining particles will shift to fill in the gap that
is created. If there were particles with charges x and y directly to the left and right of the removed
particle, they combine into a single particle of charge x + y.
For example, if the line of particles had charges of [−3, 1, 4, −1, 5, −9], performing the operation on
the 4th particle will transform the line into [−3, 1, 9, −9].
If we then use the device on the 1st particle in this new line, the line will turn into [1, 9, −9].
You will perform operations until there is only one particle left. What is the maximum charge of this
remaining particle that you can obtain?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n;
6 cin >> n;
7 vector<int> c(n);
8 for (int i = 0; i < n; i++) {
This is a simple version of the problem. The only difference is that in this version n ≤ 106 .
One winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes.
He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathe-
matician, Rudolf came up with a mathematical model of a snowflake.
He defined a snowflake as an undirected graph constructed according to the following rules:
Initially, the graph has only one vertex.
Then, more vertices are added to the graph. The initial vertex is connected by edges to k new vertices
(k > 1).
Each vertex that is connected to only one other vertex is connected by edges to k more new vertices.
This step should be done at least once.
The smallest possible snowflake for k = 4 is shown in the figure.
After some mathematical research, Rudolf realized that such snowflakes may not have any number of
vertices. Help Rudolf check if a snowflake with n vertices can exist.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 i64 n;
6 cin >> n;
7 for (int i = 2; i <= 60; i++) {
8 int d;
9 if (i == 2) {
10 d = sqrt(n);
11 } else if (i == 3) {
12 d = cbrt(n);
13 } else {
14 d = pow(n, 1.0 / i);
15 }
16 if (d == 1) {
17 continue;
18 }
19 i64 res = 0;
20 i64 p = 1;
21 for (int t = 0; t <= i; t++) {
22 if (t) {
23 p *= d;
24 }
25 res += p;
26 }
27 if (res == n) {
28 cout << "YES\n";
29 return;
30 }
31 }
32 cout << "NO\n";
33 }
34 int main() {
35 ios::sync_with_stdio(false);
36 cin.tie(nullptr);
37 cout << fixed << setprecision(10);
38 int t;
39 cin >> t;
40 while (t--) {
41 solve();
42 }
43 return 0;
44 }
There are n people taking part in a show about VOCALOID. They will sit in the row of seats, numbered 1
to m from left to right.
The n people come and sit in order. Each person occupies a seat in one of three ways:
Sit in the seat next to the left of the leftmost person who is already sitting, or if seat 1 is taken, then
leave the show. If there is no one currently sitting, sit in seat m.
Sit in the seat next to the right of the rightmost person who is already sitting, or if seat m is taken, then
leave the show. If there is no one currently sitting, sit in seat 1.
Sit in the seat numbered xi . If this seat is taken, then leave the show.
Now you want to know what is the maximum number of people that can take a seat, if you can let
people into the show in any order?
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 void solve() {
5 int n, m;
6 cin >> m >> n;
7 int cnt1 = 0, cnt2 = 0;
8 vector<int> a;
9 for (int i = 0; i < m; i++) {
10 int x;
11 cin >> x;
12 if (x == -1) {
13 cnt1++;
14 } else if (x == -2) {
15 cnt2++;
16 } else {
17 a.push_back(x);
18 }
19 }
20 sort(a.begin(), a.end());
21 a.erase(unique(a.begin(), a.end()), a.end());
22 int ans = 0;
23 ans = max(ans, cnt1 + int(a.size()));
24 ans = max(ans, cnt2 + int(a.size()));
25 ans = min(ans, n);
26 for (int i = 0; i < a.size(); i++) {
27 int l = min(a[i] - 1, i + cnt1);
28 int r = min(n - a[i], int(a.size()) - 1 - i + cnt2);
29 ans = max(ans, l + 1 + r);
30 }
31 cout << ans << "\n";
32 }
33 int main() {
34 ios::sync_with_stdio(false);
35 cin.tie(nullptr);
36 int t;
37 cin >> t;
38 while (t--) {
39 solve();
40 }
41 return 0;
42 }
In a carnival game, there is a huge pyramid of cans with 2023 rows, numbered in a regular pattern as
shown.
If can 92 is hit initially, then all cans colored red in the picture above would fall.
You throw a ball at the pyramid, and it hits a single can with number n2 . This causes all cans that are
stacked on top of this can to fall (that is, can n2 falls, then the cans directly above n2 fall, then the cans
directly above those cans, and so on). For example, the picture above shows the cans that would fall if
can 92 is hit.
What is the sum of the numbers on all cans that fall? Recall that n2 = n × n.
Problem: link
Solution: link
1 #include <bits/stdc++.h>
2 using namespace std;
3 using i64 = long long;
4 i64 sum2(i64 n) {
5 return n * (n + 1) * (2 * n + 1) / 6;
6 }
7 i64 sum2(i64 l, i64 r) {
8 return sum2(r) - sum2(l - 1);
9 }
10 void so