contest_id stringlengths 1 4 | index stringclasses 43
values | title stringlengths 2 63 | statement stringlengths 51 4.24k | tutorial stringlengths 19 20.4k | tags listlengths 0 11 | rating int64 800 3.5k ⌀ | code stringlengths 46 29.6k ⌀ |
|---|---|---|---|---|---|---|---|
1174 | D | Ehab and the Expected XOR Problem | Given two integers $n$ and $x$, construct an array that satisfies the following conditions:
- for any element $a_i$ in the array, $1 \le a_i<2^n$;
- there is no \textbf{non-empty} subsegment with bitwise XOR equal to $0$ or $x$,
- its length $l$ should be maximized.
A sequence $b$ is a subsegment of a sequence $a$ if... | The main idea is to build the prefix-xor of the array, not the array itself, then build the array from it. Let the prefix-xor array be called $b$. Now, $a_l \oplus a_{l+1} \dots \oplus a_r=b_{l-1} \oplus b_{r}$. Thus, the problem becomes: construct an array such that no pair of numbers has bitwise-xor sum equal to 0 or... | [
"bitmasks",
"constructive algorithms"
] | 1,900 | "#include <iostream>\n#include <vector>\nusing namespace std;\nbool ex[(1<<18)];\nint main()\n{\n\tint n,x;\n\tscanf(\"%d%d\",&n,&x);\n\tex[0]=1;\n\tvector<int> v({0});\n\tfor (int i=1;i<(1<<n);i++)\n\t{\n\t\tif (ex[i^x])\n\t\tcontinue;\n\t\tv.push_back(i);\n\t\tex[i]=1;\n\t}\n\tprintf(\"%d\\n\",v.size()-1);\n\tfor (in... |
1174 | E | Ehab and the Expected GCD Problem | Let's define a function $f(p)$ on a permutation $p$ as follows. Let $g_i$ be the greatest common divisor (GCD) of elements $p_1$, $p_2$, ..., $p_i$ (in other words, it is the GCD of the prefix of length $i$). Then $f(p)$ is the number of \textbf{distinct} elements among $g_1$, $g_2$, ..., $g_n$.
Let $f_{max}(n)$ be th... | Let's call the permutations from the statement good. For starters, we'll try to find some characteristics of good permutations. Let's call the first element in a good permutation $s$. Then, $s$ must have the maximal possible number of prime divisors. Also, every time the $gcd$ changes as you move along prefixes, you mu... | [
"combinatorics",
"dp",
"math",
"number theory"
] | 2,500 | "#include <iostream>\nusing namespace std;\n#define mod 1000000007\nint n,dp[1000005][21][2];\nint f(int x,int y)\n{\n\tint tmp=(1<<x);\n\tif (y)\n\ttmp*=3;\n\treturn n/tmp;\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tint p=0;\n\twhile ((1<<p)<=n)\n\tp++;\n\tp--;\n\tdp[1][p][0]=1;\n\tif ((1<<(p-1))*3<=n)\n\tdp[1][p-1][1]... |
1174 | F | Ehab and the Big Finale | This is an interactive problem.
You're given a tree consisting of $n$ nodes, rooted at node $1$. A tree is a connected graph with no cycles.
We chose a hidden node $x$. In order to find this node, you can ask queries of two types:
- d $u$ ($1 \le u \le n$). We will answer with the distance between nodes $u$ and $x$.... | Let $dep_a$ be the depth of node $a$ and $sz_a$ be the size of the subtree of node $a$. First, we'll query the distance between node 1 and node $x$ to know $dep_x$. The idea in the problem is to maintain a "search scope", some nodes such that $x$ is one of them, and to try to narrow it down with queries. From this poin... | [
"constructive algorithms",
"divide and conquer",
"graphs",
"implementation",
"interactive",
"trees"
] | 2,400 | "#include <iostream>\n#include <vector>\nusing namespace std;\nbool del[200005];\nvector<int> v[200005];\nint par[200005],sz[200005],dep[200005],depx;\nvoid pre(int node,int p)\n{\n\tfor (int u:v[node])\n\t{\n\t\tif (u!=p)\n\t\t{\n\t\t\tpar[u]=node;\n\t\t\tdep[u]=dep[node]+1;\n\t\t\tpre(u,node);\n\t\t}\n\t}\n}\nvector<... |
1175 | A | From Hero to Zero | You are given an integer $n$ and an integer $k$.
In one step you can do one of the following moves:
- decrease $n$ by $1$;
- divide $n$ by $k$ if $n$ is divisible by $k$.
For example, if $n = 27$ and $k = 3$ you can do the following steps: $27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 ... | It's always optimal to divide by $k$ whenever it's possible, since dividing by $k$ equivalent to decreasing $n$ by $\frac{n}{k}(k - 1) \ge 1$. The only problem is that it's too slow to just subtract $1$ from $n$ each time, since in the worst case we can make $O(n)$ operations (Consider case $n = 10^{18}$ and $k = \frac... | [
"implementation",
"math"
] | 900 | #include<bits/stdc++.h>
using namespace std;
long long n, k;
int main(){
int tc;
cin >> tc;
for(int i = 0; i < tc; ++i){
cin >> n >> k;
long long res = 0;
while(n > 0){
if(n % k == 0){
n /= k;
++res;
}
else{
long long rem = ... |
1175 | B | Catch Overflow! | You are given a function $f$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $x$. $x$ is an integer variable and can be assigned values from $0$ to $2^{32}-1$. The function contains three types of commands:
- for $n$ — for loop;
- end — every comma... | One can notice (or actually derive using some maths) that the answer is the sum of products of nested for loops iterations for every "add" command. Let's learn to simulate that in linear complexity. Maintain the stack of multipliers: on "for $n$" push the top of stack multiplied by $n$ to the stack, on "end" pop the la... | [
"data structures",
"expression parsing",
"implementation"
] | 1,600 | #include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
using namespace std;
const long long INF = 1ll << 32;
int main(){
int l;
cin >> l;
stack<long long> cur;
cur.push(1);
long long res = 0;
forn(_, l){
string t;
cin >> t;
if (t == "for"){
int x;
cin >> x;
cur.push(mi... |
1175 | C | Electrification | At first, there was a legend related to the name of the problem, but now it's just a formal statement.
You are given $n$ points $a_1, a_2, \dots, a_n$ on the $OX$ axis. Now you are asked to find such an integer point $x$ on $OX$ axis that $f_k(x)$ is minimal possible.
The function $f_k(x)$ can be described in the fol... | First observation: $k$ closest points to any point $x$ form a contiguous subsegment $a_i, \dots, a_{i + k - 1}$, so $f_k(x) = \min(|a_{i - 1} - x|, |a_{i + k} - x|)$. Second observation: for any contiguous subsegment $a_i, \dots, a_{i + k - 1}$ all points $x$ this subsegment closest to, also form a contiguous segment $... | [
"binary search",
"brute force",
"greedy"
] | 1,600 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
int n, k;
vector<int> a;
inline bool read() {
if(!(cin >> n >> k))
return false;
a.resize(n);
fore(i, 0, n)
cin >> a[i];
return true;
}
inline void solve() {
pair<int, int>... |
1175 | D | Array Splitting | You are given an array $a_1, a_2, \dots, a_n$ and an integer $k$.
You are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $f(i)$ be the index of subarray the $i$-th element belongs to. Subarrays are numbered from left to ri... | Let's denote $S(k)$ as $\sum\limits_{i = k}^{n}{a_i}$ (just a suffix sum). And let $p_i$ be the position where starts the $i$-th subarray (obviously, $p_1 = 1$ and $p_i < p_{i + 1}$). Then we can make an interesting transformation: $\sum_{i=1}^{n}{a_i \cdot f(i)} = 1 \cdot (S(p_1) - S(p_2)) + 2 \cdot (S(p_2) - S(p_3)) ... | [
"greedy",
"sortings"
] | 1,900 | #include<bits/stdc++.h>
using namespace std;
const int N = 300009;
int n, k;
int a[N];
int main(){
cin >> n >> k;
for(int i = 0; i < n; ++i)
cin >> a[i];
long long sum = 0;
vector <long long> v;
for(int i = n - 1; i >= 0; --i){
sum += a[i];
if(i > 0) v.push_back(sum);
}
long long res = sum;
... |
1175 | E | Minimal Segment Cover | You are given $n$ intervals in form $[l; r]$ on a number line.
You are also given $m$ queries in form $[x; y]$. What is the minimal number of intervals you have to take so that every point (\textbf{not necessarily integer}) from $x$ to $y$ is covered by at least one of them?
If you can't choose intervals so that ever... | Let's take a look at a naive approach at first. That approach is greedy. Let's find such an interval which starts to the left or at $x$ and ends as much to the right as possible. Set $x$ to its right border. Continue until either no interval can be found or $y$ is reached. The proof basically goes like this. Let there ... | [
"data structures",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"implementation",
"trees"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int N = 500 * 1000 + 13;
int n, m;
pair<int, int> a[N], q[N];
int nxt[N];
int ans[N];
pair<int, int> p[N];
pair<int, int> get(int x, int r){
if (x == -1)
return make_pair(-1... |
1175 | F | The Number of Subpermutations | You have an array $a_1, a_2, \dots, a_n$.
Let's call some subarray $a_l, a_{l + 1}, \dots , a_r$ of this array a subpermutation if it contains all integers from $1$ to $r-l+1$ exactly once. For example, array $a = [2, 2, 1, 3, 2, 3, 1]$ contains $6$ subarrays which are subpermutations: $[a_2 \dots a_3]$, $[a_2 \dots a... | At first, let's represent permutations in the next form. We assign to all numbers from $1$ to $n$ random 128-bit strings, so the $i$-th number gets the string $h_i$. Then the permutation of length $len$ can be hashed as $h_1 \oplus h_2 \oplus \dots \oplus h_{len}$, where $\oplus$ is bitwise exclusive OR (for example, $... | [
"brute force",
"data structures",
"divide and conquer",
"hashing",
"math"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
typedef pair<long long, long long> pt;
const int N = int(3e5) + 99;
const pt zero = make_pair(0, 0);
int n;
int a[N];
pt hsh[N], sumHsh[N];
void upd(pt &a, pt b){
a.first ^= b.first;
a.second ^= b.second;
}
int calc(int pos){
set <int> sl, sr;
set<pt> s;
in... |
1175 | G | Yet Another Partiton Problem | You are given array $a_1, a_2, \dots, a_n$. You need to split it into $k$ subsegments (so every element is included in exactly one subsegment).
The weight of a subsegment $a_l, a_{l+1}, \dots, a_r$ is equal to $(r - l + 1) \cdot \max\limits_{l \le i \le r}(a_i)$. The weight of a partition is a total weight of all its ... | Important note: the author solution is using both linear Convex hull trick and persistent Li Chao tree. As mentioned in commentaries, applying the Divide-and-Conquer technique can help get rid of Li Chao tree. More about both structures you can read in this article. Let's try to write standard dp we can come up with (a... | [
"data structures",
"divide and conquer",
"dp",
"geometry",
"two pointers"
] | 3,000 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) (int)((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<li, li> pt;
const int INF = int(1e9);
const li INF64 = li(1e9);
pt operator -(const pt &a, const pt &b) {
... |
1176 | A | Divide it! | You are given an integer $n$.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
- Replace $n$ with $\frac{n}{2}$ if $n$ is divisible by $2$;
- Replace $n$ with $\frac{2n}{3}$ if $n$ is divisible by $3$;
- Replace $n$ with $\frac{4n}{5}$ if $n$ is divisible... | What if the given number $n$ cannot be represented as $2^{cnt_2} \cdot 3^{cnt_3} \cdot 5^{cnt_5}$? It means that the answer is -1 because all actions we can do are: remove one power of two, remove one power of three and add one power of two, and remove one power of five and add two powers of two. So if the answer is no... | [
"brute force",
"greedy",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
long long n;
cin >> n;
int cnt2 = 0, cnt3 = 0, cnt5 = 0;
while (n % 2 == 0) {
n /= 2;
++cnt2;
}
... |
1176 | B | Merge it! | You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots , a_n$.
In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $[2, 1, 4]$ you can obtain the following array... | Let $cnt_i$ be the number of elements of $a$ with the remainder $i$ modulo $3$. Then the initial answer can be represented as $cnt_0$ and we have to compose numbers with remainders $1$ and $2$ somehow optimally. It can be shown that the best way to do it is the following: firstly, while there is at least one remainder ... | [
"math"
] | 1,100 | #include<bits/stdc++.h>
using namespace std;
int t, n;
int cnt[3];
int main(){
cin >> t;
for(int tc = 0; tc < t; ++tc){
memset(cnt, 0, sizeof cnt);
cin >> n;
for(int i = 0; i < n; ++i){
int x;
cin >> x;
++cnt[x % 3];
}
int res = c... |
1176 | C | Lose it! | You are given an array $a$ consisting of $n$ integers. Each $a_i$ is one of the six following numbers: $4, 8, 15, 16, 23, 42$.
Your task is to remove the minimum number of elements to make this array \textbf{good}.
An array of length $k$ is called \textbf{good} if $k$ is divisible by $6$ and it is possible to split i... | Let $cnt_1$ be the number of subsequences $[4]$, $cnt_2$ be the number of subsequences $[4, 8]$, $cnt_3$ - the number of subsequences $[4, 8, 15]$ and so on, and $cnt_6$ is the number of completed subsequences $[4, 8, 15, 16, 23, 42]$. Let's iterate over all elements of $a$ in order from left to right. If the current e... | [
"dp",
"greedy",
"implementation"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
vector<int> p({4, 8, 15, 16, 23, 42});
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
a[i] = lower_bound(p.begin(), p.end... |
1176 | D | Recover it! | Authors guessed an array $a$ consisting of $n$ integers; each integer is not less than $2$ and not greater than $2 \cdot 10^5$. You don't know the array $a$, but you know the array $b$ which is formed from it with the following sequence of operations:
- Firstly, let the array $b$ be equal to the array $a$;
- Secondly,... | Firstly, let's generate first $199999$ primes. It can be done in $O(n \sqrt{n})$ almost naively (just check all elements in range $[2; 2750131]$). It also can be done with Eratosthenes sieve in $O(n)$ or $O(n \log \log n)$. We also can calculate for each number in this range the maximum its divisor non-equal to it (if ... | [
"dfs and similar",
"graphs",
"greedy",
"number theory",
"sortings"
] | 1,800 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 3 * 1000 * 1000 + 13;
int lst[N];
int num[N];
void sieve(){
forn(i, N) lst[i] = i;
for (int i = 2; i < N; ++i){
if (lst[i] != i){
lst[i] = i / lst[i];
continue;
}
for (long long j = i * 1ll... |
1176 | E | Cover it! | You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose \textbf{at most} $\lfloor\frac{n}{2}\rfloor$ vertices in this graph so \textbf{each} unchosen vertex is adjacent (i... | Firstly, let's run bfs on the given graph and calculate distances for all vertices. In fact, we don't need distances, we need their parities. The second part is to find all vertices with an even distance, all vertices with and odd distance, and print the smallest by size part. Why is it always true? Firstly, it is obvi... | [
"dfs and similar",
"dsu",
"graphs",
"shortest paths",
"trees"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n, m;
vector<int> d;
vector<vector<int>> g;
void bfs(int s) {
d = vector<int>(n, INF);
d[s] = 0;
queue<int> q;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto to : g[v]) {
if (d[to] == INF) {
d[to] ... |
1176 | F | Destroy it! | You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.
The boss battle consists of $n$ turns. During each turn, you will get several cards. Each card has two parameters: its cost $c_i$ and damage $d_i$. You may play some of your cards during each ... | The first (and crucial) observation is that we don't need all the cards that we get during each turn. In fact, since the total cost is limited to $3$, we may leave three best cards of cost $1$, one best card of cost $2$ and one best card of cost $3$, and all other cards may be discarded. So, the problem is reduced: we ... | [
"dp",
"implementation",
"sortings"
] | 2,100 | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long li;
const li INF64 = li(1e18);
const int N = 200043;
vector<int> cards[N][4];
li dp[N][10];
int n;
li dp2[4][2];
int main()
{
#ifdef _DEBUG
freopen("input.txt", "r", std... |
1178 | A | Prime Minister | Alice is the leader of the State Refactoring Party, and she is about to become the prime minister.
The elections have just taken place. There are $n$ parties, numbered from $1$ to $n$. The $i$-th party has received $a_i$ seats in the parliament.
\textbf{Alice's party has number $1$}. In order to become the prime mini... | Ignore the parties that have more than half of Alice's party seats. For all other parties it is never disadvantageous to include them in the coalition, so we might as well take all of them. If the resulting number of seats is a majority, we output all involved parties, otherwise the answer is $0$. The complexity is $\m... | [
"greedy"
] | 800 | #include <iostream>
#include <vector>
using namespace std;
int main() {
int N; cin >> N;
vector<int> A(N); for (int&a:A) cin >> a;
vector<int> P{1};
int rest = 0, cur = A[0];
for (int i = 1; i < N; ++i) {
if (A[i] <= A[0]/2) {
cur += A[i];
P.push_back(i+1);
... |
1178 | B | WOW Factor | Recall that string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly zero or all) characters. For example, for the string $a$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo",... | We find all maximal blocks of vs. If there are $k$ of them, we replace the block with $k-1$ copies of w. After that, we can use a simple DP for finding the number of subsequences equal to wow. Complexity $\mathcal O(n)$. | [
"dp",
"strings"
] | 1,300 | #include <iostream>
#include <string>
using namespace std;
typedef long long ll;
int main() {
string S; cin >> S;
ll a = 0, b = 0, c = 0;
for (int i = 0; i < S.size(); ++i) {
if (S[i] == 'o') {
b += a;
} else if (i > 0 && S[i-1] == 'v') {
a++;
c += b... |
1178 | C | Tiles | Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor — a square tile that is diagonally split into white and black part as depicted in the figure below.
The dimension of this tile is perfect for this kitchen, as he will ne... | Observe that for a fixed pair of tiles $(i-1, j)$ and $(i, j-1)$ there is exactly one way of placing a tile at $(i, j)$ that satisfies the conditions. As a result, when all tiles $(1,i)$ and $(j,1)$ are placed, the rest is determined uniquely. We only need to count the number of ways to tile the first row and first col... | [
"combinatorics",
"greedy",
"math"
] | 1,300 | #include <iostream>
using namespace std;
constexpr int MOD = 998244353;
int main() {
int R, C; cin >> R >> C;
int X = 1;
while (R--) X = (2*X)%MOD;
while (C--) X = (2*X)%MOD;
cout << X << endl;
} |
1178 | D | Prime Graph | Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!
When building the graph, he needs four conditions to... | A solution always exists. We show a simple construction. For $n = 3$, a triangle is (the only) solution. For $n \geq 4$ we make a cycle on $n$ vertices: $1 \leftrightarrow 2 \leftrightarrow 3 \dots n \leftrightarrow 1$. The degree of each vertex is $2$ (a prime number), but the total number of edges - $n$ - might not b... | [
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,500 | #include <iostream>
using namespace std;
bool prime(int x) {
if (x < 2) return false;
for (int i = 2; i*i <= x; ++i) {
if (x%i == 0) return false;
}
return true;
}
int main(int argc, char ** argv){
int n; cin >> n;
int m = n;
while (!prime(m)) ++m;
cout << m << "\n1 " << n << '\... |
1178 | E | Archaeology | Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?
The book contains a single string of characters "a", "... | The answer always exists. Let's prove by induction on $|s|$, giving a construction in the process. $|s| = 0 \Rightarrow t =$ empty string, $|s| \leq 3 \Rightarrow t = s[0]$, $|s| \geq 4 \Rightarrow$. Let $t'$ be solution for $s[2:-2]$, which exists due to induction. As $s[0] \neq s[1]$ and $s[-1] \neq s[-2]$, there is ... | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | 1,900 | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string S; cin >> S;
int N = S.size();
int i = 0, j = N-1;
string A;
while (j-i >= 3) {
if (S[i] == S[j]) {
A.push_back(S[i]);
++i; --j;
} else if (S[i] == S[j-1]) {
... |
1178 | F1 | Short Colorful Strip | \textbf{This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of $m$ and the time limit. You need to solve both subtasks in order to hack this one.}
There are $n+1$ distinct colours in the universe, numbered $0$ through $n$. There is a strip o... | Let $LO[l][r]$ be the lowest ID of a colour used in the final strip on interval $[l,r]$. Let $I[c]$ be the position on which the colour $c$ occurs on the target strip. We solve this problem by computing $DP[l][r]$ - the number of ways of painting the interval $[l,r]$, given that it is painted with a single colour and a... | [
"combinatorics",
"dfs and similar",
"dp"
] | 2,200 | #include <iostream>
#include <vector>
using namespace std;
template <unsigned int N> class Field {
typedef unsigned int ui;
typedef unsigned long long ull;
public:
inline Field(int x = 0) : v(x) {}
inline Field<N>&operator+=(const Field<N>&o) {if (v+o.v >= N) v += o.v - N; else v += o.v; return *this;... |
1178 | F2 | Long Colorful Strip | \textbf{This is the second subtask of problem F. The only differences between this and the first subtask are the constraints on the value of $m$ and the time limit. It is sufficient to solve this subtask in order to hack it, but you need to solve both subtasks in order to hack the first one.}
There are $n+1$ distinct ... | There are several additional observations we need compared to previous subtask. First, note that if we ever colour a pair of positions with different colours, they will forever stay coloured with different colours. In other words, if two positions have the same colour in the final strip, the set of colours they were co... | [
"dp"
] | 2,600 | #include <iostream>
#include <vector>
using namespace std;
template <unsigned int N> class Field {
typedef unsigned int ui;
typedef unsigned long long ull;
public:
inline Field(int x = 0) : v(x) {}
inline Field<N> pow(int p){return (*this)^p; }
inline Field<N>&operator+=(const Field<N>&o) {if (v+o.v ... |
1178 | G | The Awesomest Vertex | You are given a rooted tree on $n$ vertices. The vertices are numbered from $1$ to $n$; the root is the vertex number $1$.
Each vertex has two integers associated with it: $a_i$ and $b_i$. We denote the set of all ancestors of $v$ (including $v$ itself) by $R(v)$. The awesomeness of a vertex $v$ is defined as
$$\left... | Denote $c_v = \sum_{w \in R(v)} a_w$ and $d_v = \sum_{w \in R(v)} b_w$. Let's solve a simpler task first, where we assume that all $a_i$ and $b_i$ are positive, and all updates and queries are on the root vertex. We can see that we are looking into maximum $\left(x + c_v \right) \cdot d_v$ = $c_vd_v + xd_v$, where $x$ ... | [
"data structures",
"dfs and similar"
] | 3,000 | #include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cassert>
#include <cmath>
using namespace std;
#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;
template<typen... |
1178 | H | Stock Exchange | \textbf{Warning: This problem has an unusual memory limit!}
Bob decided that he will not waste his prime years implementing GUI forms for a large corporation and instead will earn his supper on the Stock Exchange Reykjavik. The Stock Exchange Reykjavik is the only actual stock exchange in the world. The only type of t... | Lemma: If there is a solution $S$ for time $T$, there is also a solution $S'$ for time $T$ using not more exchanges than $S$, in which all exchanges occur either in time $0$ or in time $T$. Proof: Induction on $n$ - the number of exchanges not happening in time $0$ or $T$. If $n = 0$, we are done. Otherwise, pick an ar... | [
"binary search",
"flows",
"graphs"
] | 3,500 | #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define x first
#define y second
typedef long long ll;
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
/** Successive shortest paths algorithm. Runs in ... |
1179 | A | Valeriy and Deque | Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $n$ elements. The $i$-th element is $a_i$ ($i$ = $1, 2, \ldots, n$). He gradually takes the first two leftmost elements from the deque (let's call them $A$ and $B$, respectively), and then does th... | It can be noted that if the deque has the largest element of the deque in the first position, then during the next operations it will remain in the first position, and the second one will be written to the end each time, that is, all the elements of the deque starting from the second will move cyclically left. Let's go... | [
"data structures",
"implementation"
] | 1,500 | "/// author: Mr.Hakimov\n\n#include <bits/stdc++.h>\n#include <chrono>\n\n#define all(x) (x).begin(), (x).end()\n#define fin(s) freopen(s, \"r\", stdin);\n#define fout(s) freopen(s, \"w\", stdout);\n\nusing namespace std;\n\ntypedef long long LL;\ntypedef long double LD;\n\nint TN = 1;\n\nvoid showDeque(deque<int> d) {... |
1179 | B | Tolik and His Uncle | This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any... | First, we are going to describe how to bypass $1 \cdot m$ strip. This algorithm is pretty easy - $(1, 1)$ -> $(1, m)$ -> $(1, 2)$ -> $(1, m-1)$ -> $\ldots$. Obviously all jumps have different vectors because their lengths are different. It turns out that the algorithm for $n \cdot m$ grid is almost the same. Initially,... | [
"constructive algorithms"
] | 1,800 | "#include <bits/stdc++.h>\n\n#define int long long\n\n#define pii pair<int, int>\n\n#define x1 x1228\n#define y1 y1228\n\n#define left left228\n#define right right228\n\n#define pb push_back\n#define eb emplace_back\n\n#define mp make_pair \n\n#define ff fi... |
1179 | C | Serge and Dining Room | Serge came to the school dining room and discovered that there is a big queue here. There are $m$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.
Initially... | The main idea of the task is that the answer is minimal $x$ which satisfies the condition that the number of dishes with cost $\geq x$ is strictly more than the number of pupils who have more than $x$ togrogs. It can be proved using the fact that we can change every neighbor pair for pupils and we don't change the fina... | [
"binary search",
"data structures",
"graph matchings",
"greedy",
"implementation",
"math",
"trees"
] | 2,200 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define int long long\n\nconst int MAXN = 3e5 + 7;\nconst int MAXV = 3 * MAXN;\n\nint n, m;\nint a[MAXN], b[MAXN];\n\nint q;\nint t[MAXN], p[MAXN], x[MAXN];\n\nvoid read() {\n cin >> n >> m;\n for (int i = 0; i < n; ++i) {\n cin >> a[i];\n }\n for ... |
1179 | D | Fedor Runs for President | Fedor runs for president of Byteland! In the debates, he will be asked how to solve Byteland's transport problem. It's a really hard problem because of Byteland's transport system is now a tree (connected graph without cycles). Fedor's team has found out in the ministry of transport of Byteland that there is money in t... | We suppose we add an edge $u-v$. Path $u-v$ in the tree contains vertices $t_1, \ldots, t_k$, where $k$ - length of the path, $t_1 = u, t_k = v$. For each vertex $x$ of the tree, we say that $f(x)$ - the closest to $x$ vertex of this path. Finally, we call a component of $t_i$ all vertices $x$ having $f(x) = t_i$. One ... | [
"data structures",
"dp",
"trees"
] | 2,700 | "#include <bits/stdc++.h>\n#define int long long\n#define double long double\nusing namespace std;\nint INF = 1e18;\ndouble DINF = 1e18;\nvector<vector<int> > data;\nint ans = INF;\nvector<int> dp, sz;\nint n;\nstruct Line{double k; double b; double l; double r;};\nvector<Line> cht;\nint ask(int x){\n int L = 0, R =... |
1179 | E | Alesya and Discrete Math | We call a function good if its domain of definition is some set of integers and if in case it's defined in $x$ and $x-1$, $f(x) = f(x-1) + 1$ or $f(x) = f(x-1)$.
Tanya has found $n$ good functions $f_{1}, \ldots, f_{n}$, which are defined on all integers from $0$ to $10^{18}$ and $f_i(0) = 0$ and $f_i(10^{18}) = L$ fo... | We denote $T$ as $log(10^{18})$ for convenience. Let, without loss of generality, $n$ is even. Let us find such $x_i$ for function $f_i$ that $f_i(x_i) = \frac{L}{2}$ using binary search. Now we're going to renumber functions so that in new numeration $i < j$ attracts $x_i \leq x_j$. Let $x_{\frac{n}{2}} = P$. Now one ... | [
"divide and conquer",
"interactive"
] | 3,200 | "#include <iostream>\n#include <vector>\n#include <functional>\n#include <numeric>\n#include <random>\n#include <map>\nusing namespace std;\n#define int long long\nconst int FSZ = 1e18;\nmt19937 rnd;\nint cntq=0;\nint ask(int id, int x) {\n cout << \"? \" << id + 1 << \" \" << x << endl;\n int ans;\n cin >> an... |
1180 | A | Alex and a Rhombus | While playing with geometric figures Alex has accidentally invented a concept of a $n$-th order rhombus in a cell grid.
A $1$-st order rhombus is just a square $1 \times 1$ (i.e just a cell).
A $n$-th order rhombus for all $n \geq 2$ one obtains from a $n-1$-th order rhombus adding all cells which have a common side ... | Looking into the picture attentively, one can realize that there are $2$ rows with one cell, $2$ rows with two cells, ..., and $1$ row with $n$ cells. Thus the answer can be easily computed by $O(n)$. | [
"dp",
"implementation",
"math"
] | 800 | #include "bits/stdc++.h"
using namespace std;
int main() {
int n;
cin >> n;
cout << 2*n*n-2*n+1;
return 0;
} |
1180 | B | Nick and Array | Nick had received an awesome array of integers $a=[a_1, a_2, \dots, a_n]$ as a gift for his $5$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $a_1 \cdot a_2 \cdot \dots a_n$ of its elements seemed to him not large enoug... | Initially, we are going to make a product maximal by absolute value. It means that if $a_i \geq 0$ we are going to apply described operation (i.e to increase the absolute value). Now if the product is already positive, it's the answer. Else to apply the operation to the minimal number is obviously optimal (if we applie... | [
"greedy",
"implementation"
] | 1,500 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nmain(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int n;\n cin >> n;\n vector<int> v(n);\n for (int i=0;i<n;i++) cin >> v[i];\n if (n != 3 || (v[0] != -3 || v[1] != -3 || v[2] != 2)){\n for (int i=0;i<n;i++){\n if (v[i... |
1181 | A | Chunga-Changa | Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price $z$ chizhiks per coc... | It's easy to calculate how much coconuts we will buy: $k = \lfloor \frac{x + y}{z} \rfloor$ (suppose that all money transferred to a single person, this way the number of bought coconuts would be clearly maximal) If $k = \lfloor \frac{x}{z} \rfloor + \lfloor \frac{y}{z} \rfloor$, then the answer is $\langle k, 0 \rangl... | [
"greedy",
"math"
] | 1,000 | null |
1181 | B | Split a Number | Dima worked all day and wrote down on a long paper strip his favorite number $n$ consisting of $l$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.
To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a \textbf{p... | Suppose that the number doesn't contain any zeros (that is, we can split it at any point). Than it is easy to show that it is enough to check only the following cuts: $k$; $k$, if the length of the number is $2k$. $k + 1$; $k$ and $k$; $k + 1$, if the length of the number is $2k + 1$. Some intuition behind this: it's n... | [
"greedy",
"implementation",
"strings"
] | 1,500 | null |
1181 | C | Flag | Innokenty works at a flea market and sells some \sout{random stuff} rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $n \cdot m$ colored pieces that form a rectangle with $n$ rows and $m$ columns.
The colored pieces attracted Innokenty's attention so he immediately c... | To start with, let's find a way to calculate the number of flags of width $1$. Let's bruteforce the row $r$ and column $c$ of the topmost cell of the middle part of the flag. So if the cell above has the same color as $(r, c)$ then clearly there can't be a flag here. Otherwise we are standing at the topmost position of... | [
"brute force",
"combinatorics",
"dp",
"implementation"
] | 1,900 | null |
1181 | D | Irrigation | Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first $n$ olympiads the organizers i... | Let's solve all the queries simultaneously. For this purpose sort them all in increasing order. Sort all the countries based on the number of hosted competitions in the first $n$ years (see picture) How this diagram changes after several more years of the competition? The cells are filled from lower rows to the higher,... | [
"binary search",
"data structures",
"implementation",
"sortings",
"trees",
"two pointers"
] | 2,200 | null |
1181 | E2 | A Story of One Country (Hard) | This problem differs from the previous problem only in constraints.
Petya decided to visit Byteland during the summer holidays. It turned out that the history of this country is quite unusual.
Initially, there were $n$ different countries on the land that is now Berland. Each country had its own territory that was re... | We can rephrase the problem as follows: There is a set of non-intersecting rectangles on the plane. Let's say, that some rectangular area on the plane is good, if it contains exactly one rectangle in it or there exists a vertical or horizontal cut, which cuts the area into two good areas. You are asked to check whether... | [
"brute force",
"greedy",
"sortings"
] | 3,000 | null |
1182 | A | Filling Shapes | You have a given integer $n$. Find the number of ways to fill all $3 \times n$ tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
\begin{center}
This picture describes when $n = 4$. The left one is the shape and the right one is $3 \times n$ tiles.
\e... | If you want to have no empty spaces on $3 \times n$ tiles, you should fill leftmost bottom tile. Then you have only 2 choices; Both cases force you to group leftmost $3 \times 2$ tiles and fill. By this fact, we should group each $3 \times 2$ tiles and fill independently. So the answer is - if $n$ is odd, then the answ... | [
"dp",
"math"
] | 1,000 | #include <stdio.h>
int main(void){
int n; scanf("%d", &n);
if(n%2==0) printf("%d", 1<<(n/2));
else printf("0");
return 0;
} |
1182 | B | Plus from Picture | You have a given picture with size $w \times h$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:
- A "+" shape has one center nonempty cell.
- There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In othe... | First, try to find if there is any nonempty space which has 4 neighbors are all nonempty spaces. (Giant black star in the picture below.) If there is no such nonempty space, the answer is "NO". Second, try to search the end of the "+" shape from the center. (White stars in the picture below.) Third, try to find if ther... | [
"dfs and similar",
"implementation",
"strings"
] | 1,300 | #include <iostream>
#include <string>
#include <vector>
int main(void){
int w, h; std::cin >> h >> w;
std::vector<std::string> picture(h);
for(int i=0; i<h; i++) std::cin >> picture[i];
std::vector<std::vector<bool>> should_be_plus(h, std::vector<bool>(w, false));
for(int i=1; i<h-1; i++){
for(int j=1; j<w... |
1182 | C | Beautiful Lyrics | You are given $n$ words, each of which consists of lowercase alphabet letters. Each word \textbf{contains at least} one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.
Each lyric consists of two lines. Each line consists of two words separated by whitespace.
A lyr... | Let's make some definitions; $s_{1}$ and $s_{2}$ are complete duo if two word $s_{1}$ and $s_{2}$ have same number of vowels and the last vowels of $s_{1}$ and $s_{2}$ are same. For example, "hello" and "hollow" are complete duo. $s_{1}$ and $s_{2}$ are semicomplete duo if two word $s_{1}$ and $s_{2}$ have same number ... | [
"data structures",
"greedy",
"strings"
] | 1,700 | #include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <map>
// Typedef
typedef std::pair<std::string, std::string> strduo;
// Vowel related
bool isVowel(char c){
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int vowelCount(std::string &word){
int count = 0;
for(... |
1182 | D | Complete Mirror | You have given tree consist of $n$ vertices. Select a vertex as root vertex that satisfies the condition below.
- For all vertices $v_{1}$ and $v_{2}$, if $distance$($root$, $v_{1}$) $= distance$($root$, $v_{2})$ then $degree$($v_{1}$) $= degree$($v_{2}$), where $degree$ means the number of vertices connected to that ... | First, the valid tree should form like the picture below unless the whole tree is completely linear. top: This node is the top of the tree. This node has always degree $1$. This node is always one of the possible answers of valid tree. There might be no top node in the tree. semitop: This node is the closest children f... | [
"constructive algorithms",
"dfs and similar",
"dp",
"hashing",
"implementation",
"trees"
] | 2,400 | #include <stdio.h>
#include <vector>
#include <set>
#include <utility>
#include <algorithm>
// Graph attributes
typedef std::vector<std::set<int>> EDGE;
int v;
std::vector<bool> isInner;
EDGE edges, inneredges;
// Validation
bool validate(int root){
//printf("Validating for %d\n", root);
std::vector<bool> visit... |
1182 | E | Product Oriented Recurrence | Let $f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3}$ for $x \ge 4$.
You have given integers $n$, $f_{1}$, $f_{2}$, $f_{3}$, and $c$. Find $f_{n} \bmod (10^{9}+7)$. | You can form the expression into this; $c^{x} f_{x} = c^{x-1} f_{x-1} \cdot c^{x-2} f_{x-2} \cdot c^{x-3} f_{x-3}$ Let $g(x, p) = c^{x} f_{x}$'s $p$-occurrence for prime number $p$. For example, $40 = 2^{3} \times 5$ so $40$'s $2$-occurrence is $3$. Then we can set the formula $g(x, p) = g(x-1, p) + g(x-2, p) + g(x-3, ... | [
"dp",
"math",
"matrices",
"number theory"
] | 2,300 | #include <stdio.h>
#include <vector>
#include <set>
#include <map>
// Constants
typedef long long int lld;
const lld R = 1000 * 1000 * 1000 + 7; // a^(R-1) = 1 (mod R)
const lld matrixRemainder = R-1;
// Matrix class
class matrix{
public:
// Attributes
int row, col;
std::vector<std::vector<lld>> num;
// Con... |
1182 | F | Maximum Sine | You have given integers $a$, $b$, $p$, and $q$. Let $f(x) = \text{abs}(\text{sin}(\frac{p}{q} \pi x))$.
Find minimum possible integer $x$ that maximizes $f(x)$ where $a \le x \le b$. | Lemma: For all $x$, $y$ $\in [0, \pi]$, if $|\text{sin}(x)| > |\text{sin}(y)|$ then $x$ is more closer to the $\frac{\pi}{2}$ than $y$. With this lemma, we can avoid the calculation of floating precision numbers. Let's reform the problem; Find minimum possible integer $x$ that $\frac{p}{q}x \pi \bmod \pi$ is the closes... | [
"binary search",
"data structures",
"number theory"
] | 2,700 | #include <stdio.h>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
typedef long long int lld;
const lld infL = 1LL << 60;
// Find x that abs(sin(p/q pi x)) is the largest in [start, end).
int solve(lld start, lld end, lld p, lld q){
// Construct base intervals
lld interval = 1;
while(i... |
1183 | A | Nearest Interesting Number | Polycarp knows that if the sum of the digits of a number is divisible by $3$, then the number itself is divisible by $3$. He assumes that the numbers, the sum of the digits of which is divisible by $4$, are also somewhat interesting. Thus, he considers a positive integer $n$ interesting if its sum of digits is divisibl... | Even if we will iterate over all possible numbers starting from $a$ and check if sum of digits of the current number is divisible by $4$, we will find the answer very fast. The maximum possible number of iterations is no more than $5$. | [
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int sum(int a) {
int result = 0;
while (a > 0) {
result += a % 10;
a /= 10;
}
return result;
}
int main() {
int a;
cin >> a;
while (sum(a) % 4 != 0) {
a++;
}
... |
1183 | B | Equalize Prices | There are $n$ products in the shop. The price of the $i$-th product is $a_i$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.
In fact, the owner of the shop can change the price of some product $i$ in such a way that the difference between the old price ... | It is very intuitive that the maximum price we can obtain is $min + k$ where $min$ is the minimum value in the array. For this price we should check that we can change prices of all products to it. It can be done very easily: we can just check if each segment $[a_i - k; a_i + k]$ covers the point $min + k$. But this is... | [
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int j = 0; j < n; ++j) {
cin >> a[j];
}
int mn = ... |
1183 | C | Computer Game | Vova is playing a computer game. There are in total $n$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $k$.
During each turn Vova can choose what to do:
- If the current charge of his laptop battery is strictly gr... | Firstly, about the problem description. Vova really needs to complete the game i. e. play all $n$ turns. Exactly $n$ turns. Among all possible ways to do it he need choose one where the number of turns when he just plays (this is the first type turn!) is maximum possible. Suppose the answer is $n$. Then the charge of t... | [
"binary search",
"math"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
long long k, n, a, b;
cin >> k >> n >> a >> b;
k -= n * a;
if (k > 0) {
cout << n << endl;
} else {... |
1183 | D | Candy Box (easy version) | \textbf{This problem is actually a subproblem of problem G from the same contest.}
There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a ... | Let's calculate the array $cnt$ where $cnt_i$ is the number of candies of the $i$-th type. Let's sort it in non-ascending order. Obviously, now we can take $cnt_1$ because this is the maximum number of candies of some type in the array. Let $lst$ be the last number of candies we take. Initially it equals $cnt_1$ (and t... | [
"greedy",
"sortings"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int t = 0; t < q; ++t) {
int n;
cin >> n;
vector<int> cnt(n + 1);
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
++cnt[x]... |
1183 | E | Subsequences (easy version) | \textbf{The only difference between the easy and the hard versions is constraints}.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps b... | The topic of this problem is BFS. Let strings be the vertices of the graph and there is a directed edge from string $s$ to string $t$ if and only if we can obtain $t$ from $s$ by removing exactly one character. In this interpretation we have to find first $k$ visited vertices if we start our BFS from the initial string... | [
"dp",
"graphs",
"implementation",
"shortest paths"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
string s;
cin >> s;
int ans = 0;
queue<string> q;
set<string> st;
q.push(s);
st.insert(s);
while (!q.empty() && int(st.size()... |
1183 | F | Topforces Strikes Back | One important contest will take place on the most famous programming platform (Topforces) very soon!
The authors have a pool of $n$ problems and should choose \textbf{at most three} of them into this contest. The prettiness of the $i$-th problem is $a_i$. The authors have to compose the most pretty contest (in other w... | I know about some solutions that are trying to iterate over almost all possible triples, but I have a better and more interesting one. Possibly, it was already mentioned in comments, but I need to explain it. Let's solve the problem greedily. Let's sort the initial array. The first number we would like to choose is the... | [
"brute force",
"math",
"sortings"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
set<int> st;
for (int j = 0; j < n; ++j) {
int x;
cin >> x;
st.insert(x);
}
... |
1183 | G | Candy Box (hard version) | \textbf{This problem is a version of problem D from the same contest with some additional constraints and tasks.}
There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candi... | First of all, to maximize the number of candies in the gift, we can use the following greedy algorithm: let's iterate on the number of candies of some type we take from $n$ to $1$ backwards. For fixed $i$, let's try to find any suitable type of candies. A type is suitable if there are at least $i$ candies of this type ... | [
"greedy",
"implementation",
"sortings"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
scanf("%d", &n);
vector<int> cnt(n);
vector<int> cnt_good(n);
for(int i = 0; i < n; i++)
{
int a, f;
scanf("%d %d", &a, &f);
--a;
cnt[a]++;
if(f) cnt_good[a]++;
}
vector<vector<int> > types(n + 1);
for(int i = 0; i < n; i++)
types... |
1183 | H | Subsequences (hard version) | \textbf{The only difference between the easy and the hard versions is constraints}.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps b... | Firstly, let's calculate the following auxiliary matrix: $lst_{i, j}$ means the maximum position $pos$ that is less than or equal to $i$, and the character $s_{pos} = j$ (in order from $0$ to $25$, 'a' = $0$, 'b' = $1$, and so on). It can be calculated naively or with some easy dynamic programming (initially all $lst_{... | [
"dp",
"strings"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const long long INF64 = 1e12;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
long long k;
cin >> n >> k;
--k; // the whole string costs nothing
string s;
cin >> s;
vector<vector<int>> lst(n, v... |
1185 | A | Ropewalkers | Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.
The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions $a$, $b$ and $c$ respectively. At the end of the pe... | Let's solve the problem when $a \le b \le c$. If it's not true, let's sort $a$, $b$ and $c$. If we move $b$ to any direction, the distance between $b$ and one of $a$ or $c$ decreases, so we get to a worse situation than it was. Thus, we can assume that the position $b$ does not change. Then we should make following con... | [
"math"
] | 800 | def solve(a, b, c, d):
return max(0, d - (b - a)) + max(0, d - (c - b))
def main():
a, b, c, d = map(int, input().split())
a, b, c = sorted((a, b, c))
print(solve(a, b, c, d))
main() |
1185 | B | Email from Polycarp | Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the follo... | It should be noted that if Polycarp press a key once, it's possible to appear one, two or more letters. So, if Polycarp press a key $t$ times, letter will appear at least $t$ times. Also, pressing a particular key not always prints same number of letters. So the possible correct solution is followed: For both words $s$... | [
"implementation",
"strings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
vector<pair<char,int>> split(string s) {
char c = s[0];
int cnt = 1;
vector<pair<char,int>> result;
auto ss = s.c_str();
for (int i = 1; i <= int(s.length()); i++) {
if (ss[i] != c) {
... |
1185 | C1 | Exam in BerSU (easy version) | \textbf{The only difference between easy and hard versions is constraints.}
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are ... | First of all we should precalculate sum $s_i$ of all students' durations for each student. For $i$-th student $s_i = s_{i - 1} + t_i$. Then for each student we can sort all durations $t_i$ of passing exam of students, who are before the current student. So, let's walk by these durations from larger to smaller and calcu... | [
"greedy",
"sortings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
const int T = 100;
int main() {
int n, m;
cin >> n >> m;
int sum = 0;
vector<int> t(n), count(T + 1, 0);
for (int i = 0; i < n; i++) {
cin >> t[i];
}
for (int i = 0; i < n; i++) {
int d = sum + t[i] - m, k = 0;
if (d > 0) {
for (int j = T; j > 0; j... |
1185 | C2 | Exam in BerSU (hard version) | \textbf{The only difference between easy and hard versions is constraints.}
\textbf{If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.}
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of $n$... | Note that $1 \le t_i \le 100$ for each $i$-th student. It brings us to the idea that for each student we only need to know number of students, who are before current student and whose duration of passing the exam is exactly $k$, for all $k$ from $1$ to $100$. Let's use $count_k$ as array of number student, whose durati... | [
"brute force",
"data structures",
"greedy",
"math"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int T = 100;
int main() {
int n, m;
cin >> n >> m;
int sum = 0;
vector<int> t(n), count(T + 1, 0);
for (int i = 0; i < n; i++) {
cin >> t[i];
}
for (int i = 0; i < n; i++) {
int d = sum + t[i] - m, k = 0;
if (d > 0) {
for (int j = T; j > 0; j... |
1185 | D | Extra Element | A sequence $a_1, a_2, \dots, a_k$ is called an arithmetic progression if for each $i$ from $1$ to $k$ elements satisfy the condition $a_i = a_1 + c \cdot (i - 1)$ for some fixed $c$.
For example, these five sequences are arithmetic progressions: $[5, 7, 9, 11]$, $[101]$, $[101, 100, 99]$, $[13, 97]$ and $[5, 5, 5, 5, ... | First of all, we should sort all elements (from smaller to larger, for example, or vice versa). But in the answer is index of element in original sequence, so let's keep the array $c$ of pairs $\{b_i, i\}$, sorted by $b_i$. Now we need to check some simple cases, for example, let's check the $1$-st and the $2$-nd eleme... | [
"implementation",
"math"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<int, int>> b(n);
for (int i = 0; i < n; i++) {
int x;
cin >> x;
b[i] = {x, i};
}
sort(b.begin(), b.end());
vector<int> d(n - 1);
for (int i = 1; i < n; i++) {
d[i - 1] = b[i].first - b[i - 1].first;
}... |
1185 | E | Polycarp and Snakes | After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $n \times m$ (where $n$ is the number of rows, $m$ is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Lati... | Remember, that Polycarp draws snakes in alphabetic order. Firstly we should find the most top left and the most bottom right occurrences of each letter. Secondly we should walk by these letters from 'z' to 'a'. We will skip first not found letters. If for any letter both length and width are larger than $1$, there is n... | [
"brute force",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int min(int a, int b) {
return (a < b) ? a : b;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int t;
cin >> t;
vector<string> lines(2000, "");
vector<int> vertical_min(26, 2001), vertical_ma... |
1185 | F | Two Pizzas | A company of $n$ friends wants to order exactly two pizzas. It is known that in total there are $9$ pizza ingredients in nature, which are denoted by integers from $1$ to $9$.
Each of the $n$ friends has one or more favorite ingredients: the $i$-th of friends has the number of favorite ingredients equal to $f_i$ ($1 \... | The first idea that could help to solve this problem is that the number of ingredients is small ($1 \le b_{it}, a_{jt} \le 9$). It means that we can keep information about favorite ingredients for each person in a bitmask. THe same situation is for pizzas' ingredients. Let's keep two pizzas with the smallest cost for e... | [
"bitmasks",
"brute force"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define pb push_back
#define mp make_pair
#define sqr(a) ((a) * (a))
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define forn(i, n) for (int i = 0; i < int(n); ++i)
#define fore(i, l, r) for (int i = int(l); i < int... |
1185 | G1 | Playlist for Polycarp (easy version) | \textbf{The only difference between easy and hard versions is constraints.}
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes.
In the player, Polycarp stores $n$ songs, eac... | Consider all genres are from $0$ to $2$ instead of from $1$ to $3$. It will be easier to deal with 0-based indices. Let's use DP to calculate $d[mask][lst]$, where $mask$ ($0 \le mask < 2^n$) is a binary mask of songs and $lst$ is a genre of the last song. The value $d[mask][lst]$ means the number of ways to order song... | [
"bitmasks",
"combinatorics",
"dp"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int M = 1000000007;
const int N = 16;
int d[1 << N][4];
int main() {
int n, T;
cin >> n >> T;
vector<int> durs(n), types(n);
forn(i, n) {
cin >> durs[i] >> types[i];
types[i]--;
... |
1185 | G2 | Playlist for Polycarp (hard version) | \textbf{The only difference between easy and hard versions is constraints.}
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes.
In the player, Polycarp stores $n$ songs, eac... | Consider all genres are from $0$ to $2$ instead of from $1$ to $3$. It will be easier to deal with 0-based indices. Let's find two arrays: $a[i][s]$ = number of ways to choose a subset of exactly $i$ songs of the genre $0$ with total duration of exactly $s$; $bc[i][j][s]$ = number of ways to choose a subset of exactly ... | [
"combinatorics",
"dp"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int M = 1000000007;
const int N = 51;
const int S = 2501;
void inc(int& a, int d) {
a += d;
if (a >= M)
a -= M;
}
int a[N][S];
int bc[N][N][S];
int ways[N][N][N][4];
int main() {
int n, T;
... |
1186 | A | Vus the Cossack and a Contest | Vus the Cossack holds a programming competition, in which $n$ people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly $m$ pens and $k$ notebooks.
Determine whether the Cossack can reward \textbf{all} participants, giving each of them at least one pen and at least one ... | Since a pen and a notebook would be given to each participant, the answer is "Yes" if and only if $n \le k$ and $n \le m$. The answer is "No" otherwise. | [
"implementation"
] | 800 | null |
1186 | C | Vus the Cossack and Strings | Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $a$ and $b$. It is known that $|b| \leq |a|$, that is, the length of $b$ is at most the length of $a$.
The Cossack considers every substring of length $|b|$ in string $a$. Let's call this substring $c$. He ... | Let's say that we want to know whether $f(c,d)$ is even for some strings $c$ and $d$. Let's define $cnt_c$ as number of ones in string $c$ and $cnt_d$ as number of ones in $d$. It's easy to see that $f(c,d)$ is even if and only if $cnt_b$ and $cnt_c$ have same parity. In other words if $cnt_c \equiv cnt_d \pmod 2$ then... | [
"implementation",
"math"
] | 1,800 | null |
1186 | D | Vus the Cossack and Numbers | Vus the Cossack has $n$ real numbers $a_i$. It is known that the sum of all numbers is equal to $0$. He wants to choose a sequence $b$ the size of which is $n$ such that the sum of all numbers is $0$ and each $b_i$ is either $\lfloor a_i \rfloor$ or $\lceil a_i \rceil$. In other words, $b_i$ equals $a_i$ rounded up or ... | At first step we should floor all the elements of the array. Then we iterate through the array and do the following: If sum of all the elements of array is equal to $0$, then the algorithm stops. If the decimal part of $a_i$ was not equal to $0$, then we assign $a_i := a_i+1$ Increase $i$ and repeat step 1. If you are ... | [
"constructive algorithms",
"greedy",
"math"
] | 1,500 | null |
1186 | E | Vus the Cossack and a Field | Vus the Cossack has a field with dimensions $n \times m$, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way:
- He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current f... | Let's define $f(x,y)$ a function that returns sum of all elements of submatrix $(1,1,x,y)$ (these $4$ numbers stand for $x_1, y_1, x_2, y_2$ respectively. If we can get value of this function in a fast way, then we can answer the queries quickly by using well known formula for sum on submatrix with cooridantes $x_1, y_... | [
"divide and conquer",
"implementation",
"math"
] | 2,500 | null |
1186 | F | Vus the Cossack and a Graph | Vus the Cossack has a simple graph with $n$ vertices and $m$ edges. Let $d_i$ be a degree of the $i$-th vertex. Recall that a degree of the $i$-th vertex is the number of conected edges to the $i$-th vertex.
He needs to remain not more than $\lceil \frac{n+m}{2} \rceil$ edges. Let $f_i$ be the degree of the $i$-th ver... | At first, let's create a fictive vertex (I'll call it $0$ vertex) and connect it with all of the vertices which have odd degree. Now all the vertices including $0$ vertex have even degree. The statement that $0$ vertex will have even degree too can be easily proven using the fact that the sum of degrees of all vertices... | [
"dfs and similar",
"graphs",
"greedy",
"implementation"
] | 2,400 | null |
1187 | A | Stickers and Toys | Your favorite shop sells $n$ Kinder Surprise chocolate eggs. You know that exactly $s$ stickers and exactly $t$ toys are placed in $n$ eggs in total.
Each Kinder Surprise can be one of three types:
- it can contain a single sticker and \textbf{no toy};
- it can contain a single toy and \textbf{no sticker};
- it can c... | Note, that there are exactly $n - t$ eggs with only a sticker and, analogically, exactly $n - s$ with only a toy. So we need to buy more than $\max(n - t, n - s)$ eggs, or exactly $\max(n - t, n - s) + 1$. | [
"math"
] | 900 | fun main(args: Array<String>) {
val tc = readLine()!!.toInt()
for (i in 1..tc) {
val (n, s, t) = readLine()!!.split(' ').map { it.toInt() }
println(maxOf(n - s, n - t) + 1)
}
} |
1187 | B | Letters Shop | The letters shop showcase is a string $s$, consisting of $n$ lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $s$.
There are $m$ friends, the $i$-th of them is name... | Let's construct the answer letter by letter. How to get enough letters 'a' for the name? Surely, the taken letters will be the first 'a', the second 'a', up to $cnt_a$-th 'a' in string $s$, where $cnt_a$ is the amount of letters 'a' in the name. It's never profitable to skip the letter you need. Do the same for all let... | [
"binary search",
"implementation",
"strings"
] | 1,300 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int n, m;
string s, t;
vector<int> pos[26];
int main() {
cin >> n >> s;
forn(i, n)
pos[s[i] - 'a'].push_back(i + 1);
cin >> m;
forn(i, m){
cin >> t;
vector<int> cnt(26);
for (auto &c : t)
++cnt[c - 'a'... |
1187 | C | Vasya And Array | Vasya has an array $a_1, a_2, \dots, a_n$.
You don't know this array, but he told you $m$ facts about this array. The $i$-th fact is a triple of numbers $t_i$, $l_i$ and $r_i$ ($0 \le t_i \le 1, 1 \le l_i < r_i \le n$) and it means:
- if $t_i=1$ then subbarray $a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$ is sorted in non-d... | Let's consider array $b_1, b_2, \dots , b_{n-1}$, such that $b_i = a_{i + 1} - a_i$. Then subarray $a_l, a_{l+1}, \dots , a_r$ is sorted in non-decreasing order if and only if all elements $b_l, b_{l + 1} , \dots , b_{r - 1}$ are greater or equal to zero. So if we have fact $t_i = 1, l_i, r_i$, then all elements $b_{l_... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
int n, m;
int l[N], r[N], s[N];
int d[N];
int dx[N];
int res[N];
int nxt[N];
int main() {
scanf("%d %d", &n, &m);
for(int i = 0; i < m; ++i){
scanf("%d %d %d", s + i, l + i, r + i);
--l[i], --r[i];
if(s[i] == 1)
++d[l[i]], --d[r[i... |
1187 | D | Subarray Sorting | You are given an array $a_1, a_2, \dots, a_n$ and an array $b_1, b_2, \dots, b_n$.
For one operation you can sort in non-decreasing order any subarray $a[l \dots r]$ of the array $a$.
For example, if $a = [4, 2, 2, 1, 3, 1]$ and you choose subbarray $a[2 \dots 5]$, then the array turns into $[4, 1, 2, 2, 3, 1]$.
You... | Let's reformulate this problem in next form: we can sort only subarray of length 2 (swap two consecutive elements $i$ and $i+1$ if $a_i > a_{i + 1}$). It is simular tasks because we can sort any array by sorting subbarray of length 2 (for example bubble sort does exactly that). Now lets look at elements $a_1$ and $b_1$... | [
"data structures",
"sortings"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
const int INF = int(1e9) + 99;
int t, n;
int a[N], b[N];
vector <int> p[N];
int st[4 * N + 55];
int getMin(int v, int l, int r, int L, int R){
if(L >= R) return INF;
if(l == L && r == R)
return st[v];
int mid = (l + r) / 2;
return min... |
1187 | E | Tree Painting | You are given a tree (an undirected connected acyclic graph) consisting of $n$ vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to \textbf{... | I should notice that there is much simpler idea and solution for this problem without rerooting technique but I will try to explain rerooting as the main solution of this problem (it can be applied in many problems and this is just very simple example). What if the root of the tree is fixed? Then we can notice that the... | [
"dfs and similar",
"dp",
"trees"
] | 2,100 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef long long li;
using namespace std;
const int N = 200 * 1000 + 13;
int n;
vector<int> g[N];
int siz[N];
li sum[N];
void init(int v, int p = -1){
siz[v] = 1;
sum[v] = 0;
for (auto u : g[v]) if (u != p){
init(u, v);
siz[v] +... |
1187 | F | Expected Square Beauty | Let $x$ be an array of integers $x = [x_1, x_2, \dots, x_n]$. Let's define $B(x)$ as a minimal size of a partition of $x$ into subsegments such that all elements in each subsegment are equal. For example, $B([3, 3, 6, 1, 6, 6, 6]) = 4$ using next partition: $[3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6]$.
Now you don't have any exac... | As usual with tasks on an expected value, let's denote $I_i(x)$ as indicator function: $I_i(x) = 1$ if $x_i \neq x_{i - 1}$ and $0$ otherwise; $I_1(x) = 1$. Then we can note that $B(x) = \sum\limits_{i = 1}^{n}{I_i(x)}$. Now we can make some transformations: $E(B^2(x)) = E((\sum\limits_{i = 1}^{n}{I_i(x)})^2) = E(\sum\... | [
"dp",
"math",
"probabilities"
] | 2,500 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
const int MOD = int(1e9) + 7;
int norm(int a) {
while(a >= MOD) a -= MOD;
while(a < 0) a += MOD;... |
1187 | G | Gang Up | The leader of some very secretive organization has decided to invite all other members to a meeting. All members of the organization live in the same town which can be represented as $n$ crossroads connected by $m$ two-directional streets. The meeting will be held in the leader's house near the crossroad $1$. There are... | First of all, one crucial observation is that no person should come to the meeting later than $100$ minutes after receiving the message: the length of any simple path in the graph won't exceed $49$, and even if all organization members should choose the same path, we can easily make them walk alone if the first person ... | [
"flows",
"graphs"
] | 2,500 | #include<bits/stdc++.h>
using namespace std;
struct edge
{
int y, c, f, cost;
edge() {};
edge(int y, int c, int f, int cost) : y(y), c(c), f(f), cost(cost) {};
};
vector<edge> e;
const int N = 14043;
vector<int> g[N];
long long ans = 0;
long long d[N];
int p[N];
int pe[N];
int inq[N];
const long long INF64 = (... |
1188 | A2 | Add on a Tree: Revolution | \textbf{Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.}
You are given a tree with $n$ nodes. In the beginning, $0$ is written on all edges. In one operation, you can choose any $2$ disti... | We claim, that the answer is YES iff there is no vertex with degree 2. After this, it's easy to get a solution for first subtask in O(n). ProofProof of necessity If there is a vertex of degree 2, then after any number of operations numbers which are written on two outcoming edges will be equal. Indeed, any path between... | [
"constructive algorithms",
"dfs and similar",
"implementation",
"trees"
] | 2,500 | "#include <bits/stdc++.h>\n\nusing namespace std;\n#define mp make_pair\n\nvector<vector<int>> ops;\nvector<vector<pair<int, int>>> G;\nvector<vector<int>> leaves;\nvector<bool> visited;\nvector<int> pr;\nint root = 1;\n\nvoid dfs1(int s)\n{\n visited[s] = true;\n for (auto it: G[s]) if (!visited[it.first]) {pr[i... |
1188 | B | Count Pairs | You are given a \textbf{prime} number $p$, $n$ integers $a_1, a_2, \ldots, a_n$, and an integer $k$.
Find the number of pairs of indexes $(i, j)$ ($1 \le i < j \le n$) for which $(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$. | Let's transform condtition a ittle bit. a_i - a_j \not\equiv 0 mod p, so condtition is equivalent: (a_i - a_j)(a_i + a_j)(a^2_{i} + a^2_{j}) \equiv (a_i - a_j)k \Leftrightarrow a^4_{i} - a^4_{j} \equiv ka_i - ka_j \Leftrightarrow a^4_{i} - ka_i \equiv a^4_{j} - ka_j. That's why we just need to count number of pairs of ... | [
"math",
"matrices",
"number theory",
"two pointers"
] | 2,300 | "#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nint mod;\n\nint sum(int a, int b) {\n int s = a + b;\n if (s >= mod) s -= mod;\n return s;\n}\n\nint sub(int a, int b) {\n int s = a - b;\n if (s < 0) s += mod;\n return s;\n}... |
1188 | C | Array Beauty | Let's call beauty of an array $b_1, b_2, \ldots, b_n$ ($n > 1$) — $\min\limits_{1 \leq i < j \leq n} |b_i - b_j|$.
You're given an array $a_1, a_2, \ldots a_n$ and a number $k$. Calculate the sum of beauty over all subsequences of the array of length exactly $k$. As this number can be very large, output it modulo $99... | First of all, let's learn how to solve the following subtask: For given x how many subsequences of length k have beauty at least x? If we know that the answer for x is p_x, than the answer for original task is p_1 + p_2 + \ldots + p_{max(a)}, where max(a) is maximum in array a. Let's solve subtask. Suppose, that array ... | [
"dp"
] | 2,500 | "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nconst int mod = 998244353;\nint sum(int a, int b) {\n int s = (a + b);\n if (s >= mod) s -= mod;\n return s;\n}\nint sub(int a, int b) {\n int s = a - b;\n if (s < 0) s += mod;\n return s;\n}\nint mult(int... |
1188 | D | Make Equal | You are given $n$ numbers $a_1, a_2, \dots, a_n$. In one operation we can add to any one of those numbers a nonnegative integer power of $2$.
What is the smallest number of operations we need to perform to make all $n$ numbers equal? It can be proved that under given constraints it doesn't exceed $10^{18}$. | We will suppose, that array is sorted. Let x be the final number. Than x \ge a_n. Also, if we define bits[c] - as number of ones in binary notation of c, than, to get x from a_i we will spend at least bits[x - a_i] moves(it follows from the fact, that minumum number of powers of two, which in sum are equal to the numbe... | [
"dp"
] | 3,100 | "#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nint n;\nconst int maxN = 2 * (int)1e5 + 100;\nconst int LIM = 62;\nll a[maxN];\nll dp[LIM + 10][maxN];\nconst ll one = 1;\nconst ll INF = (one << LIM);\nint bit(int x) {\n int bt = 0;\n f... |
1188 | E | Problem from Red Panda | At Moscow Workshops ICPC team gets a balloon for each problem they solved first. Team MSU Red Panda got so many balloons that they didn't know how to spend them. So they came up with a problem with them.
There are several balloons, not more than $10^6$ in total, each one is colored in one of $k$ colors. We can perform... | We'll suppose(as in 3 tasks before), that the array is sorted. Our operation is equivalent to choosing some 1 \le i \le k and increasing a_i by k - 1, and decreasing remaining a_i by one. To solve the task, we need to make some claims: \textbf{Claim 1} Difference a_i - a_j mod k doesn't change for any i, j. Moreover, i... | [
"combinatorics"
] | 3,300 | "#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nconst int mod = 998244353;\n\nint sum(int a, int b) {\n int s = a + b;\n if (s >= mod) s -= mod;\n return s;\n}\n\nint sub(int a, int b) {\n int s = a - b;\n if (s < 0) s += mod;... |
1189 | A | Keanu Reeves | After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.
Let's call a string consisting of only zeroes and ones \textbf{good} if it contains \textbf{different} numbers of zeroes... | If the string is good, then answer it's itself. Otherwise, there are at least two strings in answer, and we can print substring without its last symbol and its last symbol separately. Complexity O(n). | [
"strings"
] | 800 | "n = int(input())\ns = input()\nbal = 0\nfor c in s:\n if c == '0':\n bal += 1\n else:\n bal -= 1\nif bal != 0:\n print('1' + '\\n' + s)\nelse:\n print('2' + \"\\n\" + s[0:-1] + \" \" + s[-1])" |
1189 | B | Number Circle | You are given $n$ numbers $a_1, a_2, \ldots, a_n$. Is it possible to arrange them in a circle in such a way that every number is \textbf{strictly} less than the sum of its neighbors?
For example, for the array $[1, 4, 5, 6, 7, 8]$, the arrangement on the left is valid, while arrangement on the right is not, as $5\ge 4... | Let's suppose that array is sorted. First of all, if a_n \ge a_{n - 1} + a_{n - 2}, than the answer is - NO (because otherwise a_{n} is not smaller than sum of the neighbors). We claim, that in all other cases answer is - YES. One of the possible constructions (if the array is already sorted) is: a_{n - 2}, a_{n}, a_{n... | [
"greedy",
"math",
"sortings"
] | 1,100 | "n = int(input())\na = list(map(int, input().split()))\na.sort()\nif a[n-1]>=a[n-2] + a[n-3]:\n\tprint(\"NO\")\nelse:\n print(\"YES\")\n for i in range(n-1, -1, -2):\n\t print(a[i], end = \" \")\n for i in range(n%2, n, 2):\n\t print(a[i], end = \" \")" |
1189 | C | Candies! | Consider a sequence of digits of length $2^k$ $[a_1, a_2, \ldots, a_{2^k}]$. We perform the following operation with it: replace pairs $(a_{2i+1}, a_{2i+2})$ with $(a_{2i+1} + a_{2i+2})\bmod 10$ for $0\le i<2^{k-1}$. For every $i$ where $a_{2i+1} + a_{2i+2}\ge 10$ we get a candy! As a result, we will get a sequence of ... | Solution 1 (magic) Claim: f([a_1, a_2, \ldots, a_{2^k}]) = \lfloor \frac{a_1 + a_2 + \ldots + a_{2^k}}{10} \rfloor. Clearly, using it we can answer queries in O(1) if we create array prefsum, in which prefsum[i] = a_1 + \ldots + a_i. Proof of claimImagine, that candy is equal to number 10. Then sum of all numbers doesn... | [
"data structures",
"dp",
"implementation",
"math"
] | 1,400 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint main() {\n\n int n;\n cin>>n;\n vector<int> a(n);\n for (int i = 0; i<n; i++) cin>>a[i];\n \n vector<vector<pair<int, int>>> dp(20);\n int cur = 1;\n for (int i = 0; i<n; i++) dp[0].push_back(make_pair(a[i], 0));\n for (int deg = 1; d... |
1190 | A | Tokitsukaze and Discard Items | Recently, Tokitsukaze found an interesting game. Tokitsukaze had $n$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $m$ ($1 \le m \le n$) special items of them.
These $n$ items are marked with indices from $1$ to $n$. In the beginning, the item with ind... | The order of discarding is given, so we can simulate the process of discarding. In each time, we can calculate the page that contains the first special item that has not been discarded, and then locate all the special items that need to be discarded at one time. Repeat this process until all special items are discarded... | [
"implementation",
"two pointers"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX=1e5+10;
ll p[MAX];
int main()
{
ll n,m,k;
scanf("%lld%lld%lld",&n,&m,&k);
for(int i=1;i<=m;i++) scanf("%lld",&p[i]);
int ans=0;
int sum=0;
int now=1;
while(now<=m)
{
ll r=((p[now]-sum-1)/k+1)*k+sum;
// cout<<"r:"<<r<<endl;
wh... |
1190 | B | Tokitsukaze, CSL and Stone Game | Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are $n$ piles of stones, the $i$-th pile of which has $a_i$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player lo... | Unless the first player must lose after the first move, the numbers of stones in these piles should form a permutation obtained from $0$ to $(n - 1)$ in the end, in order to ensure that there are no two piles include the same number of stones. Let's use $cnt[x]$ to represent the number of piles which have exactly $x$ s... | [
"games"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int maxn = (int)1e5 + 1;
int n, a[maxn], c[3];
void update(int x, int d) {
static map<int, int> ctr;
int &v = ctr[x];
--c[min(v, 2)];
v += d;
++c[min(v, 2)];
}
int main() {
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d", a + i);
update(a[i], 1);
... |
1190 | C | Tokitsukaze and Duel | "Duel!"
Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.
There are $n$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping ca... | If a player can make a move from a situation to that situation again, this player will not lose. Except for some initial situations, one can move from almost every situation to itself. Based on these two conclusions, we can get a solution. If Tokitsukaze cannot win after her first move, she cannot win in the future. In... | [
"brute force",
"games",
"greedy"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
const int MAXN=1000005;
int n,k,T;
int a[MAXN],sum[MAXN];
int q_sum(int l,int r)
{
if(l>r)return 0;
return sum[r]-sum[l-1];
}
bool check_fir()
{
for(int i=1;i+k-1<=n;++i)
{
int lala=q_sum(1,i-1)+q_sum(i+k,n);
if(lala==0||lala+k==n)return true;... |
1190 | D | Tokitsukaze and Strange Rectangle | There are $n$ points on the plane, the $i$-th of which is at $(x_i, y_i)$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.
The strange area is enclosed by three lines, $x = l$, $y = a$ and $x = r$, as its left side, its bottom side and its right side respectively, where $l$, $... | For each strange rectangular area and its corresponding set of points, we only need to focus on the lowest $y$-coordinate $yB$, the leftmost $x$-coordinate $xL$ and the rightmost $x$-coordinate $xR$ of points in this set. Different sets must have different $yB$, $xL$, $xR$, so we can count them by enumerating these val... | [
"data structures",
"divide and conquer",
"sortings",
"two pointers"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
//priority_queue<int> q;
//priority_queue<int,vector<int>, greater<int> > q;
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> le... |
1190 | E | Tokitsukaze and Explosion | Tokitsukaze and her friends are trying to infiltrate a secret base built by Claris. However, Claris has been aware of that and set a bomb which is going to explode in a minute. Although they try to escape, they have no place to go after they find that the door has been locked.
At this very moment, CJB, Father of Tokit... | It is obvious that we can binary search the answer because we can pull any line closer to $O$ and the situation won't change. Applying a binary search, we focus on if it is possible to set $m$ barriers with the same distance to $O$ and meet the requirement. By doing so, we can draw a circle whose center is $O$ such tha... | [
"binary search",
"greedy"
] | 3,100 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double db;
const int MAXN=100005;
const int DEP=18;
vector<pair<int,int> > filter(int n,vector<pair<int,int> > &seg)
{
vector<pair<int,int> > now;
for(auto &t:seg)
{
t.second=(t.second+n-1)%n;
int l=t.first,r=... |
1190 | F | Tokitsukaze and Powers | Tokitsukaze is playing a room escape game designed by SkywalkerT. In this game, she needs to find out hidden clues in the room to reveal a way to escape.
After a while, she realizes that the only way to run away is to open the digital door lock since she accidentally went into a secret compartment and found some clues... | Firstly, let me briefly review this problem for you. Given integers $n$, $m$ and $p$ ($n > 0$, $m > 1$, $p \neq 0$), we denote $S = \lbrace x | x \in \mathbb{Z}, 0 \leq x < m, \gcd(m, x) = 1 \rbrace$ and $T = \lbrace p^e \bmod m | e \in \mathbb{Z}, e \geq 0 \rbrace$, where $\gcd(m, x)$ means the greatest common divisor... | [
"number theory",
"probabilities"
] | 3,400 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
inline ll mul_mod(ll a, ll b, ll m)
{
a=(a%m+m)%m,b=(b%m+m)%m;
return ((a*b-(ll)(1.0L*a/m*b+0.5L)*m)%m+m)%m;
}
inline ll pow_mod(ll a,ll k,ll m)
{
ll res=1;
while(k)
{
if(k&1)res=mul_mod(res,... |
1191 | A | Tokitsukaze and Enhancement | Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP.
In general, different values of HP are grouped into $4$ categories:
- Category $A$ if HP is in the form of $(4 n + 1)$, that is, when divided by $4$, the remaind... | Just enumerating the increment can pass. However, by increasing at most $2$ points, the value of her HP can always become an odd number, and thus the highest possible level is either $A$ or $B$. We can just solve case by case. | [
"brute force"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int x;
cin>>x;
if(x%4==0) puts("1 A");
else if(x%4==1) puts("0 A");
else if(x%4==2) puts("1 B");
else if(x%4==3) puts("2 A");
return 0;
} |
1191 | B | Tokitsukaze and Mahjong | Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (\textbf{manzu}, \textbf{pinzu} or \textbf{souzu}) and a number (a digit ranged from $1$ to $9$). In this problem, we use one digit and one lowerca... | There are only two types of mentsus, so you can enumerate the mentsu you want her to form, and check the difference between that and those currently in her hand. Alternatively, you can find out that the answer is at most $2$, since she can draw two extra identical tiles which are the same as one of those in her hand. Y... | [
"brute force",
"implementation"
] | 1,200 | //#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;
//defines
typedef long long ll;
typedef long double ld;
#define TIME clock() * 1.0 / CLOCKS_PER_SEC
#define prev _prev
#define y0 y00
//permanent constants
const ld pi = acos(-1.0);
const int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, ... |
1194 | A | Remove a Progression | You have a list of numbers from $1$ to $n$ written from left to right on the blackboard.
You perform an algorithm consisting of several steps (steps are $1$-indexed). On the $i$-th step you wipe the $i$-th number (considering only \textbf{remaining} numbers). You wipe the whole number (not one digit).
When there are ... | After some simulation of the given algorithm (in your head, on paper or on a computer) we can realize that exactly all odd numbers are erased. So, all even numbers remain, and the answer is $2x$. | [
"math"
] | 800 | fun main(args: Array<String>) {
val T = readLine()!!.toInt()
for (t in 1..T) {
val (n, x) = readLine()!!.split(' ').map { it.toLong() }
println(x * 2)
}
} |
1194 | B | Yet Another Crosses Problem | You are given a picture consisting of $n$ rows and $m$ columns. Rows are numbered from $1$ to $n$ from the top to the bottom, columns are numbered from $1$ to $m$ from the left to the right. Each cell is painted either black or white.
You think that this picture is not interesting enough. You consider a picture to be ... | Let's consider each cell as a center of a cross and take the fastest one to paint. Calculating each time naively will take $O(nm(n + m))$ overall, which is too slow. Notice how the answer for some cell $(x, y)$ can be represented as $cnt_{row}[x] + cnt_{column}[y] -$ ($1$ if $a[x][y]$ is white else $0$), where $cnt_{ro... | [
"implementation"
] | 1,300 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int q;
cin >> q;
forn(_, q){
int n, m;
cin >> n >> m;
vector<string> s(n);
forn(i, n)
cin >> s[i];
vector<int> cntn(n), cntm(m);
forn(i, n) forn(j, m){
cntn[i] += (s[i][j] == '.');
... |
1194 | C | From S To T | You are given three strings $s$, $t$ and $p$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose any character from $p$, erase it from $p$ and insert it into string $s$ (you may insert this character anywhere you want: in the ... | If the answer exists then each element of string $s$ matches with some element of string $t$. Thereby string $s$ must be a subsequence of string $t$. Let $f(str, a)$ equal to the number of occurrences of the letter $a$ in the string $str$. Then for any letter $a$ condition $f(s, a) + f(p, a) \ge f(t, a)$ must be hold. ... | [
"implementation",
"strings"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int q;
string s, t, p;
int cnt[30];
int main() {
cin >> q;
for(int iq = 0; iq < q; ++iq){
cin >> s >> t >> p;
memset(cnt, 0, sizeof cnt);
for(auto x : p)
++cnt[x - 'a'];
bool ok = true;
int is = 0, it = 0;
while(is < s.size()){
if(it == t.size()){
... |
1194 | D | 1-2-K Game | Alice and Bob play a game. There is a paper strip which is divided into $n + 1$ cells numbered from left to right starting from $0$. There is a chip placed in the $n$-th cell (the last one).
Players take turns, Alice is first. Each player during his or her turn has to move the chip $1$, $2$ or $k$ cells to the left (s... | Let's determine for each cell whether it's winning or losing position (we can do it since the game is symmetric and doesn't depend on a player). The $0$-th cell is obviously losing, the $1$-st and $2$-nd ones is both winning, since we can move to the $0$-th cell and put our opponent in the losing position (here comes c... | [
"games",
"math"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int n, k;
inline bool read() {
if(!(cin >> n >> k))
return false;
return true;
}
void solve() {
bool win = true;
if(k % 3 == 0) {
int np = n % (k + 1);
if(np % 3 == 0 && np != k)
win = false;
} else {
int np = n % 3;
if(np == 0)
win = false;
}
pu... |
1194 | E | Count The Rectangles | There are $n$ segments drawn on a plane; the $i$-th segment connects two points ($x_{i, 1}$, $y_{i, 1}$) and ($x_{i, 2}$, $y_{i, 2}$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $i \in [1, n]$ either $x_{i, 1} = x_{i, 2}$ or $y_{i, 1} = y_{i, 2}$ (but only one of these co... | Let's iterate over the lower horizontal segment. Denote its coordinates as ($xl, yh$) and ($xr, yh$), where $xl < xr$. We call vertical segment ($x_{i, 1}$, $y_{i, 1}$), ($x_{i, 2}$, $y_{i, 2}$) good, if followings conditions holds: $xl \le x_{i, 1} = x_{i, 2} \le xr$; $min(y_{i, 1}, y_{i, 2}) \le yh$. Now let's use th... | [
"bitmasks",
"brute force",
"data structures",
"geometry",
"sortings"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define mp make_pair
const int N = 10009;
const int INF = 1000000009;
int n;
vector <pair<int, int> > vs[N], hs[N];
int f[N];
vector <int> d[N];
void upd(int pos, int x){
for(; pos < N; pos |= pos + 1)
f[pos] += x;
}
int get(int pos){
int res = 0;
for(; pos >= 0... |
1194 | F | Crossword Expert | Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $T$ seconds after coming.
Fortunately, Adilbek can spend time with... | Let's use (as usual) linearity of an expected value. $E = \sum\limits_{i = 1}^{n}{E(I(i))}$ where $I(i)$ is an indicator function and equal to $1$ iff Adilbek will be able to solve the $i$-th crossword. How to calculate $I(i)$? If $\sum\limits_{j = 1}^{i}{t_i} > T$ then $I(i)$ is always $0$. On the other hand, if $\sum... | [
"combinatorics",
"dp",
"number theory",
"probabilities",
"two pointers"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
return out... |
1194 | G | Another Meme Problem | Let's call a fraction $\frac{x}{y}$ good if there exists at least one another fraction $\frac{x'}{y'}$ such that $\frac{x}{y} = \frac{x'}{y'}$, $1 \le x', y' \le 9$, the digit denoting $x'$ is contained in the decimal representation of $x$, and the digit denoting $y'$ is contained in the decimal representation of $y$. ... | Let's fix an irreducible fraction $\frac{X}{Y}$ such that $1 \le X, Y \le 9$. Obviously, each good fraction is equal to exactly one of such irreducible fractions. So if we iterate on $X$ and $Y$, check that $gcd(X, Y) = 1$ and find the number of good fractions that are equal to $\frac{X}{Y}$, we will solve the problem.... | [
"dp"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
const int N = 105;
int a[N];
int n;
int numPos[10], denPos[10];
int num, den;
const int MOD = 998244353;
struct halfState
{
int carry;
int mask;
bool comp;
halfState() {};
halfState(int carry, int mask, bool comp) : carry(carry), mask(mask), comp(comp) {};
};
boo... |
1195 | A | Drinks Choosing | Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are $n$ students living in a building, and for each of them the favorite drink $a_i$ is known. So you know $n$ i... | Let's take a look on a students. If two students have the same favorite drink, let's take one set with this drink. Let the number of such students (which we can satisfy as pairs) be $good$. Because the number of sets is $\lceil\frac{n}{2}\rceil$ we always can do it. So there are students which are the only with their f... | [
"greedy",
"math"
] | 1,000 | // Created by Nikolay Budin
#ifdef LOCAL
# define _GLIBCXX_DEBUG
#else
# define cerr __get_ce
#endif
#include <bits/stdc++.h>
#define ff first
#define ss second
#define szof(x) ((int)x.size())
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef unsigned long long u... |
1195 | B | Sport Mafia | Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.
For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs $n$ actions. The first action performed is to put a single candy into the box. For each of the remaini... | In fact, we need to solve the following equation: $\frac{x(x+1)}{2} - (n - x) = k$ and when we will find $x$ we need to print $n-x$ as the answer. $\frac{x(x+1)}{2}$ is the number of candies Alya will put into the box with $x$ turns (sum of arithmetic progression). This equation can be solved mathematically. The only p... | [
"binary search",
"brute force",
"math"
] | 1,000 | #include <iostream>
#include <cmath>
int main() {
long long n, k;
std::cin >> n >> k;
std::cout << static_cast<long long>(round(n + 1.5 - sqrt(2 * (n + k) + 2.75)));
return 0;
} |
1195 | C | Basketball Exercise | Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $2 \cdot n$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $n$ people in each row). Students are numbered from $1$ to $n$ in each row in... | This is pretty standard dynamic programming problem. Let $dp_{i, 1}$ be the maximum total height of team members if the last student taken has the position $(i-1, 1)$, $dp_{i, 2}$ is the same but the last student taken has the position $(i-1, 2)$ and $dp_{i, 3}$ the same but we didn't take any student from position $i-... | [
"dp"
] | 1,400 | // Created by Nikolay Budin
#ifdef LOCAL
# define _GLIBCXX_DEBUG
#else
# define cerr __get_ce
#endif
#include <bits/stdc++.h>
#define ff first
#define ss second
#define szof(x) ((int)x.size())
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef unsigned long long u... |
1195 | D1 | Submarine in the Rybinsk Sea (easy edition) | This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.
A team of SIS students is going to make a trip on a submar... | Let's take a look into some number $a = a_1, a_2, \dots, a_{len}$, where $len$ is the length of each number in the array. We know that in $n$ cases it will be the first argument of the function $f(a, b)$ (where $b$ is some other number), and in $n$ cases it will be the second argument. What it means? It means that $a_1... | [
"combinatorics",
"math",
"number theory"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int a, int b) {
a += b;
if (a >= MOD) a -= MOD;
if (a < 0) a += MOD;
return a;
}
int mul(int a, int b) {
return a * 1ll * b % MOD;
}
int len;
vector<int> pw10;
int f(int a) {
int pos = 0;
int res = 0;
while (a > 0) {
int cu... |
1195 | D2 | Submarine in the Rybinsk Sea (hard edition) | This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$.
A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, th... | Let $cnt_{len}$ be the number of $a_i$ with length $len$. We will calculate each number's contribution in the answer separately. When we calculate the contribution of the current number in the answer, let's iterate over all lengths $l$ from $1$ to $L$ where $L$ is the maximum length of some number in the array and add ... | [
"combinatorics",
"math",
"number theory"
] | 1,800 | // Created by Nikolay Budin
#ifdef LOCAL
# define _GLIBCXX_DEBUG
#else
# define cerr __get_ce
#endif
#include <bits/stdc++.h>
#define ff first
#define ss second
#define szof(x) ((int)x.size())
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef unsigned long long u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.