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
1006
B
Polycarp's Practice
Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cann...
The maximum possible total profit you can obtain is the sum of the $k$ largest values of the given array. This is obvious because we can always separate these $k$ maximums and then extend the segments corresponding to them to the left or to the right and cover the entire array. I suggest the following: extract $k$ larg...
[ "greedy", "implementation", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<pair<int, int>> res(n); vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> res[i].first; a[i] = res[i].first; res...
1006
C
Three Parts of the Array
You are given an array $d_1, d_2, \dots, d_n$ consisting of $n$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possib...
Since the given array consists of positive integers, for each value of $a$, there can be at most one value of $c$ such that $sum_1 = sum_3$. We can use binary search on the array of prefix sums of $d$ to find the correct value of $c$, given that it exists. If it does exist and $a+c \le n$, this is a candidate solution ...
[ "binary search", "data structures", "two pointers" ]
1,200
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; int n; int a[200005]; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cerr.tie(nullptr); cin >> n; for (int i=1; i<=n; i++) cin >> a[i]; int i = 0...
1006
D
Two Strings Swaps
You are given two strings $a$ and $b$ consisting of lowercase English letters, both of length $n$. The characters of both strings have indices from $1$ to $n$, inclusive. You are allowed to do the following changes: - Choose any index $i$ ($1 \le i \le n$) and swap characters $a_i$ and $b_i$; - Choose any index $i$ (...
Let's divide all characters of both strings into groups in such a way that characters in each group can be swapped with each other with changes. So, there will be following groups: $\{a_1, a_n, b_1, b_n\}$, $\{a_2, a_{n - 1}, b_2, b_{n - 1}\}$ and so on. Since these groups don't affect each other, we can calculate the ...
[ "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #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(r); ...
1006
E
Military Problem
In this problem you will have to help Berland army with organizing their command delivery system. There are $n$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $a$ is the direct superior of off...
Let's form the following vector $p$: we run DFS from the first vertex and push the vertex $v$ to the vector when entering this vertex. Let $tin_v$ be the position of the vertex $v$ in the vector $p$ (the size of the vector $p$ in moment we call DFS from the vertex $v$) and $tout_v$ be the position of the first vertex p...
[ "dfs and similar", "graphs", "trees" ]
1,600
#include <bits/stdc++.h> using namespace std; int n, q; vector<vector<int>> tree; int current_preorder; vector<int> preorder, max_preorder; vector<int> sorted_by_preorder; void Dfs(int w) { sorted_by_preorder[current_preorder] = w; preorder[w] = current_preorder++; for (int c : tree[w]) { Dfs(c); } ma...
1006
F
Xor-Paths
There is a rectangular grid of size $n \times m$. Each cell has a number written on it; the number on the cell ($i, j$) is $a_{i, j}$. Your task is to calculate the number of paths from the upper-left cell ($1, 1$) to the bottom-right cell ($n, m$) meeting the following constraints: - You can move to the right or to t...
This is a typical problem on the meet-in-the-middle technique. The number of moves we will made equals $n + m - 2$. So if $n + m$ would be small enough (25 is the upper bound, I think), then we can just run recursive backtracking in $O(2^{n + m - 2})$ or in $O($${n + m - 2}\choose{m - 1}$$\cdot (n + m - 2))$ to iterate...
[ "bitmasks", "brute force", "dp", "meet-in-the-middle" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 20; map<long long, int> v[N][N]; int n, m; int half; long long k; long long a[N][N]; long long ans; void calclf(int x, int y, long long val, int cnt) { val ^= a[x][y]; if (cnt == half) { ++v[x][y][val]; return; } if (x + 1 < n) calclf(x + 1, y, ...
1007
A
Reorder the Array
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array $[10, 20, 30, 40]$, we can ...
The answer is $n$ minus maximal number of equal elements. Let the maximal number of equals be $x$. Let's proove that $n-x$ is reachable. It's clear that for every permutation of the array the answer will be the same, so let's sort the array in non-decreasing order. Now we should just make a left shift on $x$. After it ...
[ "combinatorics", "data structures", "math", "sortings", "two pointers" ]
1,300
null
1007
B
Pave the Parallelepiped
You are given a rectangular parallelepiped with sides of positive integer lengths $A$, $B$ and $C$. Find the number of different groups of three integers ($a$, $b$, $c$) such that $1\leq a\leq b\leq c$ and parallelepiped $A\times B\times C$ can be paved with parallelepipeds $a\times b\times c$. Note, that all small pa...
First solution. First, for every natural number up to $10^5$ we count its number of divisors in $O(\sqrt{n})$. Also for every unordered set of $3$ masks $(m_1, m_2, m_3)$ of length $3$ we check if there is a way to enumerate them in such a way that $1 \in m_1$, $2 \in m_2$ and $3 \in m_3$. We will call such sets accept...
[ "bitmasks", "brute force", "combinatorics", "math", "number theory" ]
2,400
null
1007
C
Guess two numbers
\textbf{This is an interactive problem.} Vasya and Vitya play a game. Vasya thought of two integers $a$ and $b$ from $1$ to $n$ and Vitya tries to guess them. Each round he tells Vasya two numbers $x$ and $y$ from $1$ to $n$. If both $x=a$ and $y=b$ then Vitya wins. Else Vasya must say one of the three phrases: - $x$...
First solution: Let's keep the set of possible answers as a union of three rectangles forming an angle: $A = \left[ x_l, x_m \right) \times \left[ y_l, y_m \right)$, $B = \left[ x_l, x_m \right) \times \left[ y_m, y_r \right)$ and $C = \left[ x_m, x_r \right) \times \left[ y_l, y_m \right)$, where $x_l < x_m \leq x_r$ ...
[ "binary search", "interactive" ]
3,000
null
1007
D
Ants
There is a tree with $n$ vertices. There are also $m$ ants living on it. Each ant has its own color. The $i$-th ant has two favorite pairs of vertices: ($a_i, b_i$) and ($c_i, d_i$). You need to tell if it is possible to paint the edges of the tree in $m$ colors so that every ant will be able to walk between vertices f...
Slow solution. We need to choose one of two paths for each ant so that they will not contain a common edge. Let's make a 2-SAT, and for each ant, we will create two contrary vertices: one will denote that we take the first path, and another will denote that we take the second path. Then for every two paths which share ...
[ "2-sat", "data structures", "trees" ]
3,200
null
1007
E
Mini Metro
In a simplified version of a "Mini Metro" game, there is only one subway line, and all the trains go in the same direction. There are $n$ stations on the line, $a_i$ people are waiting for the train at the $i$-th station at the beginning of the game. The game starts at the beginning of the $0$-th hour. At the end of ea...
Let's enumerate the hours and the stations starting from zero. Let's add a station to the end with an infinite number of people and infinite capacity. It is obvious that it will not affect the answer. Also, every train now will be filled completely. Let's calculate $sa[p]$, $sb[p]$ and $sc[p]$: the sum of $a[i]$, $b[i]...
[ "dp" ]
3,400
null
1008
A
Romaji
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
You need to check if after every letter except one of for these "aouien", there goes one of these "aouie". Do not forget to check the last letter.
[ "implementation", "strings" ]
900
null
1008
B
Turn the Rectangles
There are $n$ rectangles in a row. You can either turn each rectangle by $90$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. \textbf{You can not change the order of t...
You need to iterate over the rectangles from left to right and turn each rectangle in such a way that its height is as big as possible but not greater than the height of the previous rectangle (if it's not the first one). If on some iteration there is no such way to place the rectangle, the answer is "NO".
[ "greedy", "sortings" ]
1,000
null
1009
A
Game Shopping
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$. Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$. Games in the shop are ordered from left to right, Maxim tries to buy ...
Let's keep the variable $pos$ which will represent the number of games Maxim buy. Initially $pos = 0$. Assume that arrays $a$ and $c$ are 0-indexed. Then let's iterate over all $i = 0 \dots n - 1$ and if $pos < m$ and $a[pos] \ge c[i]$ make $pos := pos + 1$. So $pos$ will be the answer after this cycle.
[ "implementation" ]
800
n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) pos = 0 for i in a: pos += (pos < len(b) and b[pos] >= i) print(pos)
1009
B
Minimum Ternary String
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2'). You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa). For e...
Let's notice that described swaps allows us to place any '1' character to any position of the string $s$ (relative order of '0' and '2' obviously cannot be changed). Let's remove all '1' characters from the string $s$ (and keep their count in some variable). Now more profitable move is to place all the '{1}' characters...
[ "greedy", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif string s; cin >> s; string ans; int cnt = 0; for (auto c : s) { if (c == '1') ++cnt; else ans += c; } int n = ans.size(); int pos = -1; while (...
1009
C
Annoying Present
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice. Bob has chosen $m$ changes of the following form. For some inte...
Judging by constraints, you can guess that the greedy approach is the right one. Firstly, let's transition from maximizing the arithmetic mean to the sum, it's the same thing generally. Secondly, notice that each $x$ is being added to each element regardless of the chosen position. Finally, take a look at a function $f...
[ "greedy", "math" ]
1,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; typedef long long li; int main() { int n, m; scanf("%d%d", &n, &m); li neg = ((n - 1) / 2) * li((n - 1) / 2 + 1); if (n % 2 == 0) neg += n / 2; li pos = n * li(n - 1) / 2; li ans = 0; forn(i, m){ int x, d;...
1009
D
Relatively Prime Graph
Let's call an undirected graph $G = (V, E)$ relatively prime if and only if for each edge $(v, u) \in E$  $GCD(v, u) = 1$ (the greatest common divisor of $v$ and $u$ is $1$). If there is no edge between some pair of vertices $v$ and $u$ then the value of $GCD(v, u)$ doesn't matter. The vertices are numbered from $1$ to...
Even though $n$ is up to $10^5$, straightforward $O(n^2 \log n)$ solution will work. You iterate for $i$ from $1$ to $n$ in the outer loop, from $i + 1$ to $n$ in the inner loop and check $GCD$ each time. When $m$ edges are found, you break from both loops. Here is why this work fast enough. The total number of pairs $...
[ "brute force", "constructive algorithms", "graphs", "greedy", "math" ]
1,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 100000; pair<int, int> ans[N]; int main() { int n, m; scanf("%d%d", &n, &m); if (m < n - 1) { puts("Impossible"); return 0; } int cur = 0; forn(i, n) for (int j = i + 1; j < n; ++j){ if...
1009
E
Intercity Travelling
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car. The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance betwe...
Let's consider each kilometer of the journey separatedly and calculate the expected value of its difficulty (and then use linearity of expectation to obtain the answer). The difficulty of each kilometer depends on the rest site right before it (or, if there were no rest sites, on the distance from Moscow to this kilome...
[ "combinatorics", "math", "probabilities" ]
2,000
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int main() { int n; scanf("%d", &n); vector<int>...
1009
F
Dominant Indices
You are given a rooted undirected tree consisting of $n$ vertices. Vertex $1$ is the root. Let's denote a depth array of vertex $x$ as an infinite sequence $[d_{x, 0}, d_{x, 1}, d_{x, 2}, \dots]$, where $d_{x, i}$ is the number of vertices $y$ such that both conditions hold: - $x$ is an ancestor of $y$; - the simple ...
In this problem we can use small-to-large merging trick (also known as DSU on tree): when building a depth array for a vertex, we firstly build depth arrays recursively for its children, then pull them upwards and merge them with small-to-large technique. In different blogs on this technique it was mentioned that this ...
[ "data structures", "dsu", "trees" ]
2,300
#define _CRT_SECURE_NO_WARNINGS #include <vector> #include <cstdio> #include <iostream> #include <algorithm> // RJ? No, thanks using namespace std; const int N = 1000043; struct state { vector<int>* a; int cur_max; int sz() { return a->size(); } void add(int i, int val) { (*a)[i] += val; if(make_pair(...
1009
G
Allowed Letters
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup! Actually, Polycarp has already came up with the name but some improvement ...
The idea of solution is the following: we build the answer letter-by-letter; when choosing a character for some position, we try all possible characters and check that we can build the suffix after placing this character. But we need to somehow do this checking fast. As in many previous Educational Rounds, in this roun...
[ "bitmasks", "flows", "graph matchings", "graphs", "greedy" ]
2,400
#include<bits/stdc++.h> using namespace std; #define sz(a) ((int)(a).size()) struct edge { int y; int c; int f; edge() {}; edge(int y, int c, int f) : y(y), c(c), f(f) {}; }; const int N = 100; vector<edge> e; vector<int> g[N]; int edge_num[N][N]; int char_vertex[6]; int mask_vertex[N]; int use...
1010
A
Fly
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $n - 2$ intermediate planets. Formally: we number all the planets from $1$ to $n$. $1$ is Earth, $n$ is Mars. Natasha will make exactly $n$ flights: $1 \to 2 \to \ldots n \to 1$. Flight from $x$ to $y$ consists ...
First, we learn how to determine if a rocket can fly the entire route. Consider an element from an array $a[]$ or $b[]$. We denote it by $t$. If $t=1$ (that is, one ton of fuel can carry only one ton (cargo + fuel)), then fuel can only take it to ourselves, and we need to take a rocket and a useful cargo (the mass of w...
[ "binary search", "math" ]
1,500
#include<bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; if(a[i]<=1) { printf("-1\n"); exit(0); } } int b[n]; for(int i=0;i<n;i++) { cin>>b[i]; i...
1010
B
Rocket
\textbf{This is an interactive problem.} Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the r...
First we learn the sequence $p[]$. For this print the query "1" $n$ times. If the answer is "0" (that is, the distance to Mars is equal to one), then immediately terminate the program. Otherwise, it is clear that the correct answer is "1" (that is, the distance to Mars is greater than one). If $i$-th answer of rocket i...
[ "binary search", "interactive" ]
1,800
#include <bits/stdc++.h> using namespace std; int query(int y) { cout<<y<<"\n"; fflush(stdout); int t; cin>>t; if(t==0||t==-2) exit(0); return t; } int main() { int m,n; cin>>m>>n; int p[n]; for(int i=0;i<n;i++) { int t=query(1); p[i]=t==1; } ...
1010
C
Border
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are...
Note that the condition "the last digit in the record of Natasha's tax amount in the number system with the base $k$ will be $d$" is equivalent to the condition "the remainder of dividing the tax on $k$ will be $d$". Let $g=GCD(a_1,a_2,\ldots,a_n)$. It is stated that the original problem is equivalent to the problem wh...
[ "number theory" ]
1,800
#include<bits/stdc++.h> using namespace std; int gcd(int a,int b) { if(a<b) swap(a,b); return (b==0)?a:gcd(b,a%b); } int main() { int n,k; scanf("%d%d",&n,&k); int g=0; for(int i=0;i<n;i++) { int t; scanf("%d",&t); g=gcd(g,t); } set<int> ans; fo...
1010
D
Mars rover
Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $1$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, w...
Let's count the bit at each vertex. This can be done using depth-first search on this tree. Now for each vertex, let's check: whether the bit on the output of the scheme will change if the bit in the current vertex is changed. If all the vertices on the path from this vertex to the output of the scheme. If at least one...
[ "dfs and similar", "graphs", "implementation", "trees" ]
2,000
#pragma GCC optimize("O3") #include<bits/stdc++.h> using namespace std; struct vertex { char type; vector<int>in; bool val; bool change; }; int n; vector<vertex> g; int dfs1(int v) { switch(g[v].type) { case 'A': g[v].val = dfs1(g[v].in[0]) & dfs1(g[v].in[1]); break; ...
1010
E
Store
Natasha was already going to fly back to Earth when she remembered that she needs to go to the Martian store to buy Martian souvenirs for her friends. It is known, that the Martian year lasts $x_{max}$ months, month lasts $y_{max}$ days, day lasts $z_{max}$ seconds. Natasha also knows that this store works according t...
Consider $2$ options: $m=0$. This means that Natasha does not know about any moment when the store was closed. Let's find the numbers $x_l=min(x_i)$, $x_r=max(x_i)$, $y_l=min(y_i)$, $y_r=max(y_i)$, $z_l=min(z_i)$, $z_r=max(z_i)$, where $(x_i,y_i,z_i)$ are moments when store is open. For each query $(x_t,y_t,z_t)$ answe...
[ "data structures" ]
2,700
#include<bits/stdc++.h> using namespace std; int xmax,ymax,zmax,n,m,k; map< int , map< int , pair< int ,int > > > pmap; vector< pair< int , map< int , pair< int ,int > > > > pvector; vector< pair< vector< pair< int , pair< int , int > > > , vector< pair< int , int > > > > tree; int oxl,oxr,oyl,oyr,ozl,ozr; pair<int...
1010
F
Tree
The Main Martian Tree grows on Mars. It is a binary tree (a rooted tree, with no more than two sons at each vertex) with $n$ vertices, where the root vertex has the number $1$. Its fruits are the Main Martian Fruits. It's summer now, so this tree does not have any fruit yet. Autumn is coming soon, and leaves and branc...
Let $b_v = a_v - \sum{a_{to}}$, (for each $(v, to)$, such that $to$ - is a son of $v$ and tree have both vertices $v$ and $to$), then all that we need is $b_v \geq 0$ and $\sum{b_v} = x$, so for fixed subset of vertices number of ways to arrange weights is just number of ways to partite $x$ into such number of parts. S...
[ "fft", "graphs", "trees" ]
3,400
#include <cmath> #include <iostream> #include <vector> #include <algorithm> #include <string> #include <set> #include <map> #include <list> #include <time.h> #include <math.h> #include <random> #include <deque> #include <queue> #include <cassert> #include <unordered_map> #include <unordered_set> #include <iomanip> #inc...
1011
A
Stages
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages. There are $n$ stages available. The ro...
The problem can be solved by the following greedy algorithm. Sort letters in increasing order. Let's try to add letters in this order. If the current letter is the first in the string, then add it to the answer. Otherwise, check: if the current letter is at least two positions later in the alphabet than the previous le...
[ "greedy", "implementation", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; string s; cin>>s; sort(s.begin(),s.end()); char last='a'-2; int ans=0; int len=0; for(int i=0;i<n;i++) if(s[i]>=last+2) { last=s[i]; ans+=s[i]-'a'+1; l...
1011
B
Planning The Expedition
Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant. The warehouse has $m$ daily food packages. Each package has some food type $a_i$. Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat t...
Let $c_i$ be the number of food packages that equal to $i$. Calculate the array $c$. For any $d$ we can calculate the maximum number of people $k$, who can participate in the expedition for $d$ days. To do this, we'll go over all the elements of the array $c$. Let now be considered $c_i$. If $c_i \ge d$, we can decreas...
[ "binary search", "brute force", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; const int N = 100; int main() { int n, m; cin >> n >> m; vector<int> c(N + 1); for (int i = 0; i < m; i++) { int a; cin >> a; c[a]++; } for (int d = N; d >= 1; d--) { vector<int> cc(c); int k = 0; fo...
1012
A
Photo of The Sky
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes. Strictly speaking, it makes a photo of all points with coordinates $(x, y)$, such that $x_1 \leq x \leq x_2$ and $y_1 \leq y \leq y_2$, where...
At first let's sort array $a$, so we can assume that $a_1 \leq a_2 \leq \dots \leq a_{2 \cdot n}$. Note that area of rectangle with bottom-left corner in $(x_1, y_1)$, and up-right corner in $(x_2, y_2)$ is $(x_2 - x_1) \cdot (y_2 - y_1)$. So the task is to partite array $a$ into $2$ multisets (sets with equal elements...
[ "brute force", "implementation", "math", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int M = 2e5 + 239; const int BIG = 1e9 + 239; int n, a[M]; int main() { cin.sync_with_stdio(0); cin >> n; for (int i = 0; i < (2 * n); i++) cin >> a[i]; sort(a, a + (2 * n)); if (n == 1) { cout << "0"; return 0; } int now ...
1012
B
Chemical table
Innopolis University scientists continue to investigate the periodic table. There are $n·m$ known elements and they form a periodic table: a rectangle with $n$ rows and $m$ columns. Each element can be described by its coordinates $(r, c)$ ($1 ≤ r ≤ n$, $1 ≤ c ≤ m$) in the table. Recently scientists discovered that fo...
One of the way to solve this problem is to interprete the cells in 2d matrix as an edge in the bipartite graph, that is a cell $(i, j)$ is an edge between $i$ of the left part and $j$ of the right part. Note, that each fusion operation (we have edges $(r_{1}, c_{1})$, $(r_{1}, c_{2})$, $(r_{2}, c_{1})$ and get edge $(r...
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "matrices" ]
1,900
null
1012
C
Hills
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of $n$ hills, where $i$-th of them has height $a_{i}$. The Innopolis administration wants to build some houses on the hills. However, for the sake of ci...
The problem's short statement is: "we allowed to decrease any element and should create at least $k$ local maximums, count the minimum number of operations for all $k$". Notice, that any set of positions, where no positions are adjacent could be made to be local maximums - we just need to decrease the neighbouring hill...
[ "dp" ]
1,900
null
1012
D
AB-Strings
There are two strings $s$ and $t$, consisting only of letters a and b. You can make the following operation several times: choose a prefix of $s$, a prefix of $t$ and swap them. Prefixes \underline{can be empty}, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which ...
The solution is basically like following: Note that we can compress equal adjacent letters. Now we can do a dynamic programming with params (first letter of $s$, length of $s$, first letter of $t$, length of $t$). However, the amount of transactions and even states is too large. But we can write a slow, but surely corr...
[ "constructive algorithms", "strings" ]
2,800
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class swap_prefixes_av_n { public static void main(String[] args) { InputStream inputStream = System.in; OutputStrea...
1012
E
Cycle sort
You are given an array of $n$ positive integers $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: select several distinct indices $i_1, i_2, \dots, i_k$ ($1 \le i_j \le n$) and move the number standing at the position $i_1$ to the position $i_2$, the number at the position $i_2$ to th...
Let's solve an array if $a$ is permutation and the sum of cycle sizes is unlimited. It's known that each permutation is composition of some non-intersecting cycles. If permutation is sorted answer is $0$. If permutation is $1$ cycle and some fixed indexes answer is $1$, you should take this cycle to get this answer. If...
[ "dsu", "math" ]
3,100
#include <bits/stdc++.h> using namespace std; const int M = 2e5 + 239; int n, s, a[M], p[M]; pair<int, int> b[M]; int parent[M], r[M]; inline void init() { for (int i = 0; i < n; i++) { parent[i] = i; r[i] = 0; } } inline int find_set(int p) { if (parent[p] == p) return p; return (parent[p] = find_...
1012
F
Passports
Gleb is a famous competitive programming teacher from Innopolis. He is planning a trip to $N$ programming camps in the nearest future. Each camp will be held in a different country. For each of them, Gleb needs to apply for a visa. For each of these trips Gleb knows three integers: the number of the first day of the t...
Let's solve the $P = 1$ case first. We'll use dynamic programming on subsets. Let's try to add visas to subset in order of application. Notice that if we only have one passport, every visa processing segment should lie between some two consecutive trips. For convenience, let's find all these segments beforehand. Define...
[ "dp", "implementation" ]
3,400
null
1013
A
Piles With Stones
There is a beautiful garden of stones in Innopolis. Its most beautiful place is the $n$ piles with stones numbered from $1$ to $n$. EJOI participants have visited this place twice. When they first visited it, the number of stones in piles was $x_1, x_2, \ldots, x_n$, correspondingly. One of the participants wrote do...
It can be simply showed that the answer is <<Yes>> if and only if the sum in the first visit is not less than the sum in the second visit.
[ "math" ]
800
null
1013
B
And
There is an array with $n$ elements $a_{1}, a_{2}, ..., a_{n}$ and the number $x$. In one operation you can select some $i$ ($1 ≤ i ≤ n$) and replace element $a_{i}$ with $a_{i} & x$, where $&$ denotes the bitwise and operation. You want the array to have at least two equal elements after applying some operations (po...
Clearly, if it is possible then there are no more than $2$ operations needed. So we basically need to distinguish $4$ outcomes - $- 1$, $0$, $1$ and $2$. The answer is zero if there are already equal elements in the array. To check if the answer is -1 we can apply the operation to each element of the array. If all elem...
[ "greedy" ]
1,200
null
1015
A
Points in Segments
You are given a set of $n$ segments on the axis $Ox$, each segment has integer endpoints between $1$ and $m$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le m$) — coordinates of the left and of the right e...
In this problem all you need is to check for each point from $1$ to $m$ if it cannot belongs to any segment. It can be done in $O(n \cdot m)$ by two nested loops or in $O(n + m)$ by easy prefix sums calculation. Both solutions are below.
[ "implementation" ]
800
n, m = map(int, input().split()) seg = [list(map(int, input().split())) for i in range(n)] def bad(x): for i in range(n): if (seg[i][0] <= x and x <= seg[i][1]): return False return True ans = list(filter(bad, [i for i in range(1, m + 1)])) print(len(ans)) print(' '.join([str(x) for x in ans]))
1015
B
Obtaining the String
You are given two strings $s$ and $t$. Both strings have length $n$ and consist of lowercase Latin letters. The characters in the strings are numbered from $1$ to $n$. You can successively perform the following move any number of times (possibly, zero): - swap any two adjacent (neighboring) characters of $s$ (i.e. fo...
This problem can be solved using the next greedy approach: let's iterate over all $i$ from $1$ to $n$. If $s_i = t_i$, go further. Otherwise let's find any position $j > i$ such that $s_j = t_i$ and move the character from the position $j$ to the position $i$. If there is no such position in $s$, the answer is "-1". Up...
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s, t; cin >> n >> s >> t; vector<int> ans; for (int i = 0; i < n; ++i) { if (s[i] == t[i]) continue; int pos = -1; for (int j = i + 1; ...
1015
C
Songs Compression
Ivan has $n$ songs on his phone. The size of the $i$-th song is $a_i$ bytes. Ivan also has a flash drive which can hold at most $m$ bytes in total. Initially, his flash drive is empty. Ivan wants to copy all $n$ songs to the flash drive. He can compress the songs. If he compresses the $i$-th song, the size of the $i$-...
If we will no compress songs, the sum of the sizes will be equal $\sum\limits_{i = 1}^{n} a_i$. Let it be $sum$. Now, if we will compress the $j$-th song, how do $sum$ will change? It will decrease by $a_j - b_j$. This suggests that the optimal way to compress the songs is the compress it in non-increasing order of $a_...
[ "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<pair<int, int>> a(n); long long sum = 0; for (int i = 0; i < n; ++i) { cin >> a[i].first >> a[i].second; sum += a[i].firs...
1015
D
Walking Between Houses
There are $n$ houses in a row. They are numbered from $1$ to $n$ in order from left to right. Initially you are in the house $1$. You have to perform $k$ moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the...
The solution for this problem is very simple: at first, if $k > s$ or $k \cdot (n - 1) < s$ the answer is "NO". Otherwise let's do the following thing $k$ times: let $dist$ be $min(n - 1, s - k + 1)$ (we have to greedily decrease the remaining distance but we also should remember about the number of moves which we need...
[ "constructive algorithms", "greedy" ]
1,600
def step(cur, x): if(cur - x > 0): return cur - x else: return cur + x n, k, s = map(int, input().split()) cur = 1 if(k > s or k * (n - 1) < s): print('NO') else: print('YES') while(k > 0): l = min(n - 1, s - (k - 1)) cur = step(cur, l) print(cur, end = ' ...
1015
E1
Stars Drawing (Easy Edition)
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $0$ are not allowed). Let's consid...
Since we are almost unlimited in the number of stars in the answer, the following solution will works. We iterate over all possible stars centers and try to extend rays of the current star as large as possible. It can be done by the simple iterating and checking in $O(n)$. If the size of the current star is non-zero, l...
[ "brute force", "dp", "greedy" ]
1,700
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; const int N = 1001; int n, m; vector<string> f; int d[N][N][4]; int r[N][N], a[N][N], b[N][N]; int getd(int i, int j, int k) { int dxk = dx[k]; ...
1015
E2
Stars Drawing (Hard Edition)
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $0$ are not allowed). Let's consid...
I am sorry that some $O(n^3)$ solutions pass tests in this problem also. I was supposed to increase constraints or decrease time limit. The general idea of this problem is the same as in the previous problem. But now we should do all what we were doing earlier faster. The solution is divided by two parts. The first par...
[ "binary search", "dp", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; int n, m; vector<string> s; vector<string> draw(const vector<pair<pair<int, int>, int>> &r) { vector<string> f(n, string(m, '.')); vector<vector<int>> h(n, vector<int>(m)); vector<vector<int>> v(n, vector<int>(m)); for (auto it : r) { int x = it.first.first; int ...
1015
F
Bracket Substring
You are given a bracket sequence $s$ (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters ...
At first, let's calculate the matrix $len$ of size $(n + 1) \times 2$. Let $len_{i, j}$ will denote the maximum length of the prefix of $s$ which equals to the suffix of the prefix of $s$ of length $i$ with the additional character '(' if $j = 0$ and ')' otherwise. In other words, $len_{i, j}$ is denote which maximum l...
[ "dp", "strings" ]
2,300
#include <bits/stdc++.h> using namespace std; const int N = 203; const int MOD = 1e9 + 7; int n, ssz; string s; int len[N][2]; int dp[N][N][N][2]; int calc(const string &t) { int tsz = t.size(); for (int i = tsz; i > 0; --i) { if (s.substr(0, i) == t.substr(tsz - i, i)) return i; } return 0; } void add(in...
1016
A
Death Note
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $n$ consecutive days. During the $i$-th day you have to write exactly $a_i$ names.". You got scared (of cou...
In this problem all we need is to maintain the variable $res$ which will represent the number of names written on the current page. Initially this number equals zero. The answer for the $i$-th day equals $\lfloor\frac{res + a_i}{m}\rfloor$. This value represents the number of full pages we will write during the $i$-th ...
[ "greedy", "implementation", "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 n, m; cin >> n >> m; int r = 0; for (int i = 0; i < n; ++i) { int x; cin >> x; r += x; cout << r / m << ' '; r %= m; } cout << '\n'; re...
1016
B
Segment Occurrences
You are given two strings $s$ and $t$, both consisting only of lowercase Latin letters. The substring $s[l..r]$ is the string which is obtained by taking characters $s_l, s_{l + 1}, \dots, s_r$ without changing the order. Each of the occurrences of string $a$ in a string $b$ is a position $i$ ($1 \le i \le |b| - |a| ...
Let's take a look at a naive approach: for each query $[l, r]$ you iterate over positions $i \in [l, r - |m| + 1]$ and check if $s[i, i + |m| - 1] = t$. Okay, this is obviously $O(q \cdot n \cdot m)$. Now we notice that there are only $O(n)$ positions for $t$ to start from, we can calculate if there is an occurrence of...
[ "brute force", "implementation" ]
1,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 1000 + 7; int pr[N]; bool ok[N]; int main() { int n, m, q; scanf("%d%d%d", &n, &m, &q); string s, t; static char buf[N]; scanf("%s", buf); s = buf; scanf("%s", buf); t = buf; pr[0] = 0; forn(...
1016
C
Vasya And The Mushrooms
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into $n$ consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spen...
A route visiting each cell exactly once can always be denoted as follows: several (possibly zero) first columns of the glade are visited in a zigzag pattern, then Vasya goes to the right until the end of the glade, makes one step up or down and goes left until he visits all remaining cells: There are $n - 1$ such route...
[ "dp", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = 300 * 1000 + 9; int n; int a[2][N]; long long sum123[2][N]; long long sum321[2][N]; long long sum111[2][N]; int main() { //freopen("input.txt", "r", stdin); scanf("%d", &n); for(int i = 0; i < 2; ++i) for(int j = 0; j < n; ++j) scanf("%d", &a[i][...
1016
D
Vasya And The Matrix
Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed! Vasya knows that the matrix consists of $n$ rows and $m$ columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence $a_{1}, a_{2}, ......
If $a_{1}\oplus a_{2}\oplus\cdot\cdot\cdot\oplus a_{n}\neq b_{1}\oplus b_{2}\oplus\cdot\cdot\cdot\oplus b_{m}$, then there is no suitable matrix. The operation $\mathbb{C}$ means xor. Otherwise, we can always construct a suitable matrix by the following method: the first element of the first line will be equal to $a_{1...
[ "constructive algorithms", "flows", "math" ]
1,800
#include <bits/stdc++.h> #include "testlib.h" using namespace std; const int N = 109; int n, m; int a[N], b[N]; int res[N][N]; int main() { int cur = 0; cin >> n >> m; for(int i = 0; i < n; ++i) cin >> a[i], cur ^= a[i]; for(int i = 0; i < m; ++i) cin >> b[i], cur ^= b[i]; if(cur != 0){ puts("NO"); r...
1016
E
Rest In The Shades
There is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point $(a, s_y)$ to the $(b, s_y)$ $(s_y < 0)$ with speed equal to $1$ unit per second. The trajectory of this light source is a straight segment connecting these two points. There is also...
Let's calculate the answer for a fixed point $P$. If you project with respect of $P$ each segment of the fence to the line containing light source you can see that the answer is the length of intersection of fence projection with segment $(A, B)$ of the trajectory light source. Key idea is the fact that the length of e...
[ "binary search", "geometry" ]
2,400
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<li, li> pt; const int INF = int(1e9); const li INF64 = li(1e18); const double EPS = 1e-9; const int N = 200 * 1000 + 5...
1016
F
Road Projects
There are $n$ cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from $1$ to $n$. The travelling time between some...
The first solution (editorial by PikMike) Firtsly, we can notice that we get the most profit by placing the edge in a same position, no matter the query. Moreover, once you have calculated the minimum difference you can apply to the shortest path $dif_{min}$ by adding edge of the weight $0$, you can answer the queries ...
[ "dfs and similar", "dp", "trees" ]
2,600
#include<bits/stdc++.h> using namespace std; vector<vector<pair<int, int> > > g; vector<long long> d; vector<long long> d1; vector<long long> dn; int n, q; bool read() { scanf("%d %d", &n, &q); g.resize(n); d.resize(n); for(int i = 0; i < n - 1; i++) { int x, y, w; scanf("%d %d %d", &x, &y, &w); --x; -...
1016
G
Appropriate Team
Since next season are coming, you'd like to form a team from two or three participants. There are $n$ candidates, the $i$-th candidate has rank $a_i$. But you have weird requirements for your teammates: if you have rank $v$ and have chosen the $i$-th and $j$-th candidate, then $GCD(v, a_i) = X$ and $LCM(v, a_j) = Y$ mu...
At first, $X \mid Y$ must be met (since $X \mid v$ and $v \mid Y$). Now let $Y = p_1^{py_1} p_2^{py_2} \dots p_z^{py_z}$ and $X = p_1^{px_1} p_2^{px_2} \dots p_z^{px_z}$. From now on let's consider only $p_k$ such that $px_k < py_k$. Now let's look at $a_i$: $X \mid a_i$ must be met. Let $a_i = p_1^{pa_1} p_2^{pa_2} \d...
[ "bitmasks", "math", "number theory" ]
2,700
#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(1e18); const int N = 200 * 1000 + 555; int n; li x, y;...
1017
A
The Rank
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are $n$ students, each of them has a \textbf{unique} id (from $1$ to $n$). Thomas's id...
For each student, add his/her $4$ scores together and count how many students have strictly lower scores than Thomas. Complexity: $O(n)$ or $O(n \log n)$.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int a, b, c, d; cin >> a >> b >> c >> d; int S = a + b + c + d; int Ans = 1; for(int i = 2; i <= n; i++) { cin >> a >> b >> c >> d; if(a + b + c + d > S) { Ans++; } } printf("%d\n",Ans); return 0; }
1017
B
The Bits
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers $a$ and $b$ of length $n$. How many different ways of swapping two digits in $a$ (only in $a$, not $b$) so that bitwise OR of these two numbers will be changed? In other words, let $c$ ...
Let $t_{xy}$ be the number of indexes $i$ such that $a_i=x$ and $b_i=y$. The answer is $t_{00}\cdot t_{10} + t_{00}\cdot t_{11} + t_{01}\cdot t_{10}$.
[ "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; long long ar[4]; char c1[4] = {'0', '0', '1', '1'}; char c2[4] = {'0', '1', '0', '1'}; int main() { int n; cin >> n; string a, b; cin >> a >> b; for(int i = 0; i < n; i++){ for(int j = 0; j < 4; j++){ if(c1[j] == a[i] && c2[j] == b...
1017
C
The Phone Number
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number! The only thing Mrs. Smith remembered was that any permutation of $n$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband. The sequence of $n$ integers is call...
Show an example of $n = 22$: "' 19 20 21 22 15 16 17 18 11 12 13 14 7 8 9 10 3 4 5 6 1 2 "' You can use [Dilworth's theorem](https://en.wikipedia.org/wiki/Dilworth So assume we've already known that $LIS = L$, then we can achieve $LDS = \big\lceil\frac{n}{L}\big\rceil$. So after enumerating all possible $L$ and find th...
[ "constructive algorithms", "greedy" ]
1,600
#include <bits/stdc++.h> using namespace std; #define MAXN 100000 #define rint register int inline int rf(){int r;int s=0,c;for(;!isdigit(c=getchar());s=c);for(r=c^48;isdigit(c=getchar());(r*=10)+=c^48);return s^45?r:-r;} int n, L, A[MAXN+5]; int main() { n = rf(); L = (int)sqrt(n); for(rint i = 1, o = n, j; i <= n...
1017
D
The Wu
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace. This "personal treasure" is a multis...
We can regard a $01-string$ as a binary number. Notice that $n \le 12$, so $\frac{n}{2} \le 6$, so we can do something like meet-in-the-middle, split the numbers into higher $6$ bits and lower $6$ bits: $f[S_1][S_2][j]$ count the number of binary numbers with higher bits equal to $S_1$ and $f((\text{lower bits}) \oplus...
[ "bitmasks", "brute force", "data structures" ]
1,900
#include <bits/stdc++.h> using namespace std; #define MAXN 100000 #define rint register int inline int rf(){int r;int s=0,c;for(;!isdigit(c=getchar());s=c);for(r=c^48;isdigit(c=getchar());(r*=10)+=c^48);return s^45?r:-r;} int Wu[4096], f[64][64][104], g[4096][104], w[16], m, n, q, E, K, B = 6, L = 63, H = 4032; char _...
1017
E
The Supersonic Rocket
After the war, the supersonic rocket became the most common public transportation. Each supersonic rocket consists of \textbf{two} "engines". Each engine is a set of "power sources". The first engine has $n$ power sources, and the second one has $m$ power sources. A power source can be described as a point $(x_i, y_i)...
The statement is complicated, it is actually: Given two sets of points, check whether their convex hulls are isomorphic. The standard solution is: get the convex hulls, make it into a string of traversal: "edge-angle-edge-angle-edge-...". Then double the first string and KMP them. There can be other ways to solve this ...
[ "geometry", "hashing", "strings" ]
2,400
#pragma comment(linker, "/STACK:512000000") #define _CRT_SECURE_NO_WARNINGS //#include "testlib.h" #include <bits/stdc++.h> using namespace std; #define all(a) a.begin(), a.end() using li = long long; using ld = long double; void solve(bool); void precalc(); clock_t start; int main() { #ifdef AIM freopen("/home/ale...
1017
F
The Neutral Zone
\textbf{Notice: unusual memory limit!} After the war, destroyed cities in the neutral zone were restored. And children went back to school. The war changed the world, as well as education. In those hard days, a new math concept was created. As we all know, logarithm function can be described as: $$ \log(p_1^{a_1}p_2...
First forget about the memory limit part. Instead of enumerating all integers and count its $\text{exlog}_f$ value, we enumerate all primes and count its contribution. It is obvious that prime $p$'s contribution is: Brute-force this thing is actually $O(n)$: since there are only $O(\frac{n}{\ln n})$ primes less than or...
[ "brute force", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; typedef unsigned int ll; const ll maxn=4e8; const ll maxp=sqrt(maxn)+10; ll f[4][maxp],g[4][maxp]; ll n,m,A,B,C,D,ans,res,tmp,rt; ll p1(ll x){ ll y=x+1; if (x%2==0) x/=2; else y/=2; return x*y; } ll p2(ll x){ long long y=x+1,z=x*2+1; if (x%2==0) x/=2; els...
1017
G
The Tree
Abendsen assigned a mission to Juliana. In this mission, Juliana has a rooted tree with $n$ vertices. Vertex number $1$ is the root of this tree. Each vertex can be either black or white. At first, all vertices are white. Juliana is asked to process $q$ queries. Each query is one of three types: - If vertex $v$ is whi...
The problem can be solved using HLD or sqrt-decomposition on queries. Here, I will explain to you the second solution. Let $s$ be a constant. Let's split all queries on $\frac{n}{s}$ blocks. Each block will contain $s$ queries. In each block, since we have $s$ queries, we will have at most $s$ different vertices there....
[ "data structures" ]
3,200
#include <bits/stdc++.h> using namespace std; const int MAX = 1e5 + 10; bool black[MAX]; // is it vertex black now vector<int> vec[MAX]; // main edges bool old_black[MAX]; // to remember the tree before block const int MAX_BLOCK_SIZE = 600; int t[MAX], v[MAX]; // queries bool used[MAX]; // is in mini-tree vector<...
1017
H
The Films
In "The Man in the High Castle" world, there are $m$ different film endings. Abendsen owns a storage and a shelf. At first, he has $n$ ordered films on the shelf. In the $i$-th month he will do: - Empty the storage. - Put $k_i \cdot m$ films into the storage, $k_i$ films for each ending. - He will think about a quest...
First, we claim the probability is this: Proof: For each position in $[l,r]$ with ending $i$, you can choose any film with the same ending, there are $(t_i+k)$ of them for the first candidate, and $(t_i+k-1)$ of them for the second candidate, ... So you can satisfy the conditions with $\prod_{i=1}^m (t_i +k)^{\underlin...
[ "brute force" ]
3,300
#pragma comment(linker, "/STACK:512000000") #include <bits/stdc++.h> using namespace std; #define all(a) a.begin(), a.end() typedef long long li; typedef long double ld; void solve(__attribute__((unused)) bool); void precalc(); clock_t start; #define FILENAME "" int main() { #ifdef AIM string s = FILENAME; // ...
1019
A
Elections
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon. Elections are coming. You know the number of voters and the number of parties — $n$ and $m$ respectively. For each ...
Let's iterate over final number of votes for The United Party of Berland. We can see that all opponents should get less votes than our party, and our party should get at least our chosen number of votes. We can sort all voters by their costs, and solve the problem in two passes. First, if we need to get $x$ votes, we s...
[ "brute force", "greedy" ]
1,700
null
1019
B
The hat
\textbf{This is an interactive problem.} Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by $n$ students, where $n$ is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants ...
Let $a(i)$ be a number given to the $i$-th student. Let's introduce function $b(i)=a(i)-a(i+{\frac{n}{2}})$. As $n$ is even, $\frac{n t}{2}$ is integer, and $b(i)$ is defined correctly. Notice two facts: first, $b(i)=-b(i+{\frac{n}{2}})$, and second, $|b(i)-b(i+1)|\in\{-2,0,2\}$. The problem is to find an $i$ such that...
[ "binary search", "interactive" ]
2,000
null
1019
C
Sergey's problem
Sergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree....
Let's build the solution by induction. Suppose we have to solve the problem for $n$ vertices and we can solve this problem for all $k$ ($k < n$). Take an arbitrary vertex $A$. Remove $A$ from the graph, as well as all vertices that $A$ has an outgoing edge to. Resulting graph has less than $n$ vertices, so by induction...
[ "constructive algorithms", "graphs" ]
3,000
null
1019
D
Large Triangle
\begin{quote} There is a strange peculiarity: if you connect the cities of Rostov, Taganrog and Shakhty, peculiarly, you get a triangle \hfill «Unbelievable But True» \end{quote} Students from many different parts of Russia and abroad come to Summer Informatics School. You marked the hometowns of the SIS participants ...
Let's fix one of edge of the triangle. We need to find a third point so the area of triangle is equal to $s$. Notice that area of triangle is proportional to scalar product of the normal vector to the chosen edge and radius-vector of third point. So, if we had all other points sorted by scalar product with normal to th...
[ "binary search", "geometry", "sortings" ]
2,700
null
1019
E
Raining season
By the year 3018, Summer Informatics School has greatly grown. Hotel «Berendeetronik» has been chosen as a location of the school. The camp consists of $n$ houses with $n-1$ pathways between them. It is possible to reach every house from each other using the pathways. Everything had been perfect until the rains starte...
Let's use centroid decomposition on edges of the tree to solve this task. Centroid decomposition on edges is about finding an edge that divides a tree of $n$ vertices into two subtrees, each of which contains no more than $cn$ vertices for some fixed constant $c<1$. It is easy to see that such decomposition has only lo...
[ "data structures", "divide and conquer", "trees" ]
3,200
null
1020
A
New Building for SIS
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room. The bu...
In this problem you need to find a shortest path between some locations in a building. You need to look at some cases to solve this problem. First, if locations are in the same tower ($t_{a} = t_{b}$), you don't need to use a passages between two towers at all, and answer is $f_{a} - f_{b}$. In other case, you have to ...
[ "math" ]
1,000
null
1020
B
Badge
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $n$ students doing yet another trick. Let's assume that all these students are numbered from $1$ to $n$. The teacher came to student $a$ and put a hole in his badge. The st...
In this problem you are given a graph, with one outgoing edge from each vertex. You are asked which vertex is first to be visited twice, if you start in some vertex, and go by outgoing edge from current vertex until you visited some vertex twice. The problem can be solved by straightforward implementation. You choose a...
[ "brute force", "dfs and similar", "graphs" ]
1,000
null
1023
A
Single Wildcard Pattern Matching
You are given two strings $s$ and $t$. The string $s$ consists of lowercase Latin letters and \textbf{at most one} wildcard character '*', the string $t$ consists only of lowercase Latin letters. The length of the string $s$ equals $n$, the length of the string $t$ equals $m$. The wildcard character '*' in the string ...
If there is no wildcard character in the string $s$, the answer is "YES" if and only if strings $s$ and $t$ are equal. In the other case let's do the following thing: while both strings are not empty and their last characters are equal, let's erase them. Then do the same for the first characters, i.e. while both string...
[ "brute force", "implementation", "strings" ]
1,200
null
1023
B
Pair of Toys
Tanechka is shopping in the toy shop. There are exactly $n$ toys in the shop for sale, the cost of the $i$-th toy is $i$ burles. She wants to choose two toys in such a way that their total cost is $k$ burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs $(a, b)$ and $(b, a)$...
The problem is to calculate the number of ways to choose two distinct integers from $1$ to $n$ with sum equals $k$. If $k \le n$ then the answer is $\lfloor\frac{k}{2}\rfloor$ because this is the number of ways to choose two distinct integers from $1$ to $k - 1$ with the sum equals $k$. Otherwise let $mn = n - k$ will ...
[ "math" ]
1,000
null
1023
C
Bracket Subsequence
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r...
Let the array $used$ of $n$ boolean values describe if the corresponding bracket of string $s$ is included in answer or not. The algorithm goes like this: iterate over the string from $1$ to $n$, maintain the stack of positions of currenly unmatched opening brackets $st$. When opening bracket is met at position $i$, pu...
[ "greedy" ]
1,200
null
1023
D
Array Restoration
Initially there was an array $a$ consisting of $n$ integers. Positions in it are numbered from $1$ to $n$. Exactly $q$ queries were performed on the array. During the $i$-th query some segment $(l_i, r_i)$ $(1 \le l_i \le r_i \le n)$ was selected and values of elements on positions from $l_i$ to $r_i$ inclusive got ch...
Let's firstly solve the problem as if there are no zeroes in the given array. Let $l_i$ be the leftmost occurrence of $i$ in the array and $r_i$ be the rightmost occurrence of $i$. The main observation is that you can choose segments $(l_i; r_i)$ for the corresponding queries and this sequence will be correct if and on...
[ "constructive algorithms", "data structures" ]
1,700
null
1023
E
Down or Right
This is an interactive problem. Bob lives in a square grid of size $n \times n$, with rows numbered $1$ through $n$ from top to bottom, and columns numbered $1$ through $n$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $...
Hint: Move from $(1, 1)$ to the middle by asking queries 'query(row, col, n, n)', starting with $row = col = 1$. Similarly, move from $(n, n)$ to the middle by asking queries 'query(1, 1, row, col)'. How to ensure that we will meet in the same cell in the middle? The unusual condition in this problem is $(r_2 - r_1) + ...
[ "constructive algorithms", "interactive", "matrices" ]
2,100
null
1023
F
Mobile Phone Network
You are managing a mobile phone network, and want to offer competitive prices to connect a network. The network has $n$ nodes. Your competitor has already offered some connections between some nodes, with some fixed prices. These connections are bidirectional. There are initially $m$ connections the competitor is off...
Consider the forest of your edges. Let's add edges into this forest greedily from our competitor's set in order of increasing weight until we have a spanning tree. Remember, we don't need to sort, the input is already given in sorted order. Now, consider the competitor's edges one by one by increasing weight. Since we ...
[ "dfs and similar", "dsu", "graphs", "trees" ]
2,600
null
1023
G
Pisces
A group of researchers are studying fish population in a natural system of lakes and rivers. The system contains $n$ lakes connected by $n - 1$ rivers. Each river has integer length (in kilometers) and can be traversed in both directions. It is possible to travel between any pair of lakes by traversing the rivers (that...
First, how do we find the answer in any time complexity? Let us construct a partially ordered set where each element is a single fish in one of the observations. For two elements $x = (v_1, d_1)$ and $y = (v_2, d_2)$ we put $x < y$ if $x$ and $y$ could possibly be two occurences of the same fish one after the other, th...
[ "data structures", "flows", "trees" ]
3,400
null
1025
A
Doggo Recoloring
Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive. The committee rules strictly prohibit even the smallest diversity between dog...
It's easy to see that, if there exists such a color $x$ that at least two puppies share this color, the answer is "Yes" as we can eliminate colors one by one by taking the most numerous color and recoloring all puppies of this color into some other (the number of colors will decrease, but the more-than-one property for...
[ "implementation", "sortings" ]
900
null
1025
B
Weakened Common Divisor
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers. For a given list of pairs of integers $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ their WCD is...
The obvious solution of finding all divisors of all numbers in $\mathcal{O}(n \cdot \sqrt{a_{max}})$ definitely won't pass, so we have to come up with a slight optimization. One may notice that is's sufficient to take a prime WCD (because if some value is an answer, it can be factorized without losing the answer proper...
[ "brute force", "greedy", "number theory" ]
1,600
null
1025
C
Plasticine zebra
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras. Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now w...
Imagine just for a second, that in reality our string is cyclic with a cut at point $0$ and clockwise traversal direction. Now let's apply the cut & reverse operation at point $i$. The key fact here is that nothing happens to the cyclic string - it's just the traversal direction and the cut point (now $i$ instead of $0...
[ "constructive algorithms", "implementation" ]
1,600
null
1025
D
Recovering BST
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees! Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and s...
Let $\mathcal{dp}(l, r, root)$ be a dp determining whether it's possible to assemble a tree rooted at $root$ from the subsegment $[l..r]$. It's easy to see that calculating it requires extracting such $root_{left}$ from $[l..root - 1]$ and $root_{right}$ from $[root + 1..right]$ that: $\mathcal{gcd}(a_{root}, a_{root_{...
[ "brute force", "dp", "math", "number theory", "trees" ]
2,100
null
1025
E
Colored Cubes
Vasya passes all exams! Despite expectations, Vasya is not tired, moreover, he is ready for new challenges. However, he does not want to work too hard on difficult problems. Vasya remembered that he has a not-so-hard puzzle: $m$ colored cubes are placed on a chessboard of size $n \times n$. The fact is that $m \leq n$...
We're gonna show how to turn an arbitrary arrangement of cubes into the arrangement where $i$-th cube is located at $(i, i)$ (we call such an arrangement basic) in no more than $2*n^{2}$ operations. For simplicity, we imply that we have exactly $n$ cubes where $n$ is even. Say we have some arrangement where $i$-th cube...
[ "constructive algorithms", "implementation", "matrices" ]
2,700
null
1025
F
Disjoint Triangles
A point belongs to a triangle if it lies inside the triangle or on one of its sides. Two triangles are disjoint if there is no point on the plane that belongs to both triangles. You are given $n$ points on the plane. No two points coincide and no three points are collinear. Find the number of different ways to choose...
The most challenging part of the problem is to think of the way how to count each pair of triangles exactly once. It turns out, that this can be done in a nice and geometrical way. Each pair of triangles has exactly two inner tangents between them. Moreover, exactly one of them (if we direct tangent from point of the f...
[ "geometry" ]
2,700
null
1025
G
Company Acquisitions
There are $n$ startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup. The following steps happe...
You can solve this most likely by brute forcing small cases and looking for a pattern. Here's a proof of the pattern. Let's define a potential of a startup with $k$ followers to be equal to $2^k - 1$. For example, an active startup with zero followers has potential zero. Now, in one day, if we choose a startup with $p$...
[ "constructive algorithms", "math" ]
3,200
null
1027
A
Palindromic Twist
You are given a string $s$ consisting of $n$ lowercase Latin letters. $n$ is even. For each position $i$ ($1 \le i \le n$) in string $s$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Lett...
If some string can't be transformed to palindrom then it has some pair of positions $(i, n - i + 1)$ with different letters on them (as no such pair affects any other pair). Thus you need to check each pair for $i$ from $1$ to $\frac n 2$ and verify that the distance between the corresponding letters is either $0$ or $...
[ "implementation", "strings" ]
1,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int T; cin >> T; int n; string s; forn(_, T){ cin >> n >> s; bool ok = true; forn(i, n){ int k = abs(s[i] - s[n - i - 1]); if (k > 2...
1027
B
Numbers on the Chessboard
You are given a chessboard of size $n \times n$. It is filled with numbers from $1$ to $n^2$ in the following way: the first $\lceil \frac{n^2}{2} \rceil$ numbers from $1$ to $\lceil \frac{n^2}{2} \rceil$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $n^2 - \lceil...
Let's see the following fact: if we will decrease $\lceil \frac{n^2}{2} \rceil$ from all numbers written in cells with an odd sum of coordinates and write out the numbers obtained on the board from left to right from top to bottom, the sequence will looks like $1, 1, 2, 2, \dots, \lceil \frac{n^2}{2} \rceil, \lceil \fr...
[ "implementation", "math" ]
1,200
import sys lst = sys.stdin.readlines() n, q = map(int, lst[0].split()) for i in range(q): x, y = map(int, lst[i + 1].split()) cnt = (x - 1) * n + y ans = (cnt + 1) // 2 if ((x + y) % 2 == 1): ans += (n * n + 1) // 2 sys.stdout.write(str(ans) + '\n')
1027
C
Minimum Value Rectangle
You have $n$ sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose s...
Let's work with the formula a bit: $\frac{P^2}{s}$ $=$ $\frac{4(x + y)^2}{xy}$ $=$ $4(2 + \frac x y + \frac y x)$ $=$ $8 + 4(\frac x y + \frac y x)$ Let $a = \frac x y$, then the formula becomes $8 + 4(a + \frac 1 a)$. Considering $x \ge y$, $a = \frac x y \ge 1$, thus $(a + \frac 1 a)$ is strictly increasing and has i...
[ "greedy" ]
1,600
#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 = 1000 * 1000 + 13; int n, m; int a[N]; int b[N]; int main() { int T; scanf("%d", &T); forn(_, T){ scanf("%d", &n); forn(i, n) scanf("%d", &a[...
1027
D
Mouse Hunt
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $80\%$ of applicants are girls and majority of them are going to live in the university dormitory for the next $4$ (hopefully) years. The dormitory consists of $n$ rooms and a single mouse! Girls decided to set mou...
Mouse jumps on a cycle at some point, no matter the starting vertex, thus it's always the most profitable to set traps on cycles. The structure of the graph implies that there are no intersecting cycles. Moreover, mouse will visit each vertex of the cycle, so it's enough to set exactly one trap on each cycle. The only ...
[ "dfs and similar", "graphs" ]
1,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define sqr(a) ((a) * (a)) #define x first #define y second typedef...
1027
E
Inverse Coloring
You are given a square board, consisting of $n$ rows and $n$ columns. Each tile in it should be colored either white or black. Let's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well. Let's call some...
You can notice that every coloring can be encoded by the two binary strings of length $n$. You firstly generate one string to put as a first row and then use the second string to mark if you put the first string as it is or inverting each color. That way, you can also guess that the area of maximum rectangle of a singl...
[ "combinatorics", "dp", "math" ]
2,100
def norm(x): return (x % 998244353 + 998244353) % 998244353 n, k = map(int, input().split()) dp1 = [0] dp2 = [0] for i in range(n): l = [1] cur = 0 for j in range(n + 1): cur += l[j] if(j > i): cur -= l[j - i - 1] cur = norm(cur) l.append(cur) dp1.appen...
1027
F
Session in BSU
Polycarp studies in Berland State University. Soon he will have to take his exam. He has to pass exactly $n$ exams. For the each exam $i$ there are known two days: $a_i$ — day of the first opportunity to pass the exam, $b_i$ — day of the second opportunity to pass the exam ($a_i < b_i$). Polycarp can pass at most one ...
This problem has many approaches (as Hall's theorem, Kuhn algorithm (???) and so on), I will explain one (or two) of them. Let's find the answer using binary search. It is obvious that if we can pass all the exams in $k$ days we can also pass them in $k+1$ days. For the fixed last day $k$ let's do the following thing: ...
[ "binary search", "dfs and similar", "dsu", "graph matchings", "graphs" ]
2,400
#include <bits/stdc++.h> using namespace std; mt19937 rnd(time(NULL)); const int N = 2 * 1000 * 1000 + 11; const int INF = 1e9; int n; int a[N][2]; vector<int> nums; int m; vector<int> g[N]; int mt[N]; int used[N]; int T = 1; bool try_kuhn(int v) { if (used[v] == T) return false; used[v] = T; ...
1027
G
X-mouse in the Campus
The campus has $m$ rooms numbered from $0$ to $m - 1$. Also the $x$-mouse lives in the campus. The $x$-mouse is not just a mouse: each second $x$-mouse moves from room $i$ to the room $i \cdot x \mod{m}$ (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of ...
Some notes: At first, there is $x^{-1} \mod{m}$ since $(x, m) = 1$ (lets define $\text{GCD}(a,b)$ as $(a, b)$). That means that for each $v = 0..m-1$ there is exactly one $u$ that $u \cdot x = v$. So if we look at this problem as the graph then it consists of cycles (consider loops as cycles of length one). So we need ...
[ "bitmasks", "math", "number theory" ]
2,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()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<li, li> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; li...
1028
A
Find Square
Consider a table of size $n \times m$, initially fully white. Rows are numbered $1$ through $n$ from top to bottom, columns $1$ through $m$ from left to right. Some square inside the table with \textbf{odd} side length was painted black. Find the center of this square.
There are lots of possible solutions. For example, run through rows from the top until you find one with at least one 'B'. Do the same for the bottom. Average of the two row numbers is the number of the middle row. Now find the first and last 'B' in that row, their average value is the number of the middle column. Alte...
[ "implementation" ]
800
static class SquareInside { final int inf = (int) 1e9; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(), m = in.readInt(); char[][] s = new char[n][]; for (int i = 0; i < n; i++) { s[i] = in.readWord().toCharAr...
1028
B
Unnatural Conditions
Let $s(x)$ be sum of digits in decimal representation of positive integer $x$. Given two integers $n$ and $m$, find some positive integers $a$ and $b$ such that - $s(a) \ge n$, - $s(b) \ge n$, - $s(a + b) \le m$.
First note, that if some output is correct for test with $n = 1129$ and $m = 1$, then it's correct for any valid test. After noticing this, we don't need to read input and output one answer for any test. One of many possible answers is $a = 99..9900..001$ (200 nines, 199 zeroes, 1 one) $b = 99..99$ (200 nines) $a + b =...
[ "constructive algorithms", "math" ]
1,200
int len = 400; cout << string(len, '5') << "\n"; cout << (string(len - 1, '4') + '5') << "\n";
1028
C
Rectangles
You are given $n$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $(n-1)$ of the given $n$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary. Find any point with integer coordinates that b...
Note that intersection of any number of rectangles is a rectangle too (possibly, empty). Calculate $pref(i)$ - intersection of rectangles with numbers $1, 2, \ldots, i$, and $suf(i)$ - intersection of rectangles with numbers $i, i + 1, \ldots, n$. If $i$ is the index of the rectangle not included in the answer, then in...
[ "geometry", "implementation", "sortings" ]
1,600
static class Rectangle { public Point topLeft, bottomRight; public Rectangle(Point topLeft, Point bottomRight) { this.topLeft = topLeft; this.bottomRight = bottomRight; } public Rectangle intersect(Rectangle other) { if (other == null) { ...
1028
D
Order book
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price. At every moment of time, every SELL offer has higher price than every BUY offer. \textb...
Keep track of a lower bound for the best sell $s_{best}$ and an upper bound for the best buy $b_{best}$ in the order book. If we have ACCEPT $p$ with $p > s_{best}$ or $p < b_{best}$, it's a contradiction and the answer does not exist. If either $b_{best} = p$ or $s_{best} = p$, then the answer stay the same, and if $b...
[ "combinatorics", "data structures", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; const int mod = 1e9 + 7; signed main() { #ifdef LOCAL assert(freopen("test.in", "r", stdin)); #endif int n; cin >> n; map<int, int> a{{INT_MIN, 1}, {INT_MAX, 0}}; set<int*> non0{&a.begin()->second}; for (int i = 0;...
1028
E
Restore Array
While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers $a_1, a_2, \ldots, a_n$. Since the talk was long and not promising, Kostya created a new cyclic array $b_1, b_2, \ldots, b_{n}$ so that $b_i = (a_i \mod a_{i + 1})$, where we take $a_{n+1} = a_1$. Here $mod$ i...
Let's consider a special case at first: all numbers are equal to $M$. Then the answer exists only if $M = 0$ (prove it as an exercise). Now let $M$ be the maximum value in array $b$. Then there exists an index $i$ such that $b_i = M$ and $b_{i-1} < M$ (we assume $b_0 = b_n$). We assume it's $b_n$, otherwise we just shi...
[ "constructive algorithms" ]
2,400
void solve(__attribute__((unused)) bool read) { int n; cin >> n; vector<int> b(n, 0); for (int i = 0; i < n; ++i) { cin >> b[i]; } int mx = *max_element(all(b)); int start_pos = -1; for (int i = 0; i < n; ++i) { if (b[i] == mx && b[(i - 1 + n) % n] != mx) { start_pos = i; break; ...
1028
F
Make Symmetrical
Consider a set of points $A$, initially it is empty. There are three types of queries: - Insert a point $(x_i, y_i)$ to $A$. It is guaranteed that this point does not belong to $A$ at this moment. - Remove a point $(x_i, y_i)$ from $A$. It is guaranteed that this point belongs to $A$ at this moment. - Given a point $(...
The key idea is the fact that the number of points $(x, y)$, where $x, y \ge 0$, with fixed $x^2 + y^2 = C$ is not large. Actually it is equal to the number of divisors of $C$ after removing all prime divisors of $4k+3$ form (because if $C$ has such prime divisor, then both $x, y$ are divisible by it). For the problem ...
[ "brute force" ]
2,900
struct Point { int x, y; Point() {} Point(int x, int y) : x(x), y(y) {} void scan() { cin >> x >> y; } auto key() const { return make_pair(x, y); } bool operator < (const Point& ot) const { return key() < ot.key(); } bool operator == (const Point& ot) const { return key() == ot.key()...
1028
G
Guess the number
This problem is interactive. You should guess hidden number $x$ which is between $1$ and $M = 10004205361450474$, inclusive. You could use up to $5$ queries. In each query, you can output an increasing sequence of $k \leq x$ integers, each between $1$ and $M$, inclusive, and you will obtain one of the following as a...
Although it looks strange, the bound on the number from the problem statement is actually tight for $5$ queries of length up to $10^4$. Let's find out how to obtain this number. Let $dp(l, q)$ is the maximum $(r - l)$ such that we can guess the number which is known to be in $[l; r)$ using $q$ queries. The number $l$ i...
[ "dp", "interactive" ]
3,000
private static final int MAX_WIDTH = 10000; private static final int QUERIES = 5; public static final long INF = 20000000000000000L; long[][] memo = new long[QUERIES + 1][MAX_WIDTH + 1]; long dp(int guesses, long l) { if (guesses == 0) { return l; } if (l > MAX_WIDTH...
1028
H
Make Square
We call an array $b_1, b_2, \ldots, b_m$ good, if there exist two indices $i < j$ such that $b_i \cdot b_j$ is a perfect square. Given an array $b_1, b_2, \ldots, b_m$, in one action you can perform one of the following: - multiply any element $b_i$ by any prime $p$; - divide any element $b_i$ by prime $p$, if $b_i$ ...
Firstly, we can divide out all squares from the $a_i$, since they make no difference. Thus, each $a_i$ is then a product of unique primes. If we want to transform $a_i$ and $a_j$ so that their product becomes a square, the cost is the number of primes that appear in one but not in another. Each $a_i$ can have at most $...
[ "math" ]
2,900
const int C = 5032107 + 1; int lp[C]; int fred[C]; int num_primes[C]; const int MAX_DIVISORS = 7; const int MAX_ANS = 2 * MAX_DIVISORS; int max_left[MAX_DIVISORS + 1][C]; int max_border[MAX_ANS + 1]; vector<int> cur_primes; vector<int> divs; void get_divisors(int n) { divs = {1}; while (n > 1) { in...
1029
A
Many Equal Substrings
You are given a string $t$ consisting of $n$ lowercase Latin letters and an integer number $k$. Let's define a substring of some string $s$ with indices from $l$ to $r$ as $s[l \dots r]$. Your task is to construct such string $s$ of minimum possible length that there are exactly $k$ positions $i$ such that $s[i \dots...
Let's carry the current answer as $ans$, the last position we're checked as $pos$ and the number of occurrences as $cnt$. Initially, the answer is $t$, $cnt$ is $1$ and $pos$ is $1$ (0-indexed). We don't need to check the position $0$ because there is the beginning of the occurrence of $t$ at this position. Also $cnt$ ...
[ "implementation", "strings" ]
1,300
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; string t; cin >> n >> k >> t; vector<int> p(n); for (int i = 1; i < sz(t); ++i) { int j = p[i - 1]; while (j >...
1029
B
Creating the Contest
You are given a problemset consisting of $n$ problems. The difficulty of the $i$-th problem is $a_i$. It is guaranteed that all difficulties are distinct and are given in the increasing order. You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have...
The answer is always a segment of the initial array. The authors solution uses two pointers technique: let's iterate over all left bounds of the correct contests and try to search maximum by inclusion correct contest. Let's iterate over all $i$ from $0$ to $n-1$ and let the current left bound be $i$. Let $j$ be the max...
[ "dp", "greedy", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif int n; scanf("%d", &n); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); int ans = 0; for (int i = 0; i < n; ++i) { int j = i; while (j + 1 < n && a[j + 1] <= a[j] * 2) ...
1029
C
Maximal Intersection
You are given $n$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. The intersection of a sequence of segments is such a maximal set of points (not necesserily havi...
Intersection of some segments $[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$ is $[\max \limits_{i = 1}^n l_i; \min \limits_{i = 1}^n r_i]$. If this segment has its left bound greater than its right bound then the intersection is empty. Removing some segment $i$ makes the original sequence equal to $[l_1, r_1], \dots, [l_{...
[ "greedy", "math", "sortings" ]
1,600
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 300 * 1000 + 13; const int INF = int(1e9); int n; int prl[N], prr[N], sul[N], sur[N]; int l[N], r[N]; int main() { scanf("%d", &n); forn(i, n) scanf("%d%d", &l[i], &r[i]); prl[0] = sul[n] = 0; pr...
1029
D
Concatenated Multiples
You are given an array $a$, consisting of $n$ positive integers. Let's call a concatenation of numbers $x$ and $y$ the number that is obtained by writing down numbers $x$ and $y$ one right after another without changing the order. For example, a concatenation of numbers $12$ and $3456$ is a number $123456$. Count the...
Let's rewrite concatenation in a more convenient form. $conc(a_i, a_j) = a_i \cdot 10^{len_j} + a_j$, where $len_j$ is the number of digits in $a_j$. Then this number is divisible by $k$ if and only if the sum of ($a_{j}~ mod~ k$) and ($(a_i \cdot 10^{len_j})~ mod~ k$) is either $0$ or $k$. Let's calculate $10$ arrays ...
[ "implementation", "math" ]
1,900
#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; const int LOGN = 11; int n, k; int a[N]; int len[N]; vector<int> rems[LOGN]; int pw[LOGN]; int main() { scanf("%d%d", &n, &k); forn(i, n) scanf("%d", &a[i]); ...
1029
E
Tree with Small Distances
You are given an undirected tree consisting of $n$ vertices. An undirected tree is a connected undirected graph with $n - 1$ edges. Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex $1$ to any other vertex is at most $2$. Note that you are not allowed to...
The first idea is the following: it is always profitable to add the edges from the vertex $1$ to any other vertex. The proof is the following: if we will add two edges $(1, u)$ and $(u, v)$ then the distance to the vertex $u$ will be $1$, the distance to the vertex $v$ will be $2$. But we can add edges $(1, u)$ and $(1...
[ "dp", "graphs", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 11; int p[N]; int d[N]; vector<int> g[N]; void dfs(int v, int pr = -1, int dst = 0) { d[v] = dst; p[v] = pr; for (auto to : g[v]) { if (to != pr) { dfs(to, v, dst + 1); } } } int main() { #ifdef _DEBUG freopen("input.txt", "r", st...
1029
F
Multicolored Markers
There is an infinite board of square tiles. Initially all tiles are white. Vova has a red marker and a blue marker. Red marker can color $a$ tiles. Blue marker can color $b$ tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should ...
$a+b$ should be area of the outer rectangle. It means that its sides are divisors of $a+b$. The same holds for the inner rectangle. Let's assume that red color forms a rectangle, we'll try it and then swap $a$ with $b$ and solve the same problem again. Write down all the divisors of $a$ up to $\sqrt a$, these are the p...
[ "binary search", "brute force", "math", "number theory" ]
2,000
#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 = 1000 * 1000; int lens[N]; int k; li solve(li a, li b){ k = 0; for (li i = 1; i * i <= b; ++i) if (b % i == 0) lens[k++] = i; li ans = 2 * (a + b) + 2; li x = a + b; int...
1030
A
In Search of an Easy Problem
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked $n$ people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these $n$ people has answered tha...
Codebait. Comforting problem. Find $\max\limits_{i=1..n}{(\text{answer}_i)}$, if it's equal to $1$ then answer is HARD, otherwise - EASY.
[ "implementation" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int curMax = 0; for(int i = 0; i < n; i++) { int curAns; cin >> curAns; curMax = max(curMax, curAns); } puts(curMax > 0 ? "HARD" : "EASY"); return 0; }