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 ⌀ |
|---|---|---|---|---|---|---|---|
1151 | B | Dima and a Bad XOR | Student Dima from Kremland has a matrix $a$ of size $n \times m$ filled with non-negative integers.
He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!
Formally, he wants to choose an integers sequence $c... | Let's take the first number in each array. Then, if we have current XOR strictly greater than zero we can output an answer. And if there is some array, such that it contains at least two distinct numbers, you can change the first number in this array to number, that differs from it, and get XOR $0 \oplus x > 0$. Else, ... | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp"
] | 1,600 | null |
1151 | C | Problem for Nazar | Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.
Consider two infinite sets of numbers. The first set consists of odd positive numbers ($1, 3, 5, 7, \ldots$), and the second set consists of ev... | At first let's simplify the problem. Let's denote as $f(x)$ function that returns sum of the elements that are on positions from $1$ to $x$ inclusive. How to implement function $f(x)$? To find the answer we can find the sum of even and sum of odd numbers and add them. Let's find how many there are even and odd numbers.... | [
"constructive algorithms",
"math"
] | 1,800 | null |
1151 | D | Stas and the Queue at the Buffet | During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $n$ high school students numbered from $1$ to $n$. Initially, each student $i$ is on position $i$. Each student $i$ is characterized by two numbers — $a_i$ and $b_i$. Dissatisfaction of the person $i$ equals th... | Firstly, open the brackets: $a_i \cdot (j-1) + b_i \cdot (n-j)$ = $(a_i - b_i) \cdot j + b_i \cdot n - a_i$. As you can see $b_i \cdot n - a_i$ is not depending on $j$, so we can sum these values up and consider them as constants. Now we must minimize the sum of $(a_i - b_i) \cdot j$. Let's denote two integers arrays e... | [
"greedy",
"math",
"sortings"
] | 1,600 | null |
1151 | E | Number of Components | The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of $n$ vertices. Each vertex $i$ has its own value $a_i$. All vertices are connected in series by edges. Formally, for every $1 \leq i < n$ there is an edge between the vertices of $i$ and $i+1$.
Denote the function $f(l, r)$, w... | First of all assign $0$ to $a_0$. How to find the value of $f(l, r)$ in $\mathcal{O}(n)$? For each $i$ from $0$ to $n$ set $b_i$ to $1$ if $l \leq a_i \leq r$, otherwise set it to $0$. Now we can see that the value of $f(l, r)$ is equal to the number of adjacent pairs $(0, 1)$ in array $b$. So now we can find the answe... | [
"combinatorics",
"data structures",
"dp",
"math"
] | 2,100 | null |
1151 | F | Sonya and Informatics | A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.
Given an array $a$ of length $n$, \textbf{consisting only of the numbers $0$ and $1$}, and the number $k$. \textbf{Exactly $k$ times} the following ha... | How to solve this problem in $\mathcal{O}(n\cdot k)$? Let's find the answer using dynamic programming. Denote $cur$ as the number of zeroes in array $a$, and $dp_{i,j}$ as the number of rearrangements of array $a$ after $i$ operations and $j$ is equal to the number of zeroes on prefix of length $cur$. Denote $x$ as the... | [
"combinatorics",
"dp",
"matrices",
"probabilities"
] | 2,300 | null |
1152 | A | Neko Finds Grapes | On a random day, Neko found $n$ treasure chests and $m$ keys. The $i$-th chest has an integer $a_i$ written on it and the $j$-th key has an integer $b_j$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The $j$-th key can be used ... | The most important observation is that: Key with odd id can only be used to unlock chest with even id Key with even id can only be used to unlock chest with odd id Let: $c_0, c_1$ be the number of chests with even and odd id, respectively $k_0, k_1$ be the number of keys with even and odd id, respectively With $c_0$ ev... | [
"greedy",
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char* argv[])
{
int n, m;
scanf("%d%d", &n, &m);
vector<int> a(n), b(m);
for(int i = 0; i < n; ++i)
scanf("%d", &a[i]);
for(int i = 0; i < m; ++i)
scanf("%d", &b[i]);
int c0 = 0, c1 = 0;
for(int i = 0; i < n... |
1152 | B | Neko Performs Cat Furrier Transform | Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.
Assume that we have a cat with a number $x$. A perfect longcat is a cat with a number equal $2^m - 1$ for some no... | There are various greedy solutions possible. I'll only cover one of them. We'll perform a loop as follows: If $x \le 1$, stop the process (since it's already correct). If $x = 2^m$ ($m \ge 1$), perform operation A with $2^m-1$. Obviously, the resulting $x$ will be $2^{m+1}-1$, which satisfies the criteria, so we stop t... | [
"bitmasks",
"constructive algorithms",
"dfs and similar",
"math"
] | 1,300 | #pragma comment(linker, "/stack:247474112")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int x; vector<vector<int>> vis(2, vector<int>(1048576, INT_MAX));
vector<vector<pair<int, int>>> Last(2, vector<pair<int, int>>(1048576, {-1LL, -1LL}));
int isCompletion(int z) {... |
1152 | C | Neko does Maths | Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers $a$ and $b$. His goal is to find a non-negative integer $k$ such that the least common multiple of $a+k$ and $b+k$ is the smallest possible. If there are multiple optimal integers $k... | The $lcm(a + k, b + k)$ is equal to $\frac{(a + k) \cdot (b + k)}{\gcd(a + k, b + k)}$. In fact, there are not much possible values for the denominator of this fraction. Without losing generality, let's assume $a \le b$. Applying one step of Euclid's algorithm we can see, that $\gcd(a + k, b + k) = \gcd(b - a, a + k)$.... | [
"brute force",
"math",
"number theory"
] | 1,800 | #pragma comment(linker, "/stack:247474112")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int a, b;
void Input() {
cin >> a >> b;
}
void Solve() {
if (a == b) {cout << "0\n"; return;}
vector<int> Divisors;
for (int i=1; i<=sqrt(max(a,b) - min(a,b)); i++) {
if... |
1152 | D | Neko and Aki's Prank | Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...
It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of w... | Note, that many subtrees of the trie are equal. Basically, if we consider two vertices on the same depth and having the same balance from root to them (that is, the number of opening brackets minus the number of closing brackets), than their subtrees will be entirely same. For example, the subtrees after following $(((... | [
"dp",
"greedy",
"trees"
] | 2,100 | // Dmitry _kun_ Sayutin (2019)
#include <bits/stdc++.h>
using std::cin;
using std::cout;
using std::cerr;
using std::vector;
using std::map;
using std::array;
using std::set;
using std::string;
using std::pair;
using std::make_pair;
using std::tuple;
using std::make_tuple;
using std::get;
using std::min;
using st... |
1152 | E | Neko and Flashback | A permutation of length $k$ is a sequence of $k$ integers from $1$ to $k$ containing each integer exactly once. For example, the sequence $[3, 1, 2]$ is a permutation of length $3$.
When Neko was five, he thought of an array $a$ of $n$ positive integers and a permutation $p$ of length $n - 1$. Then, he performed the f... | Obviously, if $b'_i > c'_i$ for some $i$, then the answer is "-1". From the statement, we have $b_i = \min(a_i, a_{i+1})$ and $c_i = \max(a_i, a_{i+1})$. For this to happen, either one of the following must happen: $a_i = b_i$ and $a_{i+1} = c_i$ $a_i = c_i$ and $a_{i+1} = b_i$ In order word, one of the two following p... | [
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
class Indexer {
private:
map<int, int> id;
vector<int> num;
public:
int getId(int x) {
if (!id.count(x)) {
id[x] = num.size();
num.push_back(x);
}
return id[x];
}
int getNum... |
1152 | F1 | Neko Rules the Catniverse (Small Version) | This problem is same as the next one, but has smaller constraints.
Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.
There are $n$ planets in the Catniverse, numbered from $1$ to $n$. At the beginning of the game, Aki chooses the planet ... | As the problem stated, from planet $x$ we can go backwards any to any planet $y$ such that $y < x$. This implies an idea of considering the planets from $n$ to $1$, then deciding whether to insert each planet to the current path or not. Formally, if our current path is $v_1, v_2, \dots, v_p$ and we are going to insert ... | [
"bitmasks",
"dp",
"matrices"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
void add(int &a, long long b) {
a = (a + b) % MOD;
}
int main() {
int n, k, m;
scanf("%d%d%d", &n, &k, &m);
vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(k+1, vector<int>(1<<m, 0)));
dp[0][0][0] = 1;
... |
1152 | F2 | Neko Rules the Catniverse (Large Version) | This problem is same as the previous one, but has larger constraints.
Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.
There are $n$ planets in the Catniverse, numbered from $1$ to $n$. At the beginning of the game, Aki chooses the plan... | The core idea is similar to F1, however there is one crucial observation. We can see that all DP transitions are just linear transformations, thus we can construct a transition matrix of size $k \cdot 2^m$, then use fast matrix exponentiation as a replacement of the original DP transitions. Total complexity: $\mathcal{... | [
"bitmasks",
"dp",
"matrices"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
void add(int &a, long long b) {
a = (a + b) % MOD;
}
struct Matrix {
vector<vector<int>> a;
int n, m;
Matrix(int n, int m): n(n), m(m) {
a.assign(n, vector<int>(m, 0));
}
friend Matrix operator * (Matri... |
1153 | A | Serval and Bus | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, th... | Find the first bus Serval can see in each route and find the earliest one. For each route, finding the first bus Serval sees can work in $O(1)$. Or mark all the time no more than $\max(s_i,t+\max(d_i))$ which bus would come or there will be no bus, then search the nearest one. | [
"brute force",
"math"
] | 1,000 | null |
1153 | B | Serval and Toy Bricks | Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.
He has a special interest to create difficult problems for others to solve. This time, with many $1 \times 1 \times 1$ toy bricks, he builds up a 3-dimensional object. We c... | Fill in all the bricks, and then remove all bricks you must remove (which in some view, there is empty). This can be solved in $O(nm)$. | [
"constructive algorithms",
"greedy"
] | 1,200 | null |
1153 | C | Serval and Parenthesis Sequence | Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.
In his favorite math class, the teacher taught him the following interesting definitions.
A parenthesis sequence is a string, containing only characters "(" and ")".
A correct parenthesis sequence is a parenthesis sequence ... | First let ( be $+1$, ) be $-1$ and ? be a missing place, so we will replace all the missing places in the new $+1$,$-1$ sequence by $+1$ and $-1$. Obviously, for each prefix of a correct parenthesis sequence, the sum of the new $+1$,$-1$ sequence is not less than $0$. And for the correct parenthesis sequence itself, th... | [
"greedy",
"strings"
] | 1,700 | null |
1153 | D | Serval and Rooted Tree | Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before.
As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex cal... | If we want to check whether $x$ is the answer (I didn't say I want to do binary search), then we can set all the numbers no less than $x$ as $1$, and the numbers less than $x$ as $0$. Then we can use $dp_i$ to represent that the maximum number on node $i$ is the $dp_i$-th smallest number of leaves within subtree of $i$... | [
"binary search",
"dfs and similar",
"dp",
"greedy",
"trees"
] | 1,900 | #include <cstdio>
using namespace std;
const int N=1000005;
int n,p;
int h[N],nx[N];
int t[N],sz[N];
void getsize(int u)
{
if (!h[u])
sz[u]++;
for (int i=h[u];i;i=nx[i])
{
getsize(i);
sz[u]+=sz[i];
}
}
int getans(int u)
{
if (!h[u])
return 1;
int ret=0,tmp;
if (t[u])
{
for (int i=h[u];i;i=nx[i])
{
... |
1153 | E | Serval and Snake | This is an interactive problem.
Now Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a $n \times n$ grid. The snake has a head and a tail in different cells, and its body is a... | If the answer to a rectangle is odd, there must be exactly one head or tail in that rectangle. Otherwise, there must be even number ($0$ or $2$) of head and tail in the given rectangle. We make queries for each of the columns except the last one, then we can know for each column whether there are odd number of head and... | [
"binary search",
"brute force",
"interactive"
] | 2,200 | null |
1153 | F | Serval and Bonus Problem | Getting closer and closer to a mathematician, Serval becomes a university student on math major in Japari University. On the Calculus class, his teacher taught him how to calculate the expected length of a random subsegment of a given segment. Then he left a bonus problem as homework, with the award of a garage kit fro... | Without loss of generality, assume that $l=1$. For a segment covering, the total length of the legal intervals is the probability that we choose another point $P$ on this segment randomly such that it is in the legal intervals. Since all $2n+1$ points ($P$ and the endpoints of each segment) are chosen randomly and inde... | [
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,600 | #include <cstdio>
using namespace std;
const int mod=998244353;
const int N=4005;
const int K=2005;
int n,k,l;
int fac,ans;
int f[N][K][2];
int fpw(int b,int e=mod-2)
{
if (!e)
return 1;
int ret=fpw(b,e>>1);
ret=1ll*ret*ret%mod;
if (e&1)
ret=1ll*ret*b%mod;
return ret;
}
int main()
{
scanf("%d%d%d",&n,&k,&l);
... |
1154 | A | Restoring Three Numbers | Polycarp has guessed three positive integers $a$, $b$ and $c$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $a+b$, $a+c$, $b+c$ and $... | Let $x_1 = a + b$, $x_2 = a + c$, $x_3 = b = c$ and $x_4 = a + b + c$. Then we can construct the following answer: $c = x_4 - x_1$, $b = x_4 - x_2$ and $a = x_4 - x_3$. Because all numbers in the answer are positive, we can assume that the maximum element of $x$ is $a + b + c$. So let's sort the input array $x$ consist... | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
vector<int> a(4);
for (int i = 0; i < 4; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
cout << a[3] - a[0] << " " << a[3] - a[1] << " " << a[3] - a[2] <<... |
1154 | B | Make Them Equal | You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ integers.
You can choose any non-negative integer $D$ (i.e. $D \ge 0$), and for each $a_i$ you can:
- add $D$ (only once), i. e. perform $a_i := a_i + D$, or
- subtract $D$ (only once), i. e. perform $a_i := a_i - D$, or
- leave the value of $a_i$ unch... | Let's leave only unique values of the given array in the array $b$ (i. e. construct an array $b$ that is actually array $a$ without duplicate element) and sort it in ascending order. Then let's consider the following cases: If the length of $b$ is greater than $3$ then the answer is -1; if the length of $b$ is $3$ then... | [
"math"
] | 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;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
a.resize(unique(a.begin(), a.end()) - a.begin()... |
1154 | C | Gourmet Cat | Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:
- on Mondays, Thursdays and Sundays he eats fish food;
- on Tuesdays and Saturdays he eats rabbit stew;
- on other days of week he eats chicken stake.
Polycarp plans to go on a trip and already packed his ba... | Let the number of rations of fish food be $a_1$, the number of rations of rabbit stew be $a_2$ and the number of rations of chicken stakes be $a_3$ (so we have an array $a$ consisting of $3$ elements). Let $full$ be the maximum number of full weeks cat can eat if the starting day of the trip can be any day of the week.... | [
"implementation",
"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
vector<int> a(3);
cin >> a[0] >> a[1] >> a[2];
vector<int> idx({0, 1, 2, 0, 2, 1, 0});
int full = min({a[0] / 3, a[1] / 2, a[2] / 2});
a[0] -= full * 3;
... |
1154 | D | Walking Robot | There is a robot staying at $X=0$ on the $Ox$ axis. He has to walk to $X=n$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.
The $i$-th segment of the path (from $X=i-1$ to $X=i$) can be exposed to sunlight or not. The array $s$ denotes which s... | Let's simulate the process of walking and maintain the current charges of the battery and the accumulator, carefully choosing which to use each time we want to pass a segment. Obviously, if at the beginning of some segment our battery is exhausted (its current charge is $0$), we must use the accumulator to continue, an... | [
"greedy"
] | 1,500 | #include<bits/stdc++.h>
using namespace std;
int a, b, maxa;
void use_battery(int s)
{
if(s == 1) a = min(a + 1, maxa);
--b;
}
void use_accum()
{
--a;
}
int main()
{
int ans = 0;
int n;
cin >> n >> b >> a;
maxa = a;
vector<int> s(n);
for(int i = 0; i < n; i++) cin >> s[i];
for(int i = 0; i < n; i++)
{
... |
1154 | E | Two Teams | There are $n$ students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.
The $i$-th student has integer programming skill $a_i$. All programming skills are \textbf{distinct} and between $1$ and $n$, inclusive.
Firstly, the first... | Let's maintain two data structures: a queue with positions of students in order of decreasing their programming skill and a set (std::set, note that we need exactly ordered set) with positions of students not taken in any team. To construct the first data structure we need to sort pairs $(a_i, i)$ in decreasing order o... | [
"data structures",
"implementation",
"sortings"
] | 1,800 | #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>> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i].first;
a[i].second = i;
}
sort(a.rbegin(), a.rend());
... |
1154 | F | Shovels Shop | There are $n$ shovels in the nearby shop. The $i$-th shovel costs $a_i$ bourles.
Misha has to buy \textbf{exactly} $k$ shovels. Each shovel can be bought \textbf{no more than once}.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this ... | First of all, since we are going to buy exactly $k$ shovels, we may discard $n - k$ most expensive shovels from the input and set $n = k$ (and solve the problem which requires us to buy all the shovels). Also, let's add an offer which allows us to buy $1$ shovel and get $0$ cheapest of them for free, to simulate that w... | [
"dp",
"greedy",
"sortings"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m, k;
cin >> n >> m >> k;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
a.resiz... |
1154 | G | Minimum Possible LCM | You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$.
Your problem is to find such pair of indices $i, j$ ($1 \le i < j \le n$) that $lcm(a_i, a_j)$ is minimum possible.
$lcm(x, y)$ is the least common multiple of $x$ and $y$ (minimum positive number such that both $x$ and $y$ are divisors of ... | I've heard about some very easy solutions with time complexity $O(a \log a)$, where $a$ is the maximum value of $a_i$, but I will describe my solution with time complexity $O(nd)$, where $d$ is the maximum number of divisors of $a_i$. A very good upper-bound approximation of the number of divisors of $x$ is $\sqrt[3]{x... | [
"brute force",
"greedy",
"math",
"number theory"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int N = 10 * 1000 * 1000 + 11;
int n;
vector<int> a;
int mind[N];
pair<int, int> mins[N];
vector<pair<int, int>> divs;
void build_sieve() {
vector<int> pr;
mind[0] = mind[1] = 1;
for (int i = 2; i < N; ++i) {
if (mind[i] == 0) {
pr.p... |
1155 | A | Reverse a Substring | You are given a string $s$ consisting of $n$ lowercase Latin letters.
Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $3$ and ends in position $6$), but "aa" or "d" aren't substrings of this string. So the substring of the string $... | If the answer is "YES" then we always can reverse a substring of length $2$. So we need to check only pairs of adjacent characters in $s$. If there is no such pair of characters $s_i > s_{i + 1}$ for all $i$ from $1$ to $n-1$ then the answer is "NO". Why is it so? Consider the substring $s[l; r] = s_l s_{l+1} \dots s_r... | [
"implementation",
"sortings",
"strings"
] | 1,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;
string s;
cin >> n >> s;
for (int i = 1; i < int(s.size()); ++i) {
if (s[i] < s[i - 1]) {
cout << "YES" << endl;
cout << i << " " << i + 1 <<... |
1155 | B | Game with Telephone Numbers | A telephone number is a sequence of \textbf{exactly} $11$ digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string $s$ of length $n$ ($n$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player \textbf{must} choose a ... | Let's understand how players should act. Vasya needs to delete the first digit that is not equal to $8$, because the first digit of telephone number should be $8$, and the first digit not equal to $8$ is preventing it. Petya needs to delete the first digit equal to $8$, for the same reasons. So, all that we need to do ... | [
"games",
"greedy",
"implementation"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
int n;
string s;
int main(){
cin >> n >> s;
int cnt1 = (n - 11) / 2;
int cnt2 = cnt1;
string res = "";
for(int i = 0; i < n; ++i){
if(s[i] == '8'){
if(cnt1 > 0) --cnt1;
else res += s[i];
}
else{
... |
1155 | C | Alarm Clocks Everywhere | Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $i$-th of them will start during the $x_i$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $x_1, x_2, \dots, x_n$, so he will... | It is obvious that we can always take $x_1$ as $y$. But we don't know which value of $p$ we can take. Let $d_i$ be $x_{i + 1} - x_i$ for all $i$ from $1$ to $n-1$. The value of $p$ should be divisor of each value of $d_i$. The maximum possible divisor of each $d_i$ is $g = gcd(d_1, d_2, \dots, d_{n-1})$ (greatest commo... | [
"math",
"number theory"
] | 1,300 | #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<long long> x(n), p(m);
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
for (int i = 0; i < m; ++i) {
cin >> p[i];
}
lon... |
1155 | D | Beautiful Array | You are given an array $a$ consisting of $n$ integers. Beauty of array is the maximum sum of some \textbf{consecutive subarray} of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.
You may choose \textbf{at most one c... | The first intuitive guess one's probably made is multiplying the segment of maximum sum for positive $x$. That thing is correct. Unfortunately, there is no similar strategy for non-positive $x$, simple greedy won't work there. Thus, dynamic programming is our new friend. Let's introduce the following state: $dp[pos][st... | [
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
typedef long long li;
const int N = 300 * 1000 + 13;
const li INF64 = 1e18;
int n, x;
int a[N];
li dp[N][3][3];
int main() {
scanf("%d%d", &n, &x);
forn(i, n) scanf("%d", &a[i]);
forn(i, n + 1) forn(j, 3) forn(... |
1155 | E | Guess the Root | Jury picked a polynomial $f(x) = a_0 + a_1 \cdot x + a_2 \cdot x^2 + \dots + a_k \cdot x^k$. $k \le 10$ and all $a_i$ are integer numbers and $0 \le a_i < 10^6 + 3$. It's guaranteed that there is at least one $i$ such that $a_i > 0$.
Now jury wants you to find such an integer $x_0$ that $f(x_0) \equiv 0 \mod (10^6 + 3... | Since $10^6 + 3$ is a prime and degree $k$ of the polynomial is small enough, we can get this polynomial in our hands asking $k + 1$ queries in different points. Knowing values $f(x_i)$ for $x_1, x_2, \dots, x_{k + 1}$, we can interpolate $f$ by various ways. For example, we can construct a system of linear equations t... | [
"brute force",
"interactive",
"math"
] | 2,200 | #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<int, int> pt;
const int MOD = 1000 * 1000 + 3;
int norm(int a) {
while(a >= MOD) a -= MO... |
1155 | F | Delivery Oligopoly | The whole delivery market of Berland is controlled by two rival companies: BerEx and BerPS. They both provide fast and reliable delivery services across all the cities of Berland.
The map of Berland can be represented as an \textbf{undirected} graph. The cities are vertices and the roads are edges between them. Each p... | Let's use dynamic programming to solve this problem. We will start with a single biconnected component consisting of vertex $0$, and connect other vertices to it. So, the state of our dynamic programming will be a $mask$ of vertices that are in the same biconnected component with $0$. How can we extend a biconnected co... | [
"brute force",
"dp",
"graphs"
] | 2,800 | #include<bits/stdc++.h>
using namespace std;
const int N = 14;
const int INF = int(1e9);
int dp[1 << N];
int par[1 << N];
int last[1 << N];
pair<int, int> last_pair[1 << N];
int dp2[N][N][1 << N];
int lastv[N][N][1 << N];
vector<int> bits[1 << N];
int n;
int m;
vector<int> g[N];
int main()
{
cin >> n >> m;
for(in... |
1156 | A | Inscribed Figures | The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.
Future students will be asked just a single question. They are given a sequen... | Firstly, let's find out when the answer is infinite. Obviously, any point of intersection is produced by at least a pair of consecutive figures. Take a look at every possible pair and you'll see that only square inscribed in triangle and vice verse produce infinite number of points in intersection. The other cases are ... | [
"geometry"
] | 1,400 | #include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
using namespace std;
int main(){
int n;
scanf("%d", &n);
int sum = 0;
int lst = 1;
vector<int> figs;
forn(i, n){
int x;
scanf("%d", &x);
if (lst != 1 && x != 1){
puts("Infinite");
return 0;
}
if (x != 1){
figs.push_... |
1156 | B | Ugly Pairs | You are given a string, consisting of lowercase Latin letters.
A pair of \textbf{neighbouring} letters in a string is considered ugly if these letters are also \textbf{neighbouring} in a alphabet. For example, string "abaca" contains ugly pairs at positions $(1, 2)$ — "ab" and $(2, 3)$ — "ba". Letters 'a' and 'z' aren... | To be honest, the solution to this problem is easier to code than to prove. Let's follow the next strategy. Write down all the letters of the string which have odd positions in alphabet ("aceg$\dots$") and even positions in alphabet ("bdfi$\dots$"). Sort both of these lists in non-decreasing order. The answer is either... | [
"dfs and similar",
"greedy",
"implementation",
"sortings",
"strings"
] | 1,800 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
bool check(string s){
bool ok = true;
forn(i, int(s.size()) - 1)
ok &= (abs(s[i] - s[i + 1]) != 1);
return ok;
}
int main() {
int T;
scanf("%d", &T);
static char buf[120];
forn(_, T){
scanf("%s", buf);
str... |
1156 | C | Match Points | You are given a set of points $x_1$, $x_2$, ..., $x_n$ on the number line.
Two points $i$ and $j$ can be matched with each other if the following conditions hold:
- neither $i$ nor $j$ is matched with any other point;
- $|x_i - x_j| \ge z$.
What is the maximum number of pairs of points you can match with each other? | Let's denote the points that have greater coordinates in their matched pairs as $R$-points, and the points that have smaller coordinates as $L$-points. Suppose we have an $R$-point that has smaller coordinate than some $L$-point. Then we can "swap" them, and the answer won't become worse. Also, if some $R$-point has sm... | [
"binary search",
"greedy",
"sortings",
"ternary search",
"two pointers"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
const int N = 200043;
int n, z;
int a[N];
int main()
{
scanf("%d", &n);
scanf("%d", &z);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
sort(a, a + n);
int l = 0;
int r = n / 2 + 1;
while(r - l > 1)
{
int m = (l + r) / 2;
bool good = true;
for(int i = 0; ... |
1156 | D | 0-1-Tree | You are given a tree (an undirected connected acyclic graph) consisting of $n$ vertices and $n - 1$ edges. A number is written on each edge, each number is either $0$ (let's call such edges $0$-edges) or $1$ (those are $1$-edges).
Let's call an ordered pair of vertices $(x, y)$ ($x \ne y$) \textbf{valid} if, while tra... | Let's divide all valid pairs into three categories: the ones containing only $0$-edges on the path, the ones containing only $1$-edges, and the ones containing both types of edges. To calculate the number of pairs containing only $0$-edges, we may build a forest on the vertices of the original graph and $0$-edges, and ... | [
"dfs and similar",
"divide and conquer",
"dp",
"dsu",
"trees"
] | 2,200 | #include<bits/stdc++.h>
using namespace std;
const int N = 200043;
int p[2][N];
int siz[2][N];
int get(int x, int c)
{
if(p[c][x] == x)
return x;
return p[c][x] = get(p[c][x], c);
}
void merge(int x, int y, int c)
{
x = get(x, c);
y = get(y, c);
if(siz[c][x] < siz[c][y])
swap(x, y);
p[c][y] = x;
siz[c][... |
1156 | E | Special Segments of Permutation | You are given a permutation $p$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).
Let's call some subsegment $p[l, r]$ of this permutation special if $p_l + p_r = \max \limits_{i = l}^{r} p_i$. Please calculate the number of special subsegments. | Let's fix the maximum element on segment and iterate on either the elements to the left of it or to the right of it, and if the current maximum is $x$, and the element we found is $y$, check whether the element $x - y$ can form a special subsegment with $y$ (that is, $x$ is the maximum value on the segment between $y$ ... | [
"data structures",
"divide and conquer",
"dsu",
"two pointers"
] | 2,200 | #include<bits/stdc++.h>
using namespace std;
const int N = 200043;
int lf[N];
int rg[N];
int n;
int ans = 0;
int p[N];
int q[N];
void update(int l, int r, int l2, int r2, int sum)
{
for(int i = l; i <= r; i++)
{
int o = sum - p[i];
if(o >= 1 && o <= n && l2 <= q[o] && q[o] <= r2)
ans++;
}
}
int main()
{
... |
1156 | F | Card Bag | You have a bag which contains $n$ cards. There is a number written on each card; the number on $i$-th card is $a_i$.
You are playing the following game. During each turn, you choose and remove a random card from the bag (all cards that are still left inside the bag are chosen equiprobably). Nothing else happens during... | Let's solve the problem by dynamic programming. Let $dp_{i, j}$ be the probability of winning if the last taken card has number $i$ on it and the number of taken cards is $j$. We win immediately next turn if we take card with number $i$ on it. The probability of this is $\frac{cnt_{i} - 1}{n - j}$, where $cnt_i$ is num... | [
"dp",
"math",
"probabilities"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 5005;
void upd(int &a, int b){
a += b;
a %= MOD;
}
int mul(int a, int b){
return (a * 1LL * b) % MOD;
}
int bp(int a, int n){
int res = 1;
for(; n > 0; n >>= 1){
if(n & 1) res = mul(res, a);
a ... |
1156 | G | Optimizer | Let's analyze a program written on some strange programming language. The variables in this language have names consisting of $1$ to $4$ characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit.
There are four ty... | Let's restate the problem in a more convinient way. Initially we are given some directed acyclic graph. Let there be nodes of two kinds: For a direct set operation. These will have a single outgoing edge to another node. For a binary operation. These will have two outgoing edges to other nodes. However, it's important ... | [
"graphs",
"greedy",
"hashing",
"implementation"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef pair<ll,ll> pll;
typedef vector<bool> vb;
const ll oo = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-9;
#define sz(c) ll((c).size())
#define all(c) begin(c), end(c)
#define FOR(i,a,b) for (ll i = (a... |
1157 | A | Reachable Numbers | Let's denote a function $f(x)$ in such a way: we add $1$ to $x$, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,
- $f(599) = 6$: $599 + 1 = 600 \rightarrow 60 \rightarrow 6$;
- $f(7) = 8$: $7 + 1 = 8$;
- $f(9) = 1$: $9 + 1 = 10 \rightarrow 1$;
- $f(10099) = 10... | The key fact in this problem is that the answer is not very large (in fact, it's not greater than $91$). Why is it so? Every $10$ times we apply function $f$ to our current number, it gets divided by $10$ (at least), and the number of such divisions is bounded as $O(\log n)$. So we can just do the following: store all ... | [
"implementation"
] | 1,100 | def f(x):
x += 1
while(x % 10 == 0):
x //= 10
return x
a = set()
n = int(input())
while(not(n in a)):
a.add(n)
n = f(n)
print(len(a)) |
1157 | B | Long Number | You are given a long decimal number $a$ consisting of $n$ digits from $1$ to $9$. You also have a function $f$ that maps every digit from $1$ to $9$ to some (possibly the same) digit from $1$ to $9$.
You can perform the following operation \textbf{no more than once}: choose a non-empty \textbf{contiguous subsegment} o... | Let's find the first digit in $a$ that becomes strictly greater if we replace it (obviously, if there is no such digit, then the best solution is to leave $a$ unchanged). In the optimal solution we will replace this digit and maybe some digits after this. Why is it so? It is impossible to make any of the previous digit... | [
"greedy"
] | 1,300 | #include<bits/stdc++.h>
using namespace std;
int f[10];
string s;
int main()
{
int n;
cin >> n;
cin >> s;
for(int i = 1; i <= 9; i++)
cin >> f[i];
vector<int> diff;
for(int i = 0; i < n; i++)
diff.push_back(f[s[i] - '0'] - (s[i] - '0'));
for(int i = 0; i < n; i++)
if(diff[i] > 0)
{
while(i < n && d... |
1157 | C1 | Increasing Subsequence (easy version) | \textbf{The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2)}.
You are given a sequence $a$ consisting of $n$ integers. \textbf{All these integers are distinct, each value from $1$ to $n$ appears in the sequence exactly once.... | In this problem the following greedy solution works: let's maintain the last element of the increasing sequence we got and on each turn choose the minimum element greater than this last element among the leftmost and the rightmost. Such turns will maximize the answer. You can find details of implementation in the autho... | [
"greedy"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
string res;
int l = 0, r = n - 1;
int lst = 0;
while (l <= r) {
vec... |
1157 | C2 | Increasing Subsequence (hard version) | \textbf{The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2)}.
You are given a sequence $a$ consisting of $n$ integers.
You are making a sequence of moves. During each move you must take either the leftmost element of the se... | The solution of the previous problem works for this problem also. Almost works. What if the leftmost element is equal the rightmost element? Which one should we choose? Let's analyze it. If we take the leftmost element then we will nevertake any other element from the right, and vice versa. So we can't meet this case m... | [
"greedy"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
string res;
int l = 0, r = n - 1;
int lst = 0;
while (l <= r) {
vec... |
1157 | D | N Problems During K Days | Polycarp has to solve exactly $n$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $k$ days. It means that Polycarp has exactly $k$ days for training!
Polycarp doesn't want to procrastinate, so he wants ... | I suppose there are some solutions without cases handling, but I'll describe my own, it handling approximately $5$ cases. Firstly, let $nn = n - \frac{k(k+1)}{2}$. If $nn < 0$ then the answer is "NO" already. Otherwise let's construct the array $a$, where all $a_i$ are $\lfloor\frac{nn}{k}\rfloor$ (except rightmost $nn... | [
"constructive algorithms",
"greedy",
"math"
] | 1,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, k;
cin >> n >> k;
if (n < k * 1ll * (k + 1) / 2) {
cout << "NO" << endl;
return 0;
}
int nn = n - k * (k + 1) / 2;
vector<int> a(k);
for (int ... |
1157 | E | Minimum Array | You are given two arrays $a$ and $b$, both of length $n$. All elements of both arrays are from $0$ to $n-1$.
You can reorder elements of the array $b$ (if you want, you may leave the order of elements as it is). After that, let array $c$ be the array of length $n$, the $i$-th element of this array is $c_i = (a_i + b_i... | Let's maintain all elements of the array $b$ in a set that allows multiple copies of equal elements (std::multiset for C++). Then let's iterate from left to right over the array $a$ and try to minimize the current element in array $c$. This order will minimize the resulting array by lexicographical comparing definition... | [
"binary search",
"data structures",
"greedy"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
multiset<int> b;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
b.i... |
1157 | F | Maximum Balanced Circle | There are $n$ people in a row. The height of the $i$-th person is $a_i$. You can choose \textbf{any} subset of these people and try to arrange them into a \textbf{balanced circle}.
A \textbf{balanced circle} is such an order of people that the difference between heights of any adjacent people is no more than $1$. For ... | Let's realize what we need to construct the minimum balanced circle with heights from $l$ to $r$. We can represent it as $l, l + 1, \dots, r - 1, r, r - 1, \dots, l + 1$. As we can see, we need one occurrence of $l$ and $r$ and two occurrences of all other heights from $l + 1$ to $r - 1$. How can we find the maximum ba... | [
"constructive algorithms",
"dp",
"greedy",
"two pointers"
] | 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;
cin >> n;
vector<int> a(n);
vector<int> cnt(200 * 1000 + 1);
for (int i = 0; i < n; ++i) {
cin >> a[i];
++cnt[a[i]];
}
sort(a.begin(), a.end()... |
1157 | G | Inverse of Rows and Columns | You are given a binary matrix $a$ of size $n \times m$. A binary matrix is a matrix where each element is either $0$ or $1$.
You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing a... | The first observation: if we have an answer where the first row is inverted, we can inverse all rows and columns, then the matrix will remain the same, and the first row is not inverted in the new answer. So we can suppose that the first row is never inverted. Note that this will be true only for slow solution. The sec... | [
"brute force",
"constructive algorithms"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
int n, m;
void invRow(vector<vector<int>> &a, int idx) {
for (int pos = 0; pos < m; ++pos) {
a[idx][pos] ^= 1;
}
}
void invCol(vector<vector<int>> &a, int idx) {
for (int pos = 0; pos < n; ++pos) {
a[pos][idx] ^= 1;
}
}
int main() {
#ifdef _DEBUG
freopen("inpu... |
1158 | A | The Party and Sweets | $n$ boys and $m$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $1$ to $n$ and all girls are numbered with integers from $1$ to $m$. For all $1 \leq i \leq n$ the minimal number of sweets, which $i$-th boy presented to some g... | Let's note, that for all $1 \leq i \leq n, 1 \leq j \leq m$ is is true, that $b_i \leq g_j$, because $b_i \leq a_{{i}{j}} \leq g_j$. So $max(b_1, b_2, \ldots, b_n) \leq min(g_1, g_2, \ldots, g_m)$. If it is not true, the answer is $-1$. Let's prove, that if $max(b_1, b_2, \ldots, b_n) \leq min(g_1, g_2, \ldots, g_m)$ t... | [
"binary search",
"constructive algorithms",
"greedy",
"implementation",
"math",
"sortings",
"two pointers"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n, m;
ll r_max, c_min, x, r_max2, r_sum, c_sum, ans;
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m;
r_max = 0;
r_max2 = 0;
r_sum = 0;
for (int i = 0; i < n; i++)
{
cin >> x;... |
1158 | B | The minimal unique substring | Let $s$ be some string consisting of symbols "0" or "1". Let's call a string $t$ a substring of string $s$, if there exists such number $1 \leq l \leq |s| - |t| + 1$ that $t = s_l s_{l+1} \ldots s_{l + |t| - 1}$. Let's call a substring $t$ of string $s$ unique, if there exist only one such $l$.
For example, let $s = $... | Let's define the value $a = \frac {n-k} 2$. We know, that $(k \bmod 2) = (n \bmod 2)$ so $a$ is integer number. Let's construct this string $s$: $a$ symbols "0", $1$ symbol "1", $a$ symbols "0", $1$ symbol "1", $\ldots$ Let's prove, that this string satisfy the conditions. Let's note, that it's period is equal to $(a+1... | [
"constructive algorithms",
"math",
"strings"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, k, a;
cin >> n >> k;
a = (n - k) / 2;
for (int i = 0; i < n; i++)
cout << ((i + 1) % (a + 1) == 0);
return 0;
} |
1158 | C | Permutation recovery | Vasya has written some permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, so for all $1 \leq i \leq n$ it is true that $1 \leq p_i \leq n$ and all $p_1, p_2, \ldots, p_n$ are different. After that he wrote $n$ numbers $next_1, next_2, \ldots, next_n$. The number $next_i$ is equal to the minimal index $i <... | Note that if there are indices $i < j$ for which the values $next_i$ and $next_j$ are defined and $i < j < next_i < next_j$ are satisfied, then there is no answer. Suppose that this is not true and there exists permutation $p_1, p_2, \ldots, p_n$. Note that since $j < next_i$ we get that $p_i > p_j$ (otherwise $next_i$... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"math",
"sortings"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int M = 5e5 + 239;
int n, a[M], p[M], timer;
vector<int> v[M];
vector<int> q;
void dfs(int t)
{
p[t] = timer--;
for (int i : v[t])
dfs(i);
}
void solve()
{
cin >> n;
for (int i = 0; i <= n; i++) v[i].clear();
for (int i = 0; i < n... |
1158 | D | Winding polygonal line | Vasya has $n$ different points $A_1, A_2, \ldots A_n$ on the plane. No three of them lie on the same line He wants to place them in some order $A_{p_1}, A_{p_2}, \ldots, A_{p_n}$, where $p_1, p_2, \ldots, p_n$ — some permutation of integers from $1$ to $n$.
After doing so, he will draw oriented polygonal line on these... | Let's describe the algorithm, which is always finding the answer: Let's find any point $A_i$, lying at the convex hull of points $A_1, A_2, \ldots, A_n$. We don't need to construct the convex hull for this, we can simply take the point with the minimal $y$. This point will be the first in the permutation. Let's constru... | [
"constructive algorithms",
"geometry",
"greedy",
"math"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M = 2e3 + 239;
int n, x[M], y[M];
bool used[M];
string s;
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> x[i] >> y[i];
cin >> s;
s += 'L';
int id = -1;
for (int i = 0; i < n; i++)
i... |
1158 | E | Strange device | \textbf{It is an interactive problem.}
Vasya enjoys solving quizzes. He found a strange device and wants to know how it works.
This device encrypted with the tree (connected undirected graph without cycles) with $n$ vertices, numbered with integers from $1$ to $n$. To solve this quiz you should guess this tree.
Fort... | The solution will consist of two parts. 1 part Let's divide all points into sets with equal distance to the vertex $1$. To do this, we will do the following algorithm. How to understand what set of points lies at a distance $\lfloor \frac{n}{2} \rfloor$ from the top of $1$? Let's fill $d$ with zeros and make $d_1 = \lf... | [
"binary search",
"interactive",
"math",
"trees"
] | 3,400 | #include <bits/stdc++.h>
using namespace std;
const int M = 1010;
vector<bool> ask(vector<int> d)
{
cout << "? ";
for (int i : d)
cout << i << " ";
cout << endl;
string s;
cin >> s;
vector<bool> ans((int)d.size());
for (int i = 0; i < (int)d.size(); i++)
ans[i] = (bool)... |
1158 | F | Density of subarrays | Let $c$ be some positive integer. Let's call an array $a_1, a_2, \ldots, a_n$ of positive integers $c$-array, if for all $i$ condition $1 \leq a_i \leq c$ is satisfied. Let's call $c$-array $b_1, b_2, \ldots, b_k$ a \textbf{subarray} of $c$-array $a_1, a_2, \ldots, a_n$, if there exists such set of $k$ indices $1 \leq ... | We have some $c$-array $a$. Let's find the criterion, that any $c$-array of length $p$ is its subsequence. To check that $c$-array $b$ is a subsequence of $a$, we should iterate all elements of $b$ and take the most left occurrence of this symbol in $a$, starting from the current moment. Because any $c$-array should be... | [
"dp",
"math"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const int M = 3010;
const int MOD = 998244353;
const ll MOD2 = (ll)MOD * (ll)MOD;
const int MG = 10;
const int MS = (1 << MG);
inline int power(int a, int k)
{
if (k == 0) return 1;
int t = power(a, k >> 1);
... |
1159 | A | A pile of stones | Vasya has a pile, that consists of some number of stones. $n$ times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given $n$ operations which Vasya has made. Find the minimal possible number of stones that c... | Let's consider an array $a$, there $a_i=1$, if $s_i=$"+" and $a_i=-1$, if $s_i=$"-". Let's notice, that the answer $\geq a_{k+1} + \ldots + a_n$ for all $k$. It is true, because after making the first $k$ operations the number of stones will be $\geq 0$, so at the end the number of stones will be $\geq a_{k+1} + \ldots... | [
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int n;
string s;
int main()
{
cin >> n >> s;
int m = 0;
int a = 0;
for (int i = n - 1; i >= 0; i--)
{
if (s[i] == '+')
m++;
else
m--;
a = max(a, m);
}
cout << a;
return 0;
} |
1159 | B | Expansion coefficient of the array | Let's call an array of non-negative integers $a_1, a_2, \ldots, a_n$ a $k$-extension for some non-negative integer $k$ if for all possible pairs of indices $1 \leq i, j \leq n$ the inequality $k \cdot |i - j| \leq min(a_i, a_j)$ is satisfied. The expansion coefficient of the array $a$ is the maximal integer $k$ such th... | Let our array be a $k$-extension. All inequalities $k \cdot |i - j| \leq min(a_i, a_j)$ for $i \neq j$ can be changed to $k \leq \frac{min(a_i, a_j)}{|i - j|}$. For all $i = j$ inequalities are always true, because all numbers are non-negative. So, the maximum possible value of $k$ is equal to the minimum of $\frac{min... | [
"implementation",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int M = 1e5;
int n, a, m = 1e9;
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a;
m = min(m, a / max(i, n - 1 - i));
}
cout << m;
return 0;
} |
1162 | A | Zoning Restrictions Again | You are planning to build housing on a street. There are $n$ spots available on the street on which you can build a house. The spots are labeled from $1$ to $n$ from left to right. In each spot, you can build a house with an integer height between $0$ and $h$.
In each spot, if a house has height $a$, you will gain $a^... | This problem can be done by processing the restrictions one by one. Let's keep an array $a$ of length $n$, where the $i$-th value in this array represents the maximum possible height for house $i$. Initially, we have processed no restrictions, so we fill $a_i = h$ for all $i$. For a restriction $k$, we can loop through... | [
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
int32_t main()
{
int n, h, m;
cin>>n>>h>>m;
int a[n+1];
for(int i=1;i<=n;i++)
a[i]=h;
for(int i=0;i<m;i++)
{
int l, r, x;
... |
1162 | B | Double Matrix | You are given \textbf{two} $n \times m$ matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bot... | There are too many possibilities to try a brute force, and a dp solution also might be too slow (e.g. some bitmask dp). There is a solution that uses 2sat but that is a bit hard to code so I won't go into details in this tutorial. Let's instead look at a greedy solution. First, let's swap $a_{i,j}$ with $b_{i,j}$ if $a... | [
"brute force",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
int32_t main()
{
int n,m;
cin>>n>>m;
int a[n][m], b[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>a[i][j];
... |
1163 | A | Eating Soup | The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party...
What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now $n$ cats are at the party, sitting in a circle and eating soup. The rules are simple: anyo... | We can prove that the first one to leave the circle does not make any difference to our answer. So after trying some tests, you will probably come up with an idea of selecting the cats that are sitting right between the other two to be the prior ones to leave because, in this way, those vacancies will definitely be use... | [
"greedy",
"math"
] | 900 | #include <iostream>
using namespace std;
int main ()
{
int n, m;
cin >> n >> m;
cout << (m ? min(m, n - m) : 1) << endl;
return 0;
} |
1163 | B2 | Cat Party (Hard Edition) | This problem is same as the previous one, but has larger constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the $n$ days since the day Shiro moved to ... | We can iterate over all streaks and check for each streak if we can remove one day so that each color has the same number of cats. There are 4 cases where we can remove a day from the streak to satisfy the condition: There is only one color in this streak. All appeared colors in this streak have the occurrence of $1$ (... | [
"data structures",
"implementation"
] | 1,600 | #include <iostream>
#include <stdio.h>
using namespace std;
const int N = 1e5 + 10;
int n, color, ans, mx, f[N], cnt[N];
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &color);
cnt[f[color]]--;
f[color]++;
cnt[f[color]]++;
mx = max(mx, f[color])... |
1163 | C2 | Power Transmission (Hard Edition) | This problem is same as the previous one, but has larger constraints.
It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system c... | First, we will divide the problem into several parts: 1) construct the wires, 2) remove duplicates, and 3) count the number of pairs that intersect. The first part is relatively simple: note that each wire is simply a line that goes through two distinct points (poles) on the $Oxy$ plane. Suppose this line goes through ... | [
"data structures",
"geometry",
"implementation",
"math"
] | 1,900 | #include <cstdio>
#include <map>
#include <set>
#include <utility>
const int N = 1001;
int x[N], y[N];
std::map<std::pair<int,int>,std::set<long long>> slope_map;
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
int main()
{
int n; scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d%... |
1163 | D | Mysterious Code | During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string $c$ consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited ... | Firstly, we will find the maximal value of $f(c', s) - f(c', t)$ via dynamic programming. Denote 'dp[i][ks][kt]' as the maximal value of the said value when replacing the first $i$-th character of $c$, and the KMP state for the replaced sub-code to be $ks$ and $kt$. The maximal value of $f(c', s) - f(c', t)$ for the wh... | [
"dp",
"strings"
] | 2,100 | #include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int K = 1005, N = 55, M = 55, INF = 1E9 + 7;
int k, n, m;
int kmp_s[N], nxt_s[N][26], kmp_t[M], nxt_t[M][26];
int dp[K][N][M];
char code[K], s[N], t[M];
void init(char s[], int n, int kmp[], int nxt[][26])
{
kmp[1] = 0;
for (... |
1163 | E | Magical Permutation | Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen $n$ distinct positive integers and put all of them in a set $S$. Now he defines a magical permutation to be:
- A permutation of integers from $0$ to $2^x - 1$, where $x$ is a non-negative integer.
- The bi... | The idea here is iterate $x$ and check if it is possible to create a magical permutation for the current $x$ we are iterating through. An observation to be made is that if it is possible to create a magical permutation $P$ from $0$ to $2^x - 1$, then it must be possible to express each integer from $0$ to $2^x - 1$ as ... | [
"bitmasks",
"brute force",
"constructive algorithms",
"data structures",
"graphs",
"math"
] | 2,400 | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 200005, MX = 1E6 + 5;
int n, x = 0, a[N];
bool vis[MX];
vector<int> basis, vec, ans;
void add(int u)
{
int tmp = u;
for (int &v : basis)
u = min(u, u ^ v);
if (u > 0)
{
basi... |
1163 | F | Indecisive Taxi Fee | In the city of Capypaland where Kuro and Shiro resides, there are $n$ towns numbered from $1$ to $n$ and there are $m$ bidirectional roads numbered from $1$ to $m$ connecting them. The $i$-th road connects towns $u_i$ and $v_i$. Since traveling between the towns is quite difficult, the taxi industry is really popular h... | Firstly, we will find and trace out one shortest path from vertex $1$ to vertex $n$ in the graph. Let's call this path main path, and we will number the edges on the main path as $E_1$, $E_2$, .., $E_k$ respectively. We will also call all of the other edges that does not belong to this main path candidate edges. During... | [
"data structures",
"graphs",
"shortest paths"
] | 3,000 | #include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int N = 2E5 + 5, M = 2E5 + 5;
const long long INF = 1E18 + 7;
int n, m, q, ed, nw, mx, u[M], v[M], w[M], ind[M];
int tr[N], le[N], ri[N];
bool on_path[N];
long long dis[2][N];
struct TNode
{
int u;
long long v... |
1165 | A | Remainder | You are given a huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.
You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change... | As we can see, last $x$ digits of the resulting number will be zeros except the $n-y$-th. So we need to change all ones to zeros (if needed) among last $x$ digits, if the position of the digit is not $n-y$, and change zero to one (if needed) otherwise. It can be done with simple cycle. | [
"implementation",
"math"
] | 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, x, y;
string s;
cin >> n >> x >> y >> s;
int ans = 0;
for (int i = n - x; i < n; ++i) {
if (i == n - y - 1) ans += s[i] != '1';
else ans += s[i]... |
1165 | B | Polycarp Training | Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $1$ problem, during the second day — exactly $2$ problems, during the third day — exactly $3$ problems, and so on. During the $k$-th day he should solve $k$ problems.
Polycarp has a list of $n$ ... | After sorting the array, we can maintain the last day Polycarp can train, in the variable $pos$. Initially it is $1$. Let's iterate over all elements of the sorted array in non-decreasing order and if the current element $a_i \ge pos$ then let's increase $pos$ by one. The answer will be $pos - 1$. | [
"data structures",
"greedy",
"sortings"
] | 1,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;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
int pos = 1;
for (int i = 0; i < n; ++i) {
... |
1165 | C | Good String | Let's call (yet again) a string \textbf{good} if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good stri... | The following greedy solution works: let's iterate over all characters of the string from left to right, and if the last block of two consecutive characters in the resulting string is full, just add the current character to the resulting string, otherwise add this character if it is not equal to the first character of ... | [
"greedy"
] | 1,300 | #include<bits/stdc++.h>
using namespace std;
string s;
int n;
string res;
int main()
{
cin >> n >> s;
for(int i = 0; i < n; i++)
{
if(res.size() % 2 == 0 || res.back() != s[i])
res.push_back(s[i]);
}
if(res.size() % 2 == 1) res.pop_back();
cout << n - int(res.size()) << endl << res << endl;
return 0;
} |
1165 | D | Almost All Divisors | We guessed some integer number $x$. You are given a list of \textbf{almost all} its divisors. \textbf{Almost all} means that there are \textbf{all divisors except $1$ and $x$} in the list.
Your task is to find the minimum possible integer $x$ that can be the guessed number, or say that the input data is contradictory ... | Suppose the given list of divisors is a list of almost all divisors of some $x$ (in other words, suppose that the answer exists). Then the minimum divisor multiplied by maximum divisor should be $x$. This is true because if we have a divisor $i$ we also have a divisor $\frac{n}{i}$. Let's sort all divisors and let $x =... | [
"math",
"number theory"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
int n;
cin >> n;
vector<long long> d(n);
for (int i = 0; i < n; ++i) {
cin >> d[i];
}
sort(d.begi... |
1165 | E | Two Arrays and Sum of Functions | You are given two arrays $a$ and $b$, both of length $n$.
Let's define a function $f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array $b$ to minimize the value of $\sum\limits_{1 \le l \le r \le n} f(l, r)$. Since the answer ... | Let's use contribution to the sum technique to solve this problem. How many times the value $a_i \cdot b_i$ will occur in the answer? It will occur $i \cdot (n - i + 1)$ times. Okay, now we can see that for each position $i$ we have the value $a_i \cdot b_i \cdot i \cdot (n - i + 1)$. The only non-constant value there ... | [
"greedy",
"math",
"sortings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n), b(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < n; ++i) {
cin >> b... |
1165 | F1 | Microtransactions (easy version) | \textbf{The only difference between easy and hard versions is constraints}.
Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of... | Let's iterate over all possible answers. Obviously, this value is always in the range $[1, 2 \cdot \sum\limits_{i=1}^{n}k_i]$. The first day when Ivan can order all microtransactions he wants will be the answer. How to check if the current day $ansd$ is enough to order everything Ivan wants? If we had several sale days... | [
"binary search",
"greedy"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> k;
vector<pair<int, int>> q(1001);
bool can(int day) {
vector<int> lst(n, -1);
for (int i = 0; i < m; ++i) {
if (q[i].first <= day) {
lst[q[i].second] = max(lst[q[i].second], q[i].first);
}
}
vector<vector<int>> off(1001);
for (int i = 0... |
1165 | F2 | Microtransactions (hard version) | \textbf{The only difference between easy and hard versions is constraints}.
Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of... | The main idea of this problem is the same as in the easy version. The only thing we should replace is the search method. Replacing linear search with binary search leads to reducing time complexity from $O(n^2)$ to $O(n \log n)$. And it is obvious that we can apply binary search here because if we can order all microtr... | [
"binary search",
"greedy",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> k;
vector<pair<int, int>> q(200001);
bool can(int day) {
vector<int> lst(n, -1);
for (int i = 0; i < m; ++i) {
if (q[i].first <= day) {
lst[q[i].second] = max(lst[q[i].second], q[i].first);
}
}
vector<vector<int>> off(200001);
for (int i... |
1166 | A | Silent Classroom | There are $n$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ... | First, note that we can solve the problem for each starting letter independently, because two students whose name starts with a different letter never form a chatty pair. How do we solve the problem when all the students' names start with the same letter? We claim that it's best to split as evenly as possible. If one c... | [
"combinatorics",
"greedy"
] | 900 | null |
1166 | B | All the Vowels Please | Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $k$ is vowelly if there are positive integers $n$ and $m$ such that $n\cdot m = k$ and when the word is written by using $n$ rows and $m$ columns (the first row is filled first, then the second and ... | First, which boards could we feasibly fill with characters satisfying that every row and column contains one vowel at least once? Well, if we have a board with less than $5$ rows, then each column contains less than $5$ characters, so we cannot have every vowel on each column, and we can't fill the board. Similarly, we... | [
"constructive algorithms",
"math",
"number theory"
] | 1,100 | null |
1166 | C | A Tale of Two Lands | The legend of the foundation of Vectorland talks of two integers $x$ and $y$. Centuries ago, the array king placed two markers at points $|x|$ and $|y|$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers... | Formally, the condition for the legend being true reads $\min(\vert x - y \vert, \vert x + y \vert) \le \vert x \vert, \vert y \vert \le \max(\vert x - y \vert, \vert x + y \vert)$ Now, it is possible to characterize when this condition happens through casework on the signs and sizes of $x$ and $y$, but this can be tri... | [
"binary search",
"sortings",
"two pointers"
] | 1,500 | null |
1166 | D | Cute Sequences | Given a positive integer $m$, we say that a sequence $x_1, x_2, \dots, x_n$ of positive integers is $m$-cute if for every index $i$ such that $2 \le i \le n$ it holds that $x_i = x_{i - 1} + x_{i - 2} + \dots + x_1 + r_i$ for some positive integer $r_i$ satisfying $1 \le r_i \le m$.
You will be given $q$ queries consi... | We will first deal with determining when the sequence doesn't exist. To do this, we place some bounds on the values of $x_n$. If we choose all values of the $r_i$ to be equal to $1$ then we can calculate that $x_n = 2^{n - 2}(x_1 + 1)$. Reciprocally if we choose all $r_i$ to be equal to $m$ then we find $x_n = 2^{n - 2... | [
"binary search",
"brute force",
"greedy",
"math"
] | 2,200 | null |
1166 | E | The LCMs Must be Large | Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?
There are $n$ stores numbered from $1$ to $n$ in Nlogonia. The $i$-th of these stores offers a \textbf{positive integer} $a_i$.
Each day among the last $m$ days Dora bought a ... | We denote by $\textrm{lcm}\; A$ the $\textrm{lcm}$ of all elements in a collection $A$. Also, denote by $D_i$ and $S_i$ the collections that Dora and Swiper bought on day $i$, respectively. First, when can we say for sure that the values of $a_i$ cannot exist? Well, suppose that $D_i = S_j$ for some $i$ and $j$. Then w... | [
"bitmasks",
"brute force",
"constructive algorithms",
"math",
"number theory"
] | 2,100 | null |
1166 | F | Vicky's Delivery Service | In a magical land there are $n$ cities conveniently numbered $1, 2, \dots, n$. Some pairs of these cities are connected by magical colored roads. Magic is unstable, so at any time, new roads may appear between two cities.
Vicky the witch has been tasked with performing deliveries between some pairs of cities. However,... | Let $G$ be the graph with cities as vertices and roads as edges. Note that the edges originally in $G$ can be regarded as $m$ queries of the "add edge" type, so we will just describe a solution that can handle $m + q$ queries of any type. We need a way to capture the idea of going through two roads of the same color in... | [
"data structures",
"dsu",
"graphs",
"hashing"
] | 2,400 | null |
1167 | A | Telephone Number | A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string $s$ of length $n$, consisting of digits.
In one operation you can delete any character from s... | To solve this problem, we just need to find the first occurrence of the digit $8$, let's denote it as $x$. Now if $n - x \ge 10$ then answer is $YES$, otherwise $NO$. | [
"brute force",
"greedy",
"strings"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int n;
string s;
int main(){
int tc;
cin >> tc;
for(int t = 0; t < tc; ++t){
cin >> n >> s;
int pos = n;
for(int i = 0; i < n; ++i)
if(s[i] == '8'){
pos = i;
break;
}
... |
1167 | B | Lost Numbers | \textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentati... | The key fact that allows us to solve this problem is that if we analyze the pairwise products of special numbers, we will see that all of them (considering that we always multiply two different numbers) are unique. So, if we, for example, know that $a_i \cdot a_j = x$, then there are only two possibilities for the valu... | [
"brute force",
"divide and conquer",
"interactive",
"math"
] | 1,400 | #include<bits/stdc++.h>
using namespace std;
vector<int> p = {4, 8, 15, 16, 23, 42};
int ans[4];
int main()
{
for(int i = 0; i < 4; i++)
{
cout << "? " << i + 1 << " " << i + 2 << endl;
cout.flush();
cin >> ans[i];
}
do
{
bool good = true;
for(int i = 0; i < 4; i++)
good &= (p[i] * p[i + 1] == ans[... |
1167 | C | News Distribution | In some social network, there are $n$ users communicating with each other in $m$ groups of friends. Let's analyze the process of distributing some news between users.
Initially, some user $x$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at l... | The first intention after reading the problem is to reformulate it in graph theory terms. Let people be vertices, edge between two vertices $x$ and $y$ exists if $x$ and $y$ have some group in common. Basically, if person $x$ starts distributing the news, everyone in his connectivity component recieves it. Thus, the ta... | [
"dfs and similar",
"dsu",
"graphs"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int N = 500 * 1000 + 13;
int n, m;
int rk[N], p[N];
int getP(int a){
return (a == p[a] ? a : p[a] = getP(p[a]));
}
void unite(int a, int b){
a = getP(a), b = getP(b);
if (a == b) return;
if (rk[a] < rk[b]) ... |
1167 | D | Bicolored RBS | A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and ... | Let $d(s)$ be nested depth of RBS $s$. There is an interesting fact that $\max(d(r), d(b)) \ge \left\lceil \frac{d(s)}{2} \right\rceil$. From the other side we can always reach equation $\max(d(r), d(b)) = \left\lceil \frac{d(s)}{2} \right\rceil$ using some approaches. Let's look at prefix of length $i$ of string $s$. ... | [
"constructive algorithms",
"greedy"
] | 1,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())
int n;
string s;
inline bool read() {
if(!(cin >> n))
return false;
cin >> s;
return true;
}
inline void solve() {
string t(n, '0');
int bal = 0;
fore(i, 0, n) {
if(s[i] ... |
1167 | E | Range Deleting | You are given an array consisting of $n$ integers $a_1, a_2, \dots , a_n$ and an integer $x$. It is guaranteed that for every $i$, $1 \le a_i \le x$.
Let's denote a function $f(l, r)$ which erases all values such that $l \le a_i \le r$ from the array $a$ and returns the resulting array. For example, if $a = [4, 1, 1, ... | Lets find the maximum number $pref$ such that all values $1, 2, \dots, pref$ form the non-descending order array. It can be done the following way. Let values $1, 2, \dots, x$ form the non-descending order array. Then values $1, 2, \dots, x, x+1$ will form the non-descending order array if the first occurrence of $x+1$... | [
"binary search",
"combinatorics",
"data structures",
"two pointers"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int N = int(1e6) + 99;
int n, x;
int a[N];
vector <int> pos[N];
int prefMax[N];
int main() {
scanf("%d %d", &n, &x);
for(int i = 0; i < n; ++i){
scanf("%d", a + i);
pos[a[i]].push_back(i);
prefMax[i] = max(a[i], (i > 0 ? prefMax[i - 1] : a[i]));
}
int ... |
1167 | F | Scalar Queries | You are given an array $a_1, a_2, \dots, a_n$. All $a_i$ are pairwise distinct.
Let's define function $f(l, r)$ as follows:
- let's define array $b_1, b_2, \dots, b_{r - l + 1}$, where $b_i = a_{l - 1 + i}$;
- sort array $b$ in increasing order;
- result of the function $f(l, r)$ is $\sum\limits_{i = 1}^{r - l + 1}{b... | Let's define some functions at first: indicator function $I(x) = 1$ if $x$ is true and $0$ otherwise. $lower(l, r, x)$ is a number of $a_j$ that $l \le j \le r$ and $a_j < x$. Good observation: $lower(l, r, x) = \sum_{j = l}^{j = r}{I(a_j < x)}$. Another observation: $f(l, r) = \sum\limits_{i = l}^{i = r}{a_i \cdot (lo... | [
"combinatorics",
"data structures",
"math",
"sortings"
] | 2,300 | #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())
typedef long long li;
const int MOD = int(1e9) + 7;
int add(int a, int b) {
a += b;
while(a >= MOD)
a -= MOD;
while(a < 0)
a += MOD;
return a;
}
int mul(int a, int b) {
retu... |
1167 | G | Low Budget Inception | So we got bored and decided to take our own guess at how would "Inception" production go if the budget for the film had been terribly low.
The first scene we remembered was the one that features the whole city bending onto itself:
It feels like it will require high CGI expenses, doesn't it? Luckily, we came up with a... | Let's solve the problem for a single query at first. There are two possible types of collisions: between two buildings and between a building and a ray. Obviously, if the collision of the second type happens, then it's the building which is the closest to the bend point (from either left or right). The less obvious cla... | [
"brute force",
"geometry"
] | 3,100 | #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;
const int INF = int(1e9);
const li INF64 = li(1e18);
const int N = 200 * 1000 + 555;
const int D = 7077;
int n, d, m;
int a[... |
1168 | A | Increasing by Modulo | Toad Zitz has an array of integers, each integer is between $0$ and $m-1$ inclusive. The integers are $a_1, a_2, \ldots, a_n$.
In one operation Zitz can choose an integer $k$ and $k$ indices $i_1, i_2, \ldots, i_k$ such that $1 \leq i_1 < i_2 < \ldots < i_k \leq n$. He should then change $a_{i_j}$ to $((a_{i_j}+1) \bm... | Let's check that the answer to the problem is $\leq x$. Then, for each element, you have some interval (interval on the "circle" of remainders modulo $m$) of values, that it can be equal to. So you need to check that you can pick in each interval some point, to make all these values non-decrease. You can do it with gre... | [
"binary search",
"greedy"
] | 1,700 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0... |
1168 | B | Good Triple | Toad Rash has a binary string $s$. A binary string consists only of zeros and ones.
Let $n$ be the length of $s$.
Rash needs to find the number of such pairs of integers $l$, $r$ that $1 \leq l \leq r \leq n$ and there is at least one pair of integers $x$, $k$ such that $1 \leq x, k \leq n$, $l \leq x < x + 2k \leq r... | Lemma: there are no strings without such $x,k$ of length at least 9. In fact, you just can write brute force to find all "good" strings and then realize that they all are small. Ok, so with this you can just write some sort of "naive" solution, for each $l$ find the largest $r$, such that $l \ldots r$ is a "good" strin... | [
"brute force",
"two pointers"
] | 1,900 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0... |
1168 | C | And Reachability | Toad Pimple has an array of integers $a_1, a_2, \ldots, a_n$.
We say that $y$ is reachable from $x$ if $x<y$ and there exists an integer array $p$ such that $x = p_1 < p_2 < \ldots < p_k=y$, and $a_{p_i}\, \&\, a_{p_{i+1}} > 0$ for all integers $i$ such that $1 \leq i < k$.
Here $\&$ denotes the bitwise AND operation... | Let's calculate $go_{i, k}$ - the smallest $j$, such that $a_j$ contains bit $k$, which is reachable from $i$. How to recalculate it? Let $last_{i,k}$ is the smallest $j > i$, such that $a_j$ contains bit $k$. Then, I claim that $go_{i,k}$ is equal to the $i$ or to the $\min{(go_{last_{i,j},k})}$ for all bits $j$ that ... | [
"bitmasks",
"dp"
] | 2,200 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nconst int N = 3e5 + 7;\nconst int LG = 19;\n\nint go[N][LG];\nint a[N];\nint last[LG];\n\nint main() {\n#ifdef... |
1168 | D | Anagram Paths | Toad Ilya has a rooted binary tree with vertex $1$ being the root. A tree is a connected graph without cycles. A tree is rooted if one vertex is selected and called the root. A vertex $u$ is a child of a vertex $v$ if $u$ and $v$ are connected by an edge and $v$ is closer to the root than $u$. A leaf is a non-root vert... | Ok, let's make some useless (ha-ha, in fact not) observation at first, obviously, all leaves must have the same depth. Now, I will define the criterion for the tree to be good. Let $f(v,x)$ be the largest number of characters $x$ that contained on edges of some path from vertex $v$ to the leaf, and $len_v$ be the lengt... | [
"dp",
"implementation",
"trees"
] | 3,000 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0... |
1168 | E | Xor Permutations | Toad Mikhail has an array of $2^k$ integers $a_1, a_2, \ldots, a_{2^k}$.
Find two permutations $p$ and $q$ of integers $0, 1, \ldots, 2^k-1$, such that $a_i$ is equal to $p_i \oplus q_i$ for all possible $i$, or determine there are no such permutations. Here $\oplus$ denotes the bitwise XOR operation. | If xor of all elements of the array is not zero, then the answer is "Fou". Now let's assume that you have two permutations $p,q$ and when xored they are producing an array $a$. I will show that it is possible to change any two elements $a_i, a_j$ to elements $a_i \oplus x, a_j \oplus x$ with some transformation of the ... | [
"constructive algorithms",
"math"
] | 3,100 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0... |
1169 | A | Circle Metro | The circle line of the Roflanpolis subway has $n$ stations.
There are two parallel routes in the subway. The first one visits stations in order $1 \to 2 \to \ldots \to n \to 1 \to 2 \to \ldots$ (so the next stop after station $x$ is equal to $(x+1)$ if $x < n$ and $1$ otherwise). The second route visits stations in or... | Straightforward simulation. Check the intended solutions: Simulation | [
"implementation",
"math"
] | 900 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0... |
1169 | B | Pairs | Toad Ivan has $m$ pairs of integers, each integer is between $1$ and $n$, inclusive. The pairs are $(a_1, b_1), (a_2, b_2), \ldots, (a_m, b_m)$.
He asks you to check if there exist two integers $x$ and $y$ ($1 \leq x < y \leq n$) such that in each given pair at least one integer is equal to $x$ or $y$. | One of $x,y$ is obviously one of $a_1, b_1$. For example, let's fix who is $x$ from the first pair. Then you need to check that there exists some $y$ such that all pairs that don't contain $x$, contain $y$. For this, you can remember in the array for each value how many pairs that don't contain $x$ contain this value, ... | [
"graphs",
"implementation"
] | 1,500 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0... |
1172 | A | Nauuo and Cards | Nauuo is a girl who loves playing cards.
One day she was playing cards but found that the cards were mixed with some empty ones.
There are $n$ cards numbered from $1$ to $n$, and they were mixed with another $n$ empty cards. She piled up the $2n$ cards and drew $n$ of them. The $n$ cards in Nauuo's hands are given. T... | First, try to finish it without playing any empty cards. If that's not possible, the best choice is to play several empty cards in a row, then play from $1$ to $n$. For a card $i$, suppose that it is in the $p_i$-th position in the pile ($p_i=0$ if it is in the hand), you have to play at least $p_i - i + 1$ empty cards... | [
"greedy",
"implementation"
] | 1,800 | #include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 200010;
int n, a[N], b[N], p[N], ans;
int main()
{
int i, j;
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
scanf("%d", a + i);
p[a[i]] = 0;
}
for (i = 1; i <= n; ++i)
{
... |
1172 | B | Nauuo and Circle | Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $n$ \textbf... | First, if we choose a node as the root, then each subtree must be in a continuous arc on the circle. Then, we can use DP to solve this problem. Let $f_u$ be the number of plans to draw the subtree of $u$, then $f_u=(|son(u)|+[u\ne root])!\prod\limits_{v\in son(u)}f_v$ - choose a position for each subtree and then $u$ i... | [
"combinatorics",
"dfs and similar",
"dp",
"trees"
] | 1,900 |
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const int N = 200010;
const int mod = 998244353;
int n, ans, d[N];
int main()
{
int i, u, v;
scanf("%d", &n);
ans = n;
for (i = 1; i < n; ++i)
{
scanf("%d%d", &u, &v);
ans = (ll) ans * (++d[u]) %... |
1172 | C2 | Nauuo and Pictures (hard version) | \textbf{The only difference between easy and hard versions is constraints.}
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes $n$ pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with ... | First, let's focus on a single picture with weight $w$ which Nauuo likes, so we only have to know the sum of the weights of the pictures Nauuo likes ($SA=\sum\limits_{i=1}^nw_i[a_i=1]$) and the sum of the disliked ones ($SB=\sum\limits_{i=1}^nw_i[a_i=0]$) instead of all the $n$ weights. Then, we can use DP to solve thi... | [
"dp",
"probabilities"
] | 2,600 | #include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 200010;
const int M = 3010;
const int mod = 998244353;
int qpow(int x, int y) //calculate the modular multiplicative inverse
{
int out = 1;
while (y)
{
if (y & 1) out = (ll) out * x % mod;
x = (ll) x * x % mod;
... |
1172 | D | Nauuo and Portals | Nauuo is a girl who loves playing games related to portals.
One day she was playing a game as follows.
In an $n\times n$ grid, the rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. We denote a cell on the intersection of the $r$-th row and $c$-th column... | Consider this problem: the person in $(i,1)$ facing right is numbered $a_i$, the person in $(1,i)$ facing bottom is numbered $b_i$. The person numbered $p_i$ has to exit the grid from $(i,n)$, the person numbered $q_i$ has to exit the grid from $(n,i)$. The original problem can be easily transferred to this problem. An... | [
"constructive algorithms"
] | 2,900 | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 1010;
struct Portal
{
int x, y, p, q;
Portal(int _x, int _y, int _p, int _q): x(_x), y(_y), p(_p), q(_q) {}
};
vector<Portal> ans;
int n, a[N], b[N], c[N], d[N], ra[N], rb[N], rc[N], rd[N];
int main()
{... |
1172 | E | Nauuo and ODT | Nauuo is a girl who loves traveling.
One day she went to a tree, Old Driver Tree, literally, a tree with an old driver on it.
The tree is a connected graph consisting of $n$ nodes and $n-1$ edges. Each node has a color, and Nauuo will visit the ODT through a simple path on the tree in the old driver's car.
Nauuo wan... | For each color, we can try to maintain the number of simple paths that do not contain such color. If we can maintain such information, we can easily calculate the number of simple paths that contain a certain color, thus get the answer. For each color, we delete all nodes that belong to such color, thus splitting the t... | [
"data structures"
] | 3,300 | #include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
const int N = 400010;
struct Node
{
int fa, ch[2], siz, sizi;
ll siz2i;
ll siz2() { return (ll) siz * siz; }
} t[N];
bool nroot(int x);
void rotat... |
1172 | F | Nauuo and Bug | Nauuo is a girl who loves coding.
One day she was solving a problem which requires to calculate a sum of some numbers modulo $p$.
She wrote the following code and got the verdict "Wrong answer".
She soon discovered the bug — the ModAdd function only worked for numbers in the range $[0,p)$, but the numbers in the pro... | At first, let's solve this problem in $\mathcal{O}(n\sqrt{n \log n})$. Let's split our array into blocks by $B$ integers, and let's find a function, $f(x) =$ which value you will get at the end of the current block if you will start with $x$. With simple induction, you can prove that this function is a piece-wise linea... | [
"data structures"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000005;
const ll inf = (ll)1e16;
int n, m, P, a[N];
ll sum[N];
vector<ll> func[N << 2];
vector<ll> merge(int l, int r, int mid, const vector<ll> &f, const vector<ll> &g) {
ll suml = sum[mid] - sum[l - 1], sumr = sum[r] - sum[mid];
v... |
1173 | A | Nauuo and Votes | Nauuo is a girl who loves writing comments.
One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.
It's known that there were $x$ persons who would upvote, $y$ persons who would downvote, and there were also another $z$ persons who would vote, but you don't know whether the... | Consider the two edge cases: all the $z$ persons upvote / all the $z$ persons downvote. If the results are the same in these two cases, it is the answer. Otherwise, the result is uncertain. | [
"greedy"
] | 800 | #include <iostream>
using namespace std;
const char result[4] = {'+', '-', '0', '?'};
int solve(int x, int y)
{
return x == y ? 2 : x < y;
}
int main()
{
int x, y, z;
cin >> x >> y >> z;
cout << result[solve(x + z, y) == solve(x, y + z) ? solve(x, y) : 3];
return 0;
} |
1173 | B | Nauuo and Chess | Nauuo is a girl who loves playing chess.
One day she invented a game by herself which needs $n$ chess pieces to play on a $m\times m$ chessboard. The rows and columns are numbered from $1$ to $m$. We denote a cell on the intersection of the $r$-th row and $c$-th column as $(r,c)$.
The game's goal is to place $n$ ches... | $m\ge\left\lfloor\frac n 2\right\rfloor+1$ Consider the chess pieces $1$ and $n$. $\because\begin{cases}|r_1-r_n|+|c_1-c_n|\ge n-1\\|r_1-r_n|\le m-1\\|c_1-c_n|\le m-1\end{cases}$ $\therefore m-1+m-1\ge n-1$ $\therefore m\ge\frac{n+1}2$ $\because m\text{ is an integer}$ $\therefore m\ge\left\lfloor\frac n 2\right\rfloor... | [
"constructive algorithms",
"greedy"
] | 1,100 | #include <cstdio>
using namespace std;
int main()
{
int n, i, ans;
scanf("%d", &n);
ans = n / 2 + 1;
printf("%d", ans);
for (i = 1; i <= ans; ++i) printf("\n%d 1", i);
for (i = 2; i <= n - ans + 1; ++i) printf("\n%d %d", ans, i);
return 0;
}
|
1174 | A | Ehab Fails to Be Thanos | You're given an array $a$ of length $2n$. Is it possible to reorder it in such way so that the sum of the first $n$ elements \textbf{isn't} equal to the sum of the last $n$ elements? | If all elements in the array are equal, there's no solution. Otherwise, sort the array. The sum of the second half will indeed be greater than that of the first half. Another solution is to see if they already have different sums. If they do, print the array as it is. Otherwise, find any pair of different elements from... | [
"constructive algorithms",
"greedy",
"sortings"
] | 1,000 | "#include <iostream>\n#include <algorithm>\nusing namespace std;\nint arr[2005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<2*n;i++)\n\tscanf(\"%d\",&arr[i]);\n\tsort(arr,arr+2*n);\n\tif (arr[0]==arr[2*n-1])\n\t{\n\t\tprintf(\"-1\");\n\t\treturn 0;\n\t}\n\tfor (int i=0;i<2*n;i++)\n\tprintf(\"%d \",... |
1174 | B | Ehab Is an Odd Person | You're given an array $a$ of length $n$. You can perform the following operation on it as many times as you want:
- Pick two integers $i$ and $j$ $(1 \le i,j \le n)$ such that \textbf{$a_i+a_j$ is odd}, then swap $a_i$ and $a_j$.
What is lexicographically the smallest array you can obtain?
An array $x$ is lexicograp... | Notice that you can only swap 2 elements if they have different parities. If all elements in the array have the same parity, you can't do any swaps, and the answer will just be like the input. Otherwise, let's prove you can actually swap any pair of elements. Assume you want to swap 2 elements, $a$ and $b$, and they ha... | [
"sortings"
] | 1,200 | "#include <iostream>\n#include <algorithm>\nusing namespace std;\nbool ex[2];\nint arr[100005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tscanf(\"%d\",&arr[i]);\n\t\tex[arr[i]%2]=1;\n\t}\n\tif (ex[0] && ex[1])\n\tsort(arr,arr+n);\n\tfor (int i=0;i<n;i++)\n\tprintf(\"%d \",arr[i]);... |
1174 | C | Ehab and a Special Coloring Problem | You're given an integer $n$. For every integer $i$ from $2$ to $n$, assign a positive integer $a_i$ such that the following conditions hold:
- For any pair of integers $(i,j)$, if $i$ and $j$ are coprime, $a_i \neq a_j$.
- The maximal value of all $a_i$ should be minimized (that is, as small as possible).
A pair of i... | Let's call the maximum value in the array $max$. Let the number of primes less than or equal to $n$ be called $p$. Then, $max \ge p$. That's true because a distinct number must be assigned to each prime, since all primes are coprime to each other. Now if we can construct an answer wherein $max=p$, it'll be optimal. Let... | [
"constructive algorithms",
"number theory"
] | 1,300 | "#include <iostream>\nusing namespace std;\nint ans[100005];\nint main()\n{\n\tint n,c=0;\n\tscanf(\"%d\",&n);\n\tfor (int i=2;i<=n;i++)\n\t{\n\t\tif (!ans[i])\n\t\t{\n\t\t\tans[i]=++c;\n\t\t\tfor (int j=i;j<=n;j+=i)\n\t\t\tans[j]=ans[i];\n\t\t}\n\t\tprintf(\"%d \",ans[i]);\n\t}\n}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.