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 ⌀ |
|---|---|---|---|---|---|---|---|
1490 | E | Accidental Victory | A championship is held in Berland, in which $n$ players participate. The player with the number $i$ has $a_i$ ($a_i \ge 1$) tokens.
The championship consists of $n-1$ games, which are played according to the following rules:
- in each game, two random players with non-zero tokens are selected;
- the player with more ... | How can a player be checked if he can win the championship? Obviously, he must participate in all the games (otherwise we will increase the number of tokens of the opponents). So you can sort out all the people and play greedily with the weakest ones. Such a check will work in linear time after sorting, so we got a sol... | [
"binary search",
"data structures",
"greedy"
] | 1,400 | def win(pos : int, a : list):
power = a[pos]
for i in range(len(a)):
if i == pos:
continue
if power < a[i]:
return False
power += a[i]
return True
t = int(input())
while t > 0:
t -= 1
n = int(input())
a = list(map(int, input().split(' ')))
b ... |
1490 | F | Equalize the Array | Polycarp was gifted an array $a$ of length $n$. Polycarp considers an array beautiful if there exists a number $C$, such that each number in the array occurs either zero or $C$ times. Polycarp wants to remove some elements from the array $a$ to make it beautiful.
For example, if $n=6$ and $a = [1, 3, 2, 1, 4, 2]$, the... | Let's calculate the value of $cnt_x$ - how many times the number $x$ occurs in the array $a$. We will iterate over the value of $C$ and look for the minimum number of moves necessary for each number to appear in the $a$ array either $0$ times, or $C$ times. Note that if there is no such number $y$ that $cnt_y = C$, the... | [
"binary search",
"data structures",
"greedy",
"math",
"sortings"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
map<int, int> cnt;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
cnt[x]++;
}
map<int, int> groupedByCnt;
for (auto[x, y] : cnt) {
groupedByCnt[y]++;
}
int res = n;
int left = 0, right = n, rightCnt = (in... |
1490 | G | Old Floppy Drive | Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with $n$ integers written on it.
Polycarp wrote the numbers from the disk into the $a$ array. It turned out that the drive works according to the following algorithm:
- the drive takes one positive number ... | Let's denote for $S$ the sum of all the elements of the array, and for $pref$ the array of its prefix sums. If the drive runs for $t$ seconds, the sum is $\left\lfloor \frac{t}{s} \right\rfloor \cdot S + pref[t \bmod n]$. This formula immediately shows that if $\max\limits_{i=0}^{n-1} pref[i] < x$ and $S \le 0$, then t... | [
"binary search",
"data structures",
"math"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n, m;
cin >> n >> m;
vector<ll> a(n);
ll allSum = 0;
vector<ll> pref;
vector<int> ind;
int curInd = 0;
for (ll &e : a) {
cin >> e;
allSum += e;
if (pref.empty() || allSum > pref.back()) {
pref.push... |
1491 | A | K-th Largest Value | You are given an array $a$ consisting of $n$ integers. \textbf{Initially all elements of $a$ are either $0$ or $1$}. You need to process $q$ queries of two kinds:
- 1 x : Assign to $a_x$ the value $1 - a_x$.
- 2 k : Print the $k$-th largest value of the array.
As a reminder, $k$-th largest value of the array $b$ is d... | How can we find the largest $k$ such that the $k$-th smallest element of the array is $0$? How can we maintain $k$? Let's define $cnt$ to represent the number of 1s in the array. For the modifications, if $a_i$ is already $1$ now, then we let $cnt \gets cnt - 1$. Otherwise, let $cnt \gets cnt + 1$. For the querys, just... | [
"brute force",
"greedy",
"implementation"
] | 800 | n, q = map(int,input().split())
a = list(map(int,input().split()))
zero = a.count(0)
one = n - zero
for _ in range(q):
t, x = map(int,input().split())
if t == 1:
if a[x-1] == 1:
zero += 1
one -= 1
a[x-1] = 0
else:
zero -= 1
one += 1
... |
1491 | B | Minimal Cost | There is a graph of $n$ rows and $10^6 + 2$ columns, where rows are numbered from $1$ to $n$ and columns from $0$ to $10^6 + 1$:
Let's denote the node in the row $i$ and column $j$ by $(i, j)$.
Initially for each $i$ the $i$-th row has exactly one obstacle — at node $(i, a_i)$. You want to move some obstacles so that... | When is the answer $0$? Or rather, when do you not have to make any moves? What happens if $a[i]$ is same for all $i$? Consider the following situations: $\forall i \in [2,n], |a_i - a_{i - 1}| = 0$, then the answer will be $v + \min(u, v)$. $\exists i \in [2,n], |a_i - a_{i - 1}| > 1$, then the answer will be $0$. Oth... | [
"brute force",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int n, a[N], ans = INT_MAX, u, v, T;
int main()
{
ios::sync_with_stdio(false);
cin>>T;
while(T--){
ans = INT_MAX;
cin >> n >> u >> v;
for(int i = 1; i <= n; i++)
cin >> a[i];
for(int i = 2; i <= n; i++)
{
if(abs... |
1491 | C | Pekora and Trampoline | There is a trampoline park with $n$ trampolines in a line. The $i$-th of which has strength $S_i$.
Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice.
If at the moment Pekora jumps on trampoline $i$, the trampoline will launch her to position $i + S_i$, a... | Think greedily! By exchange argument, where can Pekora start her pass in an optimal solution? For a series of passes, we can describe it as an array $P$ where $P_i$ is the trampoline Pekora starts at in the $i$-th pass. We claim that the final state of trampolines after performing any permutation of $P$ will be the sam... | [
"brute force",
"data structures",
"dp",
"greedy",
"implementation"
] | 1,700 | TC=int(input())
for tc in range(TC):
n=int(input())
arr=list(map(int,input().split()))
curr=[0]*(n+5)
ans=0
for x in range(n):
temp=curr[x]
if (temp<arr[x]-1):
ans+=arr[x]-1-temp
temp+=arr[x]-1-temp
curr[x+1]+=temp... |
1491 | D | Zookeeper and The Infinite Zoo | There is a new attraction in Singapore Zoo: The Infinite Zoo.
The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled $1,2,3,\ldots$. There is a directed edge from vertex $u$ to vertex $u+v$ if and only if $u\&v=v$, where $\&$ denotes the bitwise AND operation. There are no other edg... | Since $\&$ is a bitwise operation, represent the number in binary form! We can convert any $u+v$ move to a series of $u+v'$ moves where $u\&v'=v'$ and $v'=2^k$. Such a move converts a substring of the binary string of the form $01\ldots11$ into $10\ldots00$. Focus on converting $01$ into $10$. Firstly, we can show that... | [
"bitmasks",
"constructive algorithms",
"dp",
"greedy",
"math"
] | 1,800 | def lsb(x):
return x & (-x)
Q = int(input())
for q in range(Q):
a,b = map(int,input().split(" "))
if a > b:
print("NO")
else:
can = True
while b > 0:
if lsb(b) < lsb(a) or a == 0:
can = False
break
a -= lsb(a)
b ... |
1491 | E | Fib-tree | Let $F_k$ denote the $k$-th term of Fibonacci sequence, defined as below:
- $F_0 = F_1 = 1$
- for any integer $n \geq 0$, $F_{n+2} = F_{n+1} + F_n$
You are given a tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles.
We call a tree a \textbf{Fib-tree}, if its number of vertices ... | The only pair $(j,k)$ that satisfies $F_i=F_j+F_k$ is $(i-1,i-2)$. Firstly, we can discover that we can only cut a tree in the size of $f_{i}$ into one in size of $f_{i-1}$ and one in size of $f_{i-2}$. We want to show that the only solution to $F_i=F_j+F_k$ is $(j,k)=(i-1,i-2)$ for $j \geq k$. Clearly, $i>j$, otherwis... | [
"brute force",
"dfs and similar",
"divide and conquer",
"number theory",
"trees"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, siz[N];
vector<int> fib;
vector<pair<int, bool> > G[N];
void NO() { cout << "NO\n"; exit(0); }
void GetSize(int u, int fa)
{
siz[u] = 1;
for(pair<int, bool> e : G[u])
{
if(e.second) continue;
int v = e.first;
... |
1491 | F | Magnets | This is an interactive problem.
Kochiya Sanae is playing with magnets. Realizing that some of those magnets are demagnetized, she is curious to find them out.
There are $n$ magnets, which can be of the following $3$ types:
- N
- S
- - — these magnets are demagnetized.
Note that \textbf{you don't know} the types of ... | Try to construct a solution that works in $2n$ queries. Try to find the second magnet which is not `-'. The actual query limit is $n-1+\lceil\log_2n\rceil$. It seems this problem needs some random technique, but here is a determinate solution: We just try to find a not demagnetized magnet. You can go through the follow... | [
"binary search",
"constructive algorithms",
"interactive"
] | 2,700 | #include<bits/stdc++.h>
int n;
std::vector<int>ans,tmp,hlf;
int main()
{
int T;
scanf("%d",&T);
for(;T--;)
{
ans.clear(),tmp.clear(),hlf.clear();
scanf("%d",&n);
register int i,ii;
int sec=0;
for(i=2;i<=n;i++)
{
printf("? 1 %d\n%d\n",i-1,i);
for(ii=1;ii<i;ii++)printf("%d... |
1491 | G | Switch and Flip | There are $n$ coins labeled from $1$ to $n$. Initially, coin $c_i$ is on position $i$ and is facing upwards (($c_1, c_2, \dots, c_n)$ is a permutation of numbers from $1$ to $n$). You can do some operations on these coins.
In one operation, you can do the following:
- Choose $2$ distinct indices $i$ and $j$.
- Then, ... | Visualize this problem as graph with directed edges $(i,c_i)$. Solve this problem where there is only $1$ big cycle. What if a cycle has $2$ coins that are upside down? How can we force a cycle into such state? We can visualize the problem as a graph with nodes of $2$ colors (face up - red and face down - blue). Initia... | [
"constructive algorithms",
"graphs",
"math"
] | 2,800 | from sys import stdin, stdout
n=int(stdin.readline())
#make 1-indexed
arr=[0]+list(map(int,stdin.readline().split()))
vis=[0]*(n+1)
ans=[]
def cswap(i,j):
arr[i],arr[j]=-arr[j],-arr[i]
ans.append((i,j))
def swap_cyc(i,j):
cswap(i,j)
curr=i
while (arr[-arr[curr]]>0):
cswap(curr... |
1491 | H | Yuezheng Ling and Dynamic Tree | Yuezheng Ling gives Luo Tianyi a tree which has $n$ nodes, rooted at $1$.
Luo Tianyi will tell you that the parent of the $i$-th node is $a_i$ ($1 \leq a_i<i$ for $2 \le i \le n$), and she will ask you to perform $q$ queries of $2$ types:
- She'll give you three integers $l$, $r$ and $x$ ($2 \le l \le r \le n$, $1 \l... | The complexity is $\mathcal O(n\sqrt{n})$. Divide the nodes into $\sqrt{n}$ blocks. The $i$-th block will contain the nodes in $[(i-1) \sqrt{n}+1,i \sqrt{n}]$. Let's define $f_x$ as an ancestor of $x$ such that $f_x$ is in the same block as $x$ and $a_{f_x}$ is not in the same block as $x$. Notice that for a given bloc... | [
"data structures",
"trees"
] | 3,400 | #include <bits/stdc++.h>
#define N 100005
using namespace std;
template <typename T>
void read(T &a)
{
T x = 0,f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
a ... |
1491 | I | Ruler Of The Zoo | After realizing that Zookeeper is just a duck, the animals have overthrown Zookeeper. They now have to decide a new ruler among themselves through a fighting tournament of the following format:
Initially, animal $0$ is king, while everyone else queues up with animal $1$ at the front of the queue and animal $n-1$ at th... | As the solution to this problem is very long, the full editorial is split into $4$ parts. If you want to challenge yourself, you can try reading one part at a time and see if you get any inspiration. You can also try to read the specific hints for each part. Convert the queue into a circle. Firstly, let's convert the q... | [
"brute force",
"data structures"
] | 3,500 | //雪花飄飄北風嘯嘯
//天地一片蒼茫
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se seco... |
1492 | A | Three swimmers | Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.
It takes the first swimmer exactly $a$ minutes to swim across the entire pool and come back, exactly $b$ minutes for the second swimmer and $c$ minutes for the third. Hence, the first swimmer ... | The answer is just $\min{(\lceil {p \over a} \rceil \cdot a, \lceil {p \over b} \rceil \cdot b, \lceil {p \over c} \rceil \cdot c)} - p$. Complexity: $O(1)$. | [
"math"
] | 800 | null |
1492 | B | Card Deck | You have a deck of $n$ cards, and you'd like to reorder it to a new one.
Each card has a value between $1$ and $n$ equal to $p_i$. All $p_i$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $p_1$ stands for the bottom card, $p_n$ is the top card.
In each step you pick some integer $k > 0$... | It's easy to prove that order of a deck differs for different permutations. And more than that order of permutation $a$ is greater than order of permutation $b$ if and only if $a$ is lexicographically greater than $b$. Since we need to build a lexicographic maximum permutation, at each point of time we need to choose s... | [
"data structures",
"greedy",
"math"
] | 1,100 | null |
1492 | C | Maximum width | Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $s$ of length $n$ and $t$ of length $m$.
A sequence $p_1, p_2, \ldots, p_m$, where $1 \leq p_1 < p_2 < \ldots < p_m \leq n$, is called beautiful, if $s_{p_i} = t_i$ for all $i$ from $1$ to $m$. The width... | For some subsequence of the string $s$, let $p_i$ denote the position of the character $t_i$ in the string $s$. For fixed $i$, we can find a subsequence that maximizes $p_{i + 1} - p_i$. Let $\textit{left}_{i}$ and $\textit{right}_{i}$ be the minimum and maximum possible value of $p_i$ among all valid $p$s. Now, it is ... | [
"binary search",
"data structures",
"dp",
"greedy",
"two pointers"
] | 1,500 | null |
1492 | D | Genius's Gambit | You are given three integers $a$, $b$, $k$.
Find two binary integers $x$ and $y$ ($x \ge y$) such that
- both $x$ and $y$ consist of $a$ zeroes and $b$ ones;
- $x - y$ (also written in binary form) has exactly $k$ ones.
You are \textbf{not allowed to use leading zeros for $x$ and $y$}. | This problem has a cute constructive solution. If $a = 0$ or $b = 1$ the answer is trivial. In other cases let's fix $x$ as a number in form $111 \ldots 1100 \ldots 000$. Let $y = x$, then we will change only $y$. Let's take the last $1$ digit from the consecutive prefix of ones, then move it $\min(k, a)$ positions to ... | [
"bitmasks",
"constructive algorithms",
"greedy",
"math"
] | 1,900 | null |
1492 | E | Almost Fault-Tolerant Database | You are storing an integer array of length $m$ in a database. To maintain internal integrity and protect data, the database stores $n$ copies of this array.
Unfortunately, the recent incident may have altered the stored information in every copy in the database.
It's believed, that the incident altered at most two el... | Let's look at the first array. Every possible answer (if there is any) should not differ from this array in more than $2$ positions. So we should try to change at most $2$ positions in the first array to find a consistent answer. Let's look at the other arrays. We can ignore each other array that differ with the first ... | [
"brute force",
"constructive algorithms",
"dfs and similar",
"greedy",
"implementation"
] | 2,500 | null |
1493 | A | Anti-knapsack | You are given two integers $n$ and $k$. You are asked to choose maximum number of distinct integers from $1$ to $n$ so that there is no subset of chosen numbers with sum equal to $k$.
A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. | Let's notice that we can take all numbers $k+1, k+2 \ldots n$, because every one of them is greater than $k$, and sum of any number from $k+1, k+2 \ldots n$ and any number from $1,2 \ldots n$ also is greater than $k$. Let's also take numbers from $\left \lceil \frac{k}{2} \right \rceil$ to $k - 1$ inclusive. Notice tha... | [
"constructive algorithms",
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t, n, k;
cin >> t;
while (t--) {
cin >> n >> k;
cout << n - k + k / 2 << '\n';
for (int i = k + 1; i <= n; ++i) cout << i << " ";
for (int i = (k + 1) / 2; i < ... |
1493 | B | Planet Lapituletti | The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $h$ hours and each hour lasts $m$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follo... | In order to solve the problem, you need to look over all the moments of time after the given one and check if the reflected time is correct in that moment of time. If such moment of time does not exist on the current day, the moment $00:00$ of the next day is always correct. For realization you need to notice that digi... | [
"brute force",
"implementation"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
vector < int > go = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
int inf = 1e9 + 7;
int get(int x) {
string s = to_string(x);
if ((int)s.size() == 1) s = "0" + s;
string answ = "";
for (int i = 1; i >= 0; --i) {
if (go[s[i] - '0'] == -1) return inf;
... |
1493 | C | K-beautiful Strings | You are given a string $s$ consisting of lowercase English letters and a number $k$. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by $k$. You are asked to find the lexicographically smallest beautiful string of length $n$, ... | First of all, let's notice that if the length of the string $n$ is not divisible by $k$, no beautiful string of such length exists. Otherwise the answer to the problem always exists (because the string $zz \ldots z$ is the greatest string of length $n$ and is beautiful). If the string $s$ is beautiful, then $s$ itself ... | [
"binary search",
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int cnt[26];
int get(int x, int k) {
return (k - x % k) % k;
}
main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k, t;
cin >> t;
while (t--) {
cin >> n >> k;
string s;
cin >> s;
for (int j ... |
1493 | D | GCD of an Array | You are given an array $a$ of length $n$. You are asked to process $q$ queries of the following format: given integers $i$ and $x$, multiply $a_i$ by $x$.
After processing each query you need to output the greatest common divisor (GCD) of all elements of the array $a$.
Since the answer can be too large, you are asked... | Notice that after each query the answer doesn't become smaller and we can solve the problem for each prime divisor independently. For each number let's maintain an amount of occurences for all its prime divisors (you can implement it using $map$). For each prime divisor let's write to its corresponding $multiset$ the a... | [
"brute force",
"data structures",
"hashing",
"implementation",
"math",
"number theory",
"sortings",
"two pointers"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int const maxn = 2e5 + 5, max_val = 2e5 + 5;
ll mod = 1e9 + 7, ans = 1;
int nxt[max_val], n;
multiset <int> cnt[max_val];
map <int, int> cnt_divisor[maxn];
void add(int i, int x) {
while (x != 1) {
int div = nxt[x], add = 0;
whi... |
1493 | E | Enormous XOR | You are given two integers $l$ and $r$ in binary representation. Let $g(x, y)$ be equal to the bitwise XOR of all integers from $x$ to $y$ inclusive (that is $x \oplus (x+1) \oplus \dots \oplus (y-1) \oplus y$). Let's define $f(l, r)$ as the maximum of all values of $g(x, y)$ satisfying $l \le x \le y \le r$.
Output $... | Let's numerate bits from $0$ to $n-1$ from the least significant bit to the most significant (from the end of the representation). If $n-1$-st bits of numbers $l$ and $r$ differ, then there is a power transition between numbers $l$ and $r$, and the answer to the problem is $11 \ldots 1$ (the number contains $n$ ones). ... | [
"bitmasks",
"constructive algorithms",
"greedy",
"math",
"strings",
"two pointers"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
string add(string s) {
int i = (int)s.size() - 1;
while (s[i] == '1') {
s[i] = '0';
i--;
}
s[i] = '1';
return s;
}
main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
string l, r;
... |
1493 | F | Enchanted Matrix | This is an interactive problem.
There exists a matrix $a$ of size $n \times m$ ($n$ rows and $m$ columns), you know only numbers $n$ and $m$. The rows of the matrix are numbered from $1$ to $n$ from top to bottom, and columns of the matrix are numbered from $1$ to $m$ from left to right. The cell on the intersection o... | Te problem can be solved in various ways but the main idea is that if we want to check, if the $x$ consecutive blocks are equal to each other, then we can do it using $\left \lceil \log_2 x \right \rceil$ queries. Let's suppose we want to check the equality of $x$ blocks, then we will check if the first and second $\le... | [
"bitmasks",
"interactive",
"number theory"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
int const maxn = 1005;
int dp[maxn];
vector < vector < int > > T;
int ask(int lx1, int ly1, int rx1, int ry1, int lx2, int ly2, int rx2, int ry2) {
cout << "? " << rx1 - lx1 + 1 << " " << ry1 - ly1 + 1 << " " << lx1 << " " << ly1
<< " " << lx2 << " " << ly2 << en... |
1494 | A | ABC String | You are given a string $a$, consisting of $n$ characters, $n$ is even. For each $i$ from $1$ to $n$ $a_i$ is one of 'A', 'B' or 'C'.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by in... | There are two key observations. First, a regular bracket sequence always starts with an opening bracket and ends with a closing one. Thus, the first letter of $a$ corresponds to an opening bracket and the last letter corresponds to a closing bracket. If they are the same, then the answer is "NO". Second, a regular brac... | [
"bitmasks",
"brute force",
"implementation"
] | 900 | #include <bits/stdc++.h>
using namespace std;
bool solve() {
string s;
cin >> s;
vector<int> d(3);
int x = s[0] - 'A';
int y = s.back() - 'A';
if (x == y)
return false;
d[x] = 1; d[y] = -1;
if (count(s.begin(), s.end(), 'A' + x) == s.length() / 2)
d[3 ^ x ^ y] = -1;
else
d[3 ^ x ^ y] = 1... |
1494 | B | Berland Crossword | Berland crossword is a puzzle that is solved on a square grid with $n$ rows and $n$ columns. Initially all the cells are white.
To solve the puzzle one has to color some cells on the border of the grid black in such a way that:
- exactly $U$ cells in the top row are black;
- exactly $R$ cells in the rightmost column ... | Consider some corner of the picture. If it's colored black, then it contributes to counts to both of the adjacent sides. Otherwise, it contributes to none. All the remaining cells can contribute only to the side they are on. There are $n-2$ of such cells on each side. So let's try all $2^4$ options of coloring the corn... | [
"bitmasks",
"brute force",
"greedy",
"implementation"
] | 1,400 | for _ in range(int(input())):
n, U, R, D, L = map(int, input().split())
for mask in range(16):
rU, rR, rD, rL = U, R, D, L
if mask & 1:
rU -= 1
rL -= 1
if mask & 2:
rL -= 1
rD -= 1
if mask & 4:
rD -= 1
rR -= ... |
1494 | C | 1D Sokoban | You are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line.
You start on a position $0$. There are $n$ boxes, the $i$-th box is on a position $a_i$. All positions of the boxes are distinct. There are also $m$ special positions, the $j$... | Since you can only push boxes, you can't bring boxes from negative positions to positive ones and vice versa. Thus, negative boxes/special positions and positive boxes/special positions are two separate tasks. You can solve them independently with the same algorithm and add up the answers. So, we will only consider the... | [
"binary search",
"dp",
"greedy",
"implementation",
"two pointers"
] | 1,900 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int calc(const vector<int> &a, const vector<int> &b){
int n = a.size();
int m = b.size();
vector<int> su(n + 1);
int r = m - 1;
for (int i = n - 1; i >= 0; --i){
su[i] = su[i + 1];
wh... |
1494 | D | Dogeforces | The Dogeforces company has $k$ employees. Each employee, except for lower-level employees, has at least $2$ subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all em... | We can solve the problem recursively from the root to the leaves. Let's maintain a list of leaf indices for the current subtree. If the list size is equal to $1$, then we can stop our recursion. Otherwise, we have to find the value of the root of the current subtree and split all leaves between child nodes. The root va... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"divide and conquer",
"dsu",
"greedy",
"sortings",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
const int N = 505;
int n;
int a[N][N];
int c[2 * N];
vector<pair<int, int>> e;
int calc(vector<int> ls) {
if (sz(ls) == 1)
return ls[0];
int res = -1;
for (int u : ls)
res = max(res, a[ls[0]][u]);
vector<vector<int>> ... |
1494 | E | A-Z Graph | You are given a directed graph consisting of $n$ vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty.
You should process $m$ queries with it. Each query is one of three types:
- "$+$ $u$ $v$ $c$" — add arc from $u$ to $v$ with label $c$. It's guaranteed that there is n... | At first, if there should be both routes $v_1, v_2, \dots, v_k$ and $v_k, v_{k - 1}, \dots, v_1$ then there are both arcs $(v_1, v_2)$ and $(v_2, v_1)$, i. e. there should exist at least one pair $\{u, v\}$ that both arcs $(u, v)$ and $(v, u)$ are present in the graph. Now, if $k$ is odd, and we have at least one pair ... | [
"constructive algorithms",
"data structures",
"graphs",
"hashing"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef pair<int, int> pt;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m;
cin >> n >> m;
map<... |
1494 | F | Delete The Edges | You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. Your goal is to destroy all edges of the given graph.
You may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if i... | Let's suppose our graph is split into two graphs $G_1$ and $G_2$, the first graph contains the edges we delete before the mode shift, the second graph contains the edges we delete after the mode shift. It's quite obvious that the graph $G_1$ has an eulerian path. The structure of $G_2$ is a bit harder to analyze, but w... | [
"brute force",
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
const int N = 300043;
int n, m;
set<int> g[N];
set<int> g2[N];
vector<int> res;
void euler(int x)
{
while(!g2[x].empty())
{
int y = *g2[x].begin();
g2[x].erase(y);
g2[y].erase(x);
euler(y);
}
res.push_back(x);
}
bool che... |
1495 | A | Diamond Miner | Diamond Miner is a game that is similar to Gold Miner, but there are $n$ miners instead of $1$ in this game.
The mining area can be described as a plane. The $n$ miners can be regarded as $n$ points \textbf{on the y-axis}. There are $n$ diamond mines in the mining area. We can regard them as $n$ points \textbf{on the ... | First, you can turn a point $(x,y)$ to $(|x|,|y|)$, while not changing the answer. After this operation, all points can be described as $(0,a)$ or $(b,0)$ ($a,b > 0$). In a triangle, if the length of the edges are $a$, $b$, $c$, it is obvious that $a+b > c$. So, if you connect all match-pairs with a segment and there a... | [
"geometry",
"greedy",
"math",
"sortings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int n,X[maxn],Y[maxn],t1,t2;
int main(){
int T; scanf("%d",&T);
for(int i(1);i <= T;++i){
scanf("%d",&n); t1 = t2 = 0;
for(int i(1);i <= 2*n;++i){
int x,y;
scanf("%d%d",&x,&y);
if(x == 0) Y[++t2] = abs(y);
else X[... |
1495 | B | Let's Go Hiking | On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper.
A permutation $p$ is written from left to right on the paper. First Qingshan chooses an integer index $x$ ($1\le x\le n$) and tells it to Daniel. Aft... | Let's consider that the $2k+1(k\ge 0)$-th turn is Qingshan's and the $2k+2(k\ge 0)$-th turn is Daniel's. If Qingshan chooses $x(1<x\le n)$ satisfying $x=n$ or $p_x<p_{x+1}$, then Daniel can choose $y=x-1$ to make Qingshan can't move in the first turn. The case that $x=1$ or $p_x<p_{x-1}$ is the same. So Qingshan must c... | [
"games",
"greedy"
] | 1,900 | #include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ch() getchar()
#define pc(x) putchar(x)
using namespace std;
template<typename T>void read(T&x){
static char c;static int f;
for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;
}
templat... |
1495 | C | Garden of the Sun | There are many sunflowers in the Garden of the Sun.
Garden of the Sun is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were ... | When $m$ is the multiple of $3$, it's easy to construct a solution: First, remove all the sunflowers on column $2,5,8,11,\ldots$. This operation won't form a cycle in the graph. Let's take this as an example: After the operation, the graph turns into: After that, you need to connect these columns to make them connected... | [
"constructive algorithms",
"graphs"
] | 2,300 | #include <bits/stdc++.h>
const int MX = 1e3 + 23;
int read(){
char k = getchar(); int x = 0;
while(k < '0' || k > '9') k = getchar();
while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();
return x;
}
char str[MX][MX];
void solve(){
int n = read() ,m = read();
for(int i = 1 ; i <= n ; ++i){
sc... |
1495 | D | BFS Trees | We define a spanning tree of a graph to be a BFS tree rooted at vertex $s$ if and only if for every node $t$ the shortest distance between $s$ and $t$ in the graph is equal to the shortest distance between $s$ and $t$ in the spanning tree.
Given a graph, we define $f(x,y)$ to be the number of spanning trees of that gr... | Let's enumerate vertexes $x,y$, and calculate $f(x,y)$ for them. Let $dist(x,y)$ denote the number of the vertexes which lie on the shortest-path between $x$ and $y$ on the graph. It is obvious that the distance between $x$ and $y$ in the tree is equal to $dist(x,y)$. And the vertex $z$ satisfying $dist(x,z)+dist(y,z)-... | [
"combinatorics",
"dfs and similar",
"graphs",
"math",
"shortest paths",
"trees"
] | 2,600 | #pragma GCC optimize(2)
#include <bits/stdc++.h>
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define RI register int
typedef long long LL;
#define FILEIO(name) freopen(name".in", "r", stdin), freopen(name".out", "w", stdout);
using namespace std;
namespace IO {
char buf[1000000], *p1 = buf, *p2 = buf;
inl... |
1495 | E | Qingshan and Daniel | Qingshan and Daniel are going to play a card game. But it will be so boring if only two persons play this. So they will make $n$ robots in total to play this game automatically. Robots made by Qingshan belong to the team $1$, and robots made by Daniel belong to the team $2$. Robot $i$ belongs to team $t_i$. Before the ... | We can consider that the robots are standing on a cycle. The game ends up with at least one team having no cards. Let the team having no cards in the end be team $A$ and let the other be team $B$. If two teams both use up their cards, the first robot's team is $A$. For team $A$, we've already known how many cards will ... | [
"brute force",
"data structures",
"greedy",
"implementation"
] | 3,200 | #include <bits/stdc++.h>
#define debug(...) fprintf(stderr ,__VA_ARGS__)
#define __FILE(x)\
freopen(#x".in" ,"r" ,stdin);\
freopen(#x".out" ,"w" ,stdout)
#define LL long long
const int MX = 5e6 + 23;
const LL MOD = 1e9 + 7;
int read(){
char k = getchar(); int x = 0;
while(k < '0' || k > '9') k = getchar();
w... |
1495 | F | Squares | There are $n$ squares drawn from left to right on the floor. The $i$-th square has three integers $p_i,a_i,b_i$, written on it. The sequence $p_1,p_2,\dots,p_n$ forms a permutation.
Each round you will start from the leftmost square $1$ and jump to the right. If you are now on the $i$-th square, you can do one of the ... | If we let the parent of $i(1\le i\le n)$ is the rightmost $j$ satisfying $j<i,p_j>p_i$(if that $j$ doesn't exist, the parent of $i$ is $0$), we can get a tree and we can dfs the tree with the order $0,1,2,\dots,n$. Let's call the parent of $i$ is $\operatorname{pa}_i$ and the children set of $i$ is $\operatorname{child... | [
"constructive algorithms",
"data structures",
"dp",
"graphs",
"trees"
] | 3,300 | #include<set>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ch() getchar()
#define pc(x) putchar(x)
using namespace std;
template<typename T>void read(T&x){
static char c;static int f;
for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x... |
1496 | A | Split it! | Kawashiro Nitori is a girl who loves competitive programming.
One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.
Given a string $s$ and a parameter $k$, you need to check if there exist $k+1$ non-empty strings $a_1,a_2...,a_{k+1}$, such that $$s=a_1+a_2+\ldots ... | If $k=0$ or $s[1,k]+s[n-k+1,n]$ is a palindrome, the answer is yes. Otherwise, the answer is no. Note that when $2k=n$, the answer is no, too. The time complexity is $O(n+k)$ for each test case. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | 900 | #include <bits/stdc++.h>
#define debug(...) fprintf(stderr ,__VA_ARGS__)
#define __FILE(x)\
freopen(#x".in" ,"r" ,stdin);\
freopen(#x".out" ,"w" ,stdout)
#define LL long long
const int MX = 100 + 23;
const LL MOD = 998244353;
int read(){
char k = getchar(); int x = 0;
while(k < '0' || k > '9') k = getchar();
... |
1496 | B | Max and Mex | You are given a multiset $S$ initially consisting of $n$ distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.
You will perform the following operation $k$ times:
- Add the element $\lceil\frac{a+b}{2}\rceil$ (rounded up) into $S$, where $a = \operatorname{mex}(S)$ and $b... | Let $a=\max(S),b=\operatorname{mex}(S)$. When $k=0$, the answer is $n$. Otherwise if $b>a$, then $b=a+1$ , so $\lceil\frac{a+b}{2}\rceil=b$ . It's not hard to find out that $\max(S\cup\{b\})=b,\operatorname{mex}(S\cup\{b\})=b+1$, so the set $S$ always satisfies $\max(S)+1=\operatorname{mex}(S)$. So the answer is $n+k$ ... | [
"math"
] | 1,100 | #include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ch() getchar()
#define pc(x) putchar(x)
using namespace std;
template<typename T>void read(T&x){
static char c;static int f;
for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;
}
templat... |
1497 | A | Meximization | You are given an integer $n$ and an array $a_1, a_2, \ldots, a_n$. You should reorder the elements of the array $a$ in such way that the sum of $\textbf{MEX}$ on prefixes ($i$-th prefix is $a_1, a_2, \ldots, a_i$) is maximized.
Formally, you should find an array $b_1, b_2, \ldots, b_n$, such that the sets of elements ... | To maximize the sum of $\textbf{MEX}$ on prefixes we will use a greedy algorithm. Firstly we put all unique elements in increasing order to get maximal $\textbf{MEX}$ on each prefix. It is easy to see that replacing any two elements after that makes both $\textbf{MEX}$ and sum of $\textbf{MEX}$ less. In the end we put ... | [
"brute force",
"data structures",
"greedy",
"sortings"
] | 800 | // один манул
#include <bits/stdc++.h>
using namespace std;
int main() {
int T;
cin >> T;
while (T --> 0) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
sort(a.begin(), a.end());
vector<int> b;
for (int i = 0; i < n; i++... |
1497 | B | M-arrays | You are given an array $a_1, a_2, \ldots, a_n$ consisting of $n$ positive integers and a positive integer $m$.
You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.
Let's call an array $m$-divisible if for each two adjacent numbers in the array (two numbe... | Let's take each number modulo $m$. Now let $cnt_x$ be the amount of $x$ in array $a$. If $cnt_0 \neq 0$, then all $0$ should be put in a single array, answer increases by $1$. For each number $x \neq 0$ we put it in an array $x, m - x, x, m - x, \dots$ In this array the amount of $x$ and the amount of $m - x$ should di... | [
"constructive algorithms",
"greedy",
"math"
] | 1,200 | //два манула
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
map<int, int> cnt;
while (n--) {
int x;
cin >> x;
cnt[x % m]++;
}
int ans = 0;
for (aut... |
1497 | C1 | k-LCM (easy version) | \textbf{It is the easy version of the problem. The only difference is that in this version $k = 3$.}
You are given a positive integer $n$. Find $k$ positive integers $a_1, a_2, \ldots, a_k$, such that:
- $a_1 + a_2 + \ldots + a_k = n$
- $LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$
Here $LCM$ is the least common mult... | If $n$ is odd, then the answer is $(1, \lfloor \frac{n}{2} \rfloor, \lfloor \frac{n}{2} \rfloor)$ If $n$ is even, but is not a multiple of $4$, then the answer is $(\frac{n}{2} - 1, \frac{n}{2} - 1, 2)$. If $n$ is a multiple of $4$, then the answer is $(\frac{n}{2}, \frac{n}{4}, \frac{n}{4})$. | [
"constructive algorithms",
"math"
] | 1,200 | // три манула
#include <bits/stdc++.h>
using namespace std;
int main() {
int T;
cin >> T;
while (T --> 0) {
int n, k;
cin >> n >> k;
if (n % 2) cout << 1 << ' ' << n / 2 << ' ' << n / 2 << '\n';
else if (n % 2 == 0 && n % 4) cout << 2 << ' ' << n / 2 - 1 << ' ' << n / 2 - 1... |
1497 | C2 | k-LCM (hard version) | \textbf{It is the hard version of the problem. The only difference is that in this version $3 \le k \le n$.}
You are given a positive integer $n$. Find $k$ positive integers $a_1, a_2, \ldots, a_k$, such that:
- $a_1 + a_2 + \ldots + a_k = n$
- $LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$
Here $LCM$ is the least com... | In this solution we will reuse the solution for $k = 3$. The answer will be $1, 1, \ldots, 1$ ($k - 3$ times) and the solution $a, b, c$ of the easy version for $n - k + 3$. $(1 + 1 + \ldots + 1) + (a + b + c) = (k - 3) + (n - k - 3) = n$. Also $LCM(1, 1, \ldots, 1, a, b, c) = LCM(a, b, c) \le \frac{n - k + 3}{2} \le \... | [
"constructive algorithms",
"math"
] | 1,600 | // четыре манула
#include <bits/stdc++.h>
using namespace std;
vector<int> solve3(int n) {
if (n % 2 == 1) return {1, n / 2, n / 2};
if (n % 4 == 0) return {n / 2, n / 4, n / 4};
if (n % 2 == 0) return {2, n / 2 - 1, n / 2 - 1};
}
int main() {
int T;
cin >> T;
while (T --> 0) {
int n, ... |
1497 | D | Genius | \textbf{Please note the non-standard memory limit.}
There are $n$ problems numbered with integers from $1$ to $n$. $i$-th problem has the complexity $c_i = 2^i$, tag $tag_i$ and score $s_i$.
After solving the problem $i$ it's allowed to solve problem $j$ if and only if $\text{IQ} < |c_i - c_j|$ and $tag_i \neq tag_j$... | Let's consider a graph where vertexes are problems and there is an edge $\{i, j\}$ between vertexes $i$ and $j$ with weight $|c_i - c_j|$. Each edge has a unique weight. Let's prove that. Let's assume that $weight = |2^i - 2^j|$ and $i > j$. Then in binary form $weight$ has its $k$-th bit set true if and only if $j \le... | [
"bitmasks",
"dp",
"graphs",
"number theory"
] | 2,500 | // пять манулов
#include <bits/stdc++.h>
using namespace std;
int main() {
int T;
cin >> T;
while (T --> 0) {
int n;
cin >> n;
vector<long long> s(n), tag(n), dp(n, 0);
for (int i = 0; i < n; ++i) cin >> tag[i];
for (int i = 0; i < n; ++i) cin >> s[i];
for (i... |
1497 | E1 | Square-Free Division (easy version) | \textbf{This is the easy version of the problem. The only difference is that in this version $k = 0$.}
There is an array $a_1, a_2, \ldots, a_n$ of $n$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whos... | For factorization of $x = p_1^{q_1} \cdot p_2^{q_2} \cdot \cdots \cdot p_k^{q_k}$ let's define $mask(x) = p_1^{q_1 \bmod 2} \cdot p_2^{q_2 \bmod 2} \cdot \cdots \cdot p_m^{q_m \bmod 2}$. After that it is easy to see that $x \cdot y$ is a perfect square if and only if $mask(x) = mask(y)$. Now let's say $a_i = mask(a_i)$... | [
"data structures",
"dp",
"greedy",
"math",
"number theory",
"two pointers"
] | 1,700 | // шесть манулов
#include <bits/stdc++.h>
using namespace std;
const int MAXA = 1e7;
vector<int> primes;
int mind[MAXA + 1];
int main() {
for (int i = 2; i <= MAXA; ++i) {
if (mind[i] == 0) {
primes.emplace_back(i);
mind[i] = i;
}
for (auto &x : primes) {
... |
1497 | E2 | Square-Free Division (hard version) | \textbf{This is the hard version of the problem. The only difference is that in this version $0 \leq k \leq 20$.}
There is an array $a_1, a_2, \ldots, a_n$ of $n$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different posit... | Let's use the same definitions as in tutorial of E1. So after making $a_i = mask(a_i)$ for all $1 \le i \le n$ we need to split the whole array into minimal amount of contiguous subsegments with all different elements. Also, we can change $k$ elements how we want. Firstly, for each $1 \le i \le n$ and $0 \le j \le k$ l... | [
"data structures",
"dp",
"greedy",
"math",
"number theory",
"two pointers"
] | 2,500 | // семь манулов
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 1;
const int MAXA = 1e7;
vector<int> primes;
int mind[MAXA + 1];
int main() {
for (int i = 2; i <= MAXA; ++i) {
if (mind[i] == 0) {
primes.emplace_back(i);
mind[i] = i;
}
for (auto &... |
1498 | A | GCD Sum | The $\text{$gcdSum$}$ of a positive integer is the $gcd$ of that integer with its sum of digits. Formally, $\text{$gcdSum$}(x) = gcd(x, \text{ sum of digits of } x)$ for a positive integer $x$. $gcd(a, b)$ denotes the greatest common divisor of $a$ and $b$ — the largest integer $d$ such that both integers $a$ and $b$ a... | Can you think of the simplest properties that relate a number and its sum of digits? Note that if $X$ is a multiple of 3, then both $X$ as well as the sum of digits of $X$ are a multiple of 3! Can you put this property to use here? If $X$ is a multiple of 3, then $\texttt{gcd-sum}(X) \ge 3$. Therefore, we are guarantee... | [
"brute force",
"math"
] | 800 | from math import gcd
def valid(x):
return gcd(x, sum([ord(c) - ord('0') for c in str(x)])) != 1
t = int(input())
while t > 0:
t -= 1
n = int(input())
while not valid(n):
n += 1
print(n) |
1498 | B | Box Fitting | You are given $n$ rectangles, each of height $1$. Each rectangle's width is a power of $2$ (i. e. it can be represented as $2^x$ for some non-negative integer $x$).
You are also given a two-dimensional box of width $W$. Note that $W$ may or may not be a power of $2$. Moreover, $W$ is at least as large as the width of ... | There can exist multiple optimal packings for a given set of rectangles. However, all of them can always be rearranged to follow a specific pattern, based on the rectangles' sizes. Can you show that it is always possible to replace a set of consecutive small blocks with a single large block? (of same or larger size) We... | [
"binary search",
"bitmasks",
"data structures",
"greedy"
] | 1,300 | #include <array>
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
#define PW 20
array<int, PW> arr;
int n, w;
bool valid(int height) {
for (int pw = 0; pw < PW; pw++) {
long long units_i_have = 1ll * height * (w / (1 << pw));
if (units_i_have < arr[pw]) return false;
... |
1498 | C | Planar Reflections | Gaurang has grown up in a mystical universe. He is faced by $n$ consecutive 2D planes. He shoots a particle of decay age $k$ at the planes.
A particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age $k-1$. If a particle... | We can use dynamic programming to store the state of the simulation at a given time. Therefore, we can simulate the entire situation by reusing the dp states. I will describe the most intuitive solution. Naturally, looking at the constraints as well as at the output that is required, we can store a 3-state dp: dp[n][k]... | [
"brute force",
"data structures",
"dp"
] | 1,600 | mod = int(1e9 + 7)
def iter_solver(N, K):
dp = [[[-1 for _ in range(2)] for __ in range(K + 1)] for ___ in range(N + 1)]
for i in range(1, N + 1):
dp[i][1][0] = dp[i][1][1] = 1
for k in range(2, K + 1):
# forward dir
for n in range(N, 0, -1):
ans = 2
if n <... |
1498 | D | Bananas in a Microwave | You have a malfunctioning microwave in which you want to put some bananas. You have $n$ time-steps before the microwave stops working completely. At each time-step, it displays a new operation.
Let $k$ be the number of bananas in the microwave currently. Initially, $k = 0$. In the $i$-th operation, you are given three... | We have a brute force $\mathcal{O}(N\cdot M^2)$ solution. At every timestep $t$, for each banana $b_i$ that has already been reached previously, apply this timestep's operation $y_t$ times on $b_i$. For all the $y_t$ bananas reachable from $b_i$, update their minimum reachability time if they hadn't been reached previo... | [
"dfs and similar",
"dp",
"graphs",
"implementation"
] | 2,200 | import sys
input = lambda: sys.stdin.readline().rstrip()
DIV = int(1e5)
def ceil(x, y):
return (x + y - 1) // y
T, M = list(map(int, input().split()))
is_seen = [0 for _ in range(M + 1)]
is_seen[0] = 1
answer = [-1 for _ in range(M + 1)]
answer[0] = 0
o = 0
for timestep in range(1, T + 1):
t, x, y = list(... |
1498 | E | Two Houses | \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... | In this problem we have to output two nodes $a$ and $b$ such that there is a path from $a$ to $b$ and $b$ to $a$ and the absolute value of the difference of the indegree $(|k_a - k_b|)$ should be maximum. First of all, let us think of bireachability only i.e how to find two nodes $a$ and $b$ such that they are both rea... | [
"brute force",
"graphs",
"greedy",
"interactive",
"sortings"
] | 2,200 | import sys
input = lambda: sys.stdin.readline().rstrip()
n = int(input())
indegs = list(map(int, input().split()))
pairs = []
for i in range(n):
for j in range(i + 1, n):
if indegs[i] > indegs[j]:
pairs.append((indegs[i] - indegs[j], (i, j)))
else:
pairs.append((indegs[j] ... |
1498 | F | Christmas Game | Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has $n$ nodes (numbered $1$ to $n$, with some node $r$ as its root). There are $a_i$ presents are hanging from the $i$-th node.
Before beginning the game, a special integer $k$ is chosen. The game proceeds as follows:
-... | By the Sprague-Grundy theorem, we know that the current player has a winning strategy if $a_1 \oplus a_2 \oplus \ldots \oplus a_n$ (xorsum of sizes of the existing piles) is non-zero. For a proof, read details on CP-algorithms. Let us classify nodes into odd or even depending on their depth relative to the root. Note t... | [
"bitmasks",
"data structures",
"dfs and similar",
"dp",
"games",
"math",
"trees"
] | 2,500 | n, k = list(map(int, input().split()))
k2 = 2 * k
dp = [[0 for _ in range(k2)] for _ in range(n + 1)]
adj = [[] for _ in range(n + 1)]
for _ in range(n - 1):
_x, _y = list(map(int, input().split()))
adj[_x].append(_y)
adj[_y].append(_x)
a = [0] + list(map(int, input().split()))
win = [0 for _ in range(n... |
1499 | A | Domino on Windowsill | You have a board represented as a grid with $2 \times n$ cells.
The first $k_1$ cells on the first row and first $k_2$ cells on the second row are colored in white. All other cells are colored in black.
You have $w$ white dominoes ($2 \times 1$ tiles, both cells are colored in white) and $b$ black dominoes ($2 \times... | We can prove that if we have $k_1 + k_2$ white cells on the board then we can place any $w$ white dominoes as long as $2w \le k_1 + k_2$. The proof is the following: if $k_1 \ge k_2$ let's place one domino at position $((1, k_1 - 1), (1, k_1))$, otherwise let's place domino at position $((2, k_2 - 1), (2, k_2))$. Then ... | [
"combinatorics",
"constructive algorithms",
"math"
] | 800 | fun main() {
repeat(readLine()!!.toInt()) {
val (n, k1, k2) = readLine()!!.split(' ').map { it.toInt() }
val (w, b) = readLine()!!.split(' ').map { it.toInt() }
if (k1 + k2 >= 2 * w && (n - k1) + (n - k2) >= 2 * b)
println("YES")
else
println("NO")
}
} |
1499 | B | Binary Removals | You are given a string $s$, consisting only of characters '0' or '1'. Let $|s|$ be the length of $s$.
You are asked to choose some integer $k$ ($k > 0$) and find a sequence $a$ of length $k$ such that:
- $1 \le a_1 < a_2 < \dots < a_k \le |s|$;
- $a_{i-1} + 1 < a_i$ for all $i$ from $2$ to $k$.
The characters at pos... | There are several different ways to solve this problem. In my opinion, the two easiest solutions are: notice that, in the sorted string, there is a prefix of zeroes and a suffix of ones. It means that we can iterate on the prefix (from which we remove all ones), and remove all zeroes from the suffix we obtain. If we tr... | [
"brute force",
"dp",
"greedy",
"implementation"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
int i = s.find("11");
int j = s.rfind("00");
cout << (i != -1 && j != -1 && i < j ? "NO" : "YES") << endl;
}
} |
1499 | C | Minimum Grid Path | Let's say you are standing on the $XY$-plane at point $(0, 0)$ and you want to reach point $(n, n)$.
You can move only in two directions:
- to the right, i. e. horizontally and in the direction that increase your $x$ coordinate,
- or up, i. e. vertically and in the direction that increase your $y$ coordinate.
In oth... | Suppose we decided to make exactly $k - 1$ turns or, in other words, our path will consist of exactly $k$ segments. Since we should finish at point $(n, n)$ and vertical and horizontal segments alternates, then it means that $length_1 + length_3 + length_5 + \dots = n$ and $legth_2 + length_4 + length_6 + \dots = n$. F... | [
"brute force",
"data structures",
"greedy",
"math"
] | 1,500 | fun main() {
repeat(readLine()!!.toInt()) {
val n = readLine()!!.toInt()
val c = readLine()!!.split(' ').map { it.toInt() }
val mn = intArrayOf(1e9.toInt(), 1e9.toInt())
val rem = longArrayOf(n.toLong(), n.toLong())
var sum = 0L
var ans = 1e18.toLong()
for (i... |
1499 | D | The Number of Pairs | You are given three positive (greater than zero) integers $c$, $d$ and $x$.
You have to find the number of pairs of positive integers $(a, b)$ such that equality $c \cdot lcm(a, b) - d \cdot gcd(a, b) = x$ holds. Where $lcm(a, b)$ is the least common multiple of $a$ and $b$ and $gcd(a, b)$ is the greatest common divis... | Let's represent $a$ as $Ag$ and $b$ as $Bg$, where $g=gcd(a,b)$ and $gcd(A,B)=1$. By definition $lcm(a,b) = \frac{ab}{g}$, so we can represent $lcm(a,b)$ as $\frac{Ag \cdot Bg}{g} = ABg$. Now we can rewrite the equation from the statement as follows: $c \cdot ABg - d \cdot g = x \implies g(c \cdot AB - d) = x$. Since t... | [
"dp",
"math",
"number theory"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int N = 2e7 + 13;
int main() {
vector<int> mind(N, -1), val(N);
mind[1] = 1;
for (int i = 2; i < N; ++i) if (mind[i] == -1)
for (int j = i; j < N; j += i) if (mind[j] == -1)
mind[j] = i;
for (int i = 2; i < N; ++i) {
int j = i / mind[i];
v... |
1499 | E | Chaotic Merge | You are given two strings $x$ and $y$, both consist only of lowercase Latin letters. Let $|s|$ be the length of string $s$.
Let's call a sequence $a$ a merging sequence if it consists of exactly $|x|$ zeros and exactly $|y|$ ones in some order.
A merge $z$ is produced from a sequence $a$ by the following rules:
- if... | First, let's try to calculate the number of merging sequences just for some fixed pair of strings $x$ and $y$. Imagine we build a merge letter by letter. So far $i$ letters are in the merge already. For the $(i+1)$-th letter we can pick a letter from either string $x$ or string $y$ (put a $0$ or a $1$ into the merging ... | [
"combinatorics",
"dp",
"math",
"strings"
] | 2,400 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = 998244353;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
if (a < 0)
a += MOD;
return a;
}
int main() {
string s, t;
cin >> s >> t;
int n = s.size(), m = t.size();
vector<vector<vec... |
1499 | F | Diameter Cuts | You are given an integer $k$ and an undirected tree, consisting of $n$ vertices.
The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of... | The task is obviously solved by dynamic programming, so our first reaction should be to start looking for meaningful states for it. Obviously, one of the states is the vertex which subtree we are processing. We can choose the root for the tree arbitrarily, let it be vertex $1$. What can be the other helpful state? Cons... | [
"combinatorics",
"dfs and similar",
"dp",
"trees"
] | 2,400 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = 998244353;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
if (a < 0)
a += MOD;
return a;
}
int mul(int a, int b){
return a * 1ll * b % MOD;
}
int k;
vector<vector<int>> g;
vector<vect... |
1499 | G | Graph Coloring | You are given a bipartite graph consisting of $n_1$ vertices in the first part, $n_2$ vertices in the second part, and $m$ edges, numbered from $1$ to $m$. You have to color each edge into one of two colors, red and blue. You have to minimize the following value: $\sum \limits_{v \in V} |r(v) - b(v)|$, where $V$ is the... | Let's split all edges of the graph into several paths and cycles (each edge will belong to exactly one path or cycle). Each path and each cycle will be colored in an alternating way: the first edge will be red, the second - blue, the third - red, and so on (or vice versa). Since the graph is bipartite, each cycle can b... | [
"data structures",
"graphs",
"interactive"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 1000043;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int sub(int x, int y)
{
return add(x, -y);
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
} ... |
1500 | A | Going Home | It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $a$.
Several hours after starting her journey home Nastya remembered about the present. To ent... | Let's prove that if there're at least four different pairs indices with the common sum ($a_{x_1} + a_{y_1} = a_{x_2} + a_{y_2} = \ldots = a_{x_4} + a_{y_4}$), then there necessarily will be two pairs such that all four indices in them are unique. Let's analyze some cases: There're four pairs of the form $(x, y_1), (x, ... | [
"brute force",
"hashing",
"implementation",
"math"
] | 1,800 | null |
1500 | B | Two chandeliers | Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: r... | A formal statement of the problem: there are two sequences of distinct integers, whose are infinitely cycled. You need to find prefix of minimal length which contains exactly $k$ positions $i$ such that $a_i \neq b_i$. Let's notice that we can use binary search. So we need to count number of positions $i$ such that $a_... | [
"binary search",
"brute force",
"chinese remainder theorem",
"math",
"number theory"
] | 2,200 | null |
1500 | C | Matrix Sorting | You are given two tables $A$ and $B$ of size $n \times m$.
We define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this co... | Let's first learn how to solve with O ($n \cdot m^2$). Note that each column can be sorted no more than once. Now, let's note that if we could turn matrix A into matrix B, then B has a sorted column. Idea - we will choose the rows that we will sort from the end. To do this, we can support string equivalence classes. Wh... | [
"bitmasks",
"brute force",
"constructive algorithms",
"greedy",
"two pointers"
] | 2,600 | null |
1500 | D | Tiles for Bathroom | Kostya is extremely busy: he is renovating his house! He needs to hand wallpaper, assemble furniture throw away trash.
Kostya is buying tiles for bathroom today. He is standing in front of a large square stand with tiles in a shop. The stand is a square of $n \times n$ cells, each cell of which contains a small tile w... | Let's denote $ans_{i,\,j}$ as max "good" subsquare side size with left top angle at $(i,\,j)$ cell. It's obvious that every subsquare with side less than $ans_{i,\,j}$ is "good" too. So we need to find $ans_{i,\,j}$ and then print answer for k-size side as $\displaystyle \sum_{x=k}^{n} |\{(i,\,j)\ |\ ans_{i,\,j} = k\}$... | [
"data structures",
"sortings",
"two pointers"
] | 2,900 | null |
1500 | E | Subset Trick | Vanya invented an interesting trick with a set of integers.
Let an illusionist have a set of positive integers $S$. He names a positive integer $x$. Then an audience volunteer must choose some subset (possibly, empty) of $S$ without disclosing it to the illusionist. The volunteer tells the illusionist the size of the ... | Let $S = \{a_1, a_2, \ldots, a_n\}$, where $a_1 < a_2 < \ldots < a_n$. Let's calculate the number of good numbers from $0$ to $sum(X) - 1$. To get the answer to our problem we should subtract this value from $sum(S)$. Let's suppose that $0 \leq x < sum(X)$ is good. It is easy to see that it is equivalent to $a_{n - k +... | [
"binary search",
"data structures"
] | 3,300 | null |
1500 | F | Cupboards Jumps | In the house where Krosh used to live, he had $n$ cupboards standing in a line, the $i$-th cupboard had the height of $h_i$. Krosh moved recently, but he wasn't able to move the cupboards with him. Now he wants to buy $n$ new cupboards so that they look as similar to old ones as possible.
Krosh does not remember the e... | $-$ Note 1 We can change cupboards' heights with differences between following ones: $d_i = h_{i + 1} - h_{i}$. How to get $w$ using $d$? $w_i = \max(\left|{d_i}\right|, \left|{d_{i + 1}}\right|, \left|{d_i + d_{i + 1}}\right|)$ $\quad$ $-$ $O(n C)$ $dp[i][dif]$ - can we choose $i$ differences, with the last equal to $... | [
"dp"
] | 3,500 | null |
1501 | A | Alexey and Train | Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!
Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $0$. Also, let's say that the train will visit $n$ stations numbered from $1$ to $n$ along its w... | The solution of this task is to basically implement what was written in the statement. Let $dep_i$ be the moment of train departure from the station $i$ ($dep_0 = 0$ initially). Then train arrives at the current station $i$ at moment $ar_i = dep_{i - 1} + (a_i - b_{i - 1}) + tm_i$ and departure at moment $dep_i = \max(... | [
"implementation"
] | 800 | null |
1501 | B | Napoleon Cake | This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.
To bake a Napoleon cake, one has to bake $n... | The $i$-th layer is drenched in cream if there is such $j \ge i$ that $j - a_j < i$. Then we can calculate answers for all layers $i$ in reverse order (from $n$ to $1$) and maintain minimum over all values $j - a_j$ as some variable $mn$. As a result, when we move from $i + 1$ to $i$, we update $mn = \min(mn, i - a_i)$... | [
"dp",
"implementation",
"sortings"
] | 900 | null |
1503 | A | Balance the Bits | A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.
You are given a binary string $s$ of length $n$. Construct two balanced bracket sequen... | Any balanced bracket sequence must begin with '(' and end with ')'. Therefore, $a$ and $b$ must agree in the first and last positions, so we require $s_1=s_n=1$ or a solution doesn't exist. The total number of open brackets in $a$ and $b$ must be $n$, which is even. Each $1$ bit in $s$ creates an even number of open br... | [
"constructive algorithms",
"greedy"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
string s;
cin >> n >> s;
int cnt = 0;
for(int i = 0; i < n; i++) {
cnt += (s[i] == '1');
}
if(cnt % 2 == 1 || s[0] == '0' || s.back() == '0') {
cout << "NO\n";
return;
}
string a, b;
i... |
1503 | B | 3-Coloring | \textbf{This is an interactive problem.}
Alice and Bob are playing a game. There is $n\times n$ grid, initially empty. We refer to the cell in row $i$ and column $j$ by $(i, j)$ for $1\le i, j\le n$. There is an infinite supply of tokens that come in $3$ colors labelled $1$, $2$, and $3$.
The game proceeds with turns... | Imagine the grid is colored like a checkerboard with black and white squares. Then Bob's strategy is to put tokens $1$ on white squares and tokens $2$ on black squares as long as he is able. If he is unable, this means all squares of one color are filled, and he can start placing tokens $3$ without making an invalid co... | [
"constructive algorithms",
"games",
"interactive"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<pair<int, int>> ve[2];
#define BLACK 0
#define WHITE 1
// color the cells like a checkerboard
// ve[COLOR] = {list of unfilled cells of that color}
... |
1503 | C | Travelling Salesman Problem | There are $n$ cities numbered from $1$ to $n$, and city $i$ has beauty $a_i$.
A salesman wants to start at city $1$, visit every city exactly once, and return to city $1$.
For all $i\ne j$, a flight from city $i$ to city $j$ costs $\max(c_i,a_j-a_i)$ dollars, where $c_i$ is the price floor enforced by city $i$. Note ... | Let's reindex the cities so they are in increasing order of beauty. Note that it doesn't matter which city we call the start: the trip will be a cycle visiting every city exactly once. Let's rewrite the cost of a flight $i\to j$ as $\max(c_i, a_j-a_i)=c_i+\max(0, a_j-a_i-c_i).$ Since we always need to leave each city e... | [
"binary search",
"data structures",
"dp",
"greedy",
"shortest paths",
"sortings",
"two pointers"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<pair<long long, long long>> ve;
long long ans = 0;
for(int i = 0; i < n; i++) {
long long a, c;
cin >> a >> c;
ve.push_back({a, c});
... |
1503 | D | Flip the Cards | There is a deck of $n$ cards. The $i$-th card has a number $a_i$ on the front and a number $b_i$ on the back. Every integer between $1$ and $2n$ appears exactly once on the cards.
A deck is called sorted if the front values are in \textbf{increasing} order and the back values are in \textbf{decreasing} order. That is,... | Suppose there is a sorted deck where the $i$-th card has $c_i$ on the front and $d_i$ on the back. That is, it looks like this: $c_1< c_2< \cdots< c_n\\ d_1> d_2> \cdots> d_n$ The values $1,\ldots, n$ must appear in some prefix of $c_i$ and some suffix of $d_i$. That is, they must all appear on distinct cards. So, if t... | [
"2-sat",
"constructive algorithms",
"data structures",
"greedy",
"sortings",
"two pointers"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> ve(n + 1), c(n + 1), suffmax(n + 2), seq0, seq1;
bool flag = true;
for(int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
int cost = 0;
if(a > b) {
cost = 1;
... |
1503 | E | 2-Coloring | There is a grid with $n$ rows and $m$ columns. Every cell of the grid should be colored either blue or yellow.
A coloring of the grid is called stupid if every row has exactly one segment of blue cells and every column has exactly one segment of yellow cells.
In other words, every row must have at least one blue cell... | Before counting, we should understand the structure of a stupid coloring. First, both of the following cannot hold: There exists a path of yellow cells from column $1$ to column $m$. There exists a path of blue cells from row $1$ to row $n$. In fact, if two such paths existed, they must have a cell in common, and it wo... | [
"combinatorics",
"dp",
"math"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
const int M = 998244353;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
if(n < m) swap(n, m);
vector<vector<long long>> choose(n + m, vector<long long>(n));
for(int i = 0; i < n + m; i++) {
for(i... |
1503 | F | Balance the Cards | A balanced bracket sequence is defined as an integer sequence that can be built with the following rules:
- The empty sequence is balanced.
- If $[a_1,\ldots,a_n]$ and $[b_1,\ldots, b_m]$ are balanced, then their concatenation $[a_1,\ldots,a_n,b_1,\ldots,b_m]$ is balanced.
- If $x$ is a positive integer and $[a_1,\ldo... | Suppose we have a deck of cards where the front and back are both balanced bracket sequences. Let's line the cards up horizontally and draw them as points. For each pair of matching brackets on the front and back, we will connect them with an edge. For matched brackets on the front, we add an edge as a semicircle lying... | [
"constructive algorithms",
"data structures",
"divide and conquer",
"geometry",
"graphs",
"implementation"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
struct curve {
list<int> a, b;
curve() {}
curve(int x) {
a.push_back(x);
b.push_back(x);
}
curve& operator+=(curve &o) {
a.splice(a.end(), o.a);
o.b.splice(o.b.end(), b);
b.swap(o.b);
return *this;
... |
1504 | A | Déjà Vu | A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.
There is a string $s$. You \textbf{must} insert \textbf{exactly one} character 'a' somewhere... | If $s$ is the character 'a' repeated some number of times, there is no solution. Otherwise, I claim either 'a' + $s$ or $s$ + 'a' is a solution (or both). Let's prove it. Assume for contradiction that 'a' + $s$ and $s$ + 'a' are both palindromes. Then the first and last characters of $s$ are 'a'. Then the second and se... | [
"constructive algorithms",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
bool palindrome(const string &s) {
int n = s.length();
for(int i = 0; i < n; i++) {
if(s[i] != s[n - i - 1]) return false;
}
return true;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int te;
cin >> te;
while(te--)... |
1504 | B | Flip the Bits | There is a binary string $a$ of length $n$. In one operation, you can select any prefix of $a$ with an \textbf{equal} number of $0$ and $1$ symbols. Then all symbols in the prefix are inverted: each $0$ becomes $1$ and each $1$ becomes $0$.
For example, suppose $a=0111010000$.
- In the first operation, we can select ... | Let's call a prefix legal if it contains an equal number of $0$ and $1$ symbols. The key observation is that applying operations never changes which prefixes are legal. In fact, suppose we apply an operation to a prefix of length $i$, and consider a prefix of length $j$. We want to show that if $j$ was legal before, it... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
string a, b;
cin >> n >> a >> b;
a.push_back('0');
b.push_back('0');
int cnt = 0;
for(int i = 0; i < n; i++) {
cnt += (a[i] == '1') - (a[i] == '0');
if((a[i] == b[i]) != (a[i + 1] == b[i + 1]) && cnt != 0... |
1506 | A | Strange Table | Polycarp found a rectangular table consisting of $n$ rows and $m$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm \textbf{"by columns"}:
- cells are numbered starting from one;
- cells are numbered from left to right by columns, and inside each column from top to bot... | To find the cell number in a different numbering, you can find $(r, c)$ coordinates of the cell with the number $x$ in the numbering "by columns": $r = ((x-1) \mod r) + 1$, where $a \mod b$ is the remainder of dividing the number $a$ by the number $b$; $c = \left\lceil \frac{x}{n} \right\rceil$, where $\left\lceil \fra... | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
ll n, m, x;
cin >> n >> m >> x;
x--;
ll col = x / n;
ll row = x % n;
cout << row * m + col + 1 << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int n;
... |
1506 | B | Partial Replacement | You are given a number $k$ and a string $s$ of length $n$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met:
- The first character '*' in the original string should be replaced with 'x';
- The last character '*' in the... | To solve this problem, you can use the dynamic programming method or the greedy algorithm. Let's describe the greedy solution. Until we get to the last character '*' we will do the following: being in position $i$, find the maximum $j$, such that $s_j=$'*' and $j-i \le k$, and move to position $j$. Since we make the lo... | [
"greedy",
"implementation"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int res = 1;
int i = s.find_first_of('*');
while (true) {
int j = min(n - 1, i + k);
for (; i < j && s[j] == '.'; j--) {}
if (i == j) {
break;
}
res++;
i = j;
}
cout... |
1506 | C | Double-ended Strings | You are given the strings $a$ and $b$, consisting of lowercase Latin letters. You can do any number of the following operations in any order:
- if $|a| > 0$ (the length of the string $a$ is greater than zero), delete the first character of the string $a$, that is, replace $a$ with $a_2 a_3 \ldots a_n$;
- if $|a| > 0$,... | Regarding to the small constraints, in this problem you could iterate over how many characters were removed by each type of operation. If $l$ characters at the beginning and $x$ characters at the end are removed from the string $s$, then the substring $s[l+1, n-x]$ remains, where $n$ - is the length of the string $s$. ... | [
"brute force",
"implementation",
"strings"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
string a, b;
cin >> a >> b;
int n = a.size(), m = b.size();
int ans = 0;
for (int len = 1; len <= min(n, m); len++) {
for (int i = 0; i + len <= n; i++) {
for (int j = 0; j + len <= m; j++) {
... |
1506 | D | Epic Transformation | You are given an array $a$ of length $n$ consisting of integers. You can apply the following operation, consisting of several steps, on the array $a$ \textbf{zero} or more times:
- you select two \textbf{different} numbers in the array $a_i$ and $a_j$;
- you remove $i$-th and $j$-th elements from the array.
For examp... | Let's replace each character with the number of its occurrences in the string. Then each operation - take two non-zero numbers and subtract one from them. In the end, we will have only one non-zero number left, and we want to minimize it. We can say that we want to minimize the maximum number after applying all the ope... | [
"constructive algorithms",
"data structures",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
priority_queue<pair<int, int>> q;
int n;
cin >> n;
map<int, int> v;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v[x]++;
}
for (auto [x, y] : v) {
q.push({y, x});
}
... |
1506 | E | Restoring the Permutation | A permutation is a sequence of $n$ integers from $1$ to $n$, in which all numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ are permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ are not.
Polycarp was presented with a permutation $p$ of numbers from $1$ to $n$. However, when Polycarp came h... | If we want to build a minimal lexicographic permutation, we need to build it from left to right by adding the smallest possible element. If $q[i] = q[i-1]$, so the new number must not be greater than all the previous ones, and if $q[i] > q[i-1]$, then necessarily $a[i] = q[i]$. $q[i] < q[i-1]$ does not happen, since $q... | [
"constructive algorithms",
"implementation"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
void placeLeft(vector<int> &q, bool minimize) {
set<int> left;
for (int i = 1; i <= (int) q.size(); i++) {
left.insert(i);
}
for (int i : q) {
if (i != -1) {
left.erase(i);
}
}
int lastPlaced = -1;
for (int &i : q) {
if (i == -1) {
... |
1506 | F | Triangular Paths | Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $k$-th layer of the triangle contains $k$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $(r, c)$ ($1 \le c \le r... | Since all edges are directed downward, there is only one way to visit all $n$ points is to visit the points in ascending order of the layer number. Let's sort the points in order of increasing layer. It is easy to see that the cost of the entire path is equal to the sum of the cost of paths between adjacent points. Let... | [
"constructive algorithms",
"graphs",
"math",
"shortest paths",
"sortings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
bool isLeftArrow(int r, int c) {
return (r + c) % 2 == 0;
}
bool isRightArrow(int r, int c) {
return (r + c) % 2 == 1;
}
int calcDist(int r1, int c1, int r2, int c2) {
if (r1 - c1 == r2 - c2) {
return isRightArrow(r1, c1) ? 0 : r2 - r1;
}
r2 -= r1 - 1;
c2... |
1506 | G | Maximize the Remaining String | You are given a string $s$, consisting of lowercase Latin letters. While there is at least one character in the string $s$ that is \textbf{repeated at least twice}, you perform the following operation:
- you choose the index $i$ ($1 \le i \le |s|$) such that the character at position $i$ occurs \textbf{at least two} t... | How can you check if you can perform such a sequence of operations on the string $s$ to get the string $t$? Note that each time we delete an arbitrary character that is repeated at least two times, so $t$ must be a subsequence of the string $s$ and have the same character set as the string $s$. We will consequently bui... | [
"brute force",
"data structures",
"dp",
"greedy",
"strings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int distinct(string s) {
sort(s.begin(), s.end());
return unique(s.begin(), s.end()) - s.begin();
}
string filter(const string &s, char c) {
string t;
bool foundFirst = false;
for (char a : s) {
if (a != c && foundFirst) {
t += a;
} else if (a == c... |
1508 | A | Binary Literature | A bitstring is a string that contains only the characters 0 and 1.
Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length $2n$. A valid novel for the cont... | First solution Let's focus on two bitstrings $s$ and $t$. How can we get a short string that has them both as subsequences? Well, suppose both strings have a common subsequence of length $L$. Then we can include this subsequence as part of our string. Then we just place the remaining characters of both sequences in the... | [
"constructive algorithms",
"greedy",
"implementation",
"strings",
"two pointers"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
string mix(string s, string t, char c) {
int n = s.size()/2;
vector<int> v1 = {-1}, v2 = {-1};
for(int i = 0; i < 2 * n; i++) {
if(s[i] == c)
v1.push_back(i);
if(t[i] == c)
v2.push_back(i);
}
string ans;
for(... |
1508 | B | Almost Sorted | Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations.
A permutation $a_1, a_2, \dots, a_n$ of $1, 2, \dots, n$ is said to be almost sorted if the condition $a_{i + 1} \ge a_i - ... | First solution. Let's first analyze the general structure of an almost sorted permutation. We know that when the sequence decreases, it must decrease by exactly $1$. Thus, every decreasing subarray covers some consecutive range of values. Let's split the permutation into decreasing subarrays, each of them as large as p... | [
"binary search",
"combinatorics",
"constructive algorithms",
"implementation"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
ll k;
cin >> n >> k;
if(n < 62 && k > 1LL << (n - 1)) {
cout << "-1\n";
return;
}
string s;
for(int i = 0; i < n; i++)
s += '0';
k--;
for(ll b = 0; b < min(60LL, (l... |
1508 | C | Complete the MST | As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows.
You are given an undirected complete graph with $n$ nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign a... | Call $x$ the XOR sum of the weights of all pre-assigned edges. Lemma. All but one unassigned edges are assigned with $0$, while the remaining unassigned edge is assigned with $x$. Proof. Consider any assignment of unassigned edges. There are two cases on the minimum spanning tree: The MST does not use all unassigned ed... | [
"bitmasks",
"brute force",
"data structures",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int n, m, u, v, w, lef;
long long rem, ans = 0;
set<int> ava;
vector<int> adj[N];
vector<array<int, 3>> ed;
struct dsu {
int par[N];
void init() {
fill(par + 1, par + n + 1, -1);
}
int trace(int u) {
return par... |
1508 | D | Swap Pass | Based on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem!
You are given $n$ points on the plane, no three of which are collinear. The $i$-th point initially has a label $a_i$, in such a way that the labels $a_1, a_2, \dots, a_n$ form a permutation of $1, 2, ... | As it turns out, it is always possible to find the required sequence, no matter the position of the points in the plane and the initial permutation. It turns out that it's pretty hard to analyze even particular positions of the points, and it will be more convenient to start by analyzing particular permutations instead... | [
"constructive algorithms",
"geometry",
"sortings"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct point {
ll x, y;
point(ll _x = 0, ll _y = 0) : x(_x), y(_y) {}
point operator- (const point &o) const { return point(x - o.x, y - o.y); }
int half() { return y < 0 || (y == 0 && x < 0); }
};
ll cross(point p, point q) {
r... |
1508 | E | Tree Calendar | Yuu Koito and Touko Nanami are newlyweds! On the wedding day, Yuu gifted Touko a directed tree with $n$ nodes and rooted at $1$, and a labeling $a$ which is some DFS order of the tree. Every edge in this tree is directed away from the root.
After calling dfs(1) the following algorithm returns $a$ as a DFS order of a t... | From the structure, we see that until the end, the process is divided into $n$ phases, where the $i$-th involves phase pushing value $i$ from the root to the smallest-labeled leaf. Also in the following tutorial, I will use post-order and exit order, as well as pre-order and DFS order interchangeably. Lemma 1. After fi... | [
"brute force",
"constructive algorithms",
"data structures",
"dfs and similar",
"sortings",
"trees"
] | 3,100 | null |
1508 | F | Optimal Encoding | Touko's favorite sequence of numbers is a permutation $a_1, a_2, \dots, a_n$ of $1, 2, \dots, n$, and she wants some collection of permutations that are similar to her favorite permutation.
She has a collection of $q$ intervals of the form $[l_i, r_i]$ with $1 \le l_i \le r_i \le n$. To create permutations that are si... | We will first solve the problem for $q$-similar permutations only. Let's transform each of the $q$ ranges into edges on a DAG we call $G$: for all ranges $[l_i, r_i]$, for all pairs of indices $l \le x, y \le r$ such that $a_x < a_y$, we add an edge from $x$ to $y$. We can easily see a permutation is $q$-similar iff it... | [
"brute force",
"data structures"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
using namespace chrono;
const int N = 25005, Q = 100005, D = 80;
int n, q, a[N], l[Q], r[Q], pos[N], ans[Q];
set<int> se;
vector<pair<int, int>> edges;
vector<int> in, out;
vector<pair<int, int>> l_edge[N], r_edge[N];
vector<array<int, 3>> eve[N];
vector<pair<int, int>>... |
1509 | A | Average Height | Sayaka Saeki is a member of the student council, which has $n$ other members (excluding Sayaka). The $i$-th member has a height of $a_i$ millimeters.
It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, ... | For two consecutive members to be non-photogenic, $a_u$ and $a_v$ must have different parity. Therefore, to maximize the number of photogenic pairs, or to minimize the number of non-photogenic pairs, we will order the members so that all members with even height are in front and all members with odd height are at the b... | [
"constructive algorithms"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t, n;
cin >> t;
while (t--) {
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
partition(a.begin(), a.end()... |
1509 | B | TMT Document | The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.
However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to fig... | There are many slightly different solutions, all based on some sort of greedy idea. Write $n = 3k$ for convenience. Obviously, the string must have $k$ characters M and $2k$ characters T for the partition to be possible, so we can just discard all other cases. Now, let's consider the first M character in the string. Th... | [
"greedy"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
bool solve() {
int n;
cin >> n;
string s;
cin >> s;
vector<int> t, m;
for(int i = 0; i < n; i++) {
if(s[i] == 'T')
t.push_back(i);
else
m.push_back(i);
}
if(t.size() != 2 * m.size())
return fa... |
1509 | C | The Sports Festival | The student council is preparing for the relay race at the sports festival.
The council consists of $n$ members. They will run one after the other in the race, the speed of member $i$ is $s_i$. The discrepancy $d_i$ of the $i$-th stage is the difference between the maximum and the minimum running speed among the first... | Assume that the array of speeds is sorted, i.e. $s_1 \le s_2 \le \dots \le s_n$. The key observation is that the last running can be assumed to be either $s_1$ or $s_n$. This is because if $s_1$ and $s_n$ are both in the prefix of length $i$, then clearly $d_i = s_n - s_1$, which is the maximum possible value of any di... | [
"dp",
"greedy"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAX = 2e3 + 5;
ll mem[MAX][MAX], a[MAX];
ll dp(int l, int r) {
if(mem[l][r] != -1)
return mem[l][r];
if(l == r)
return 0;
return mem[l][r] = a[r] - a[l] + min(dp(l + 1, r), dp(l, r - 1));
}
int main() {
i... |
1511 | A | Review Site | You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.
However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.
$n$ re... | Notice that the answer depends only on the number of the reviewers of the third type who upvote the movie. Optimally we would want every single reviewer of the third type to upvote. We can achieve it with the following construction: send all reviewers of the first type to the first server, all reviewers of the second t... | [
"greedy"
] | 800 | fun main() {
repeat(readLine()!!.toInt()) {
readLine()!!.toInt()
println(readLine()!!.split(' ').count { it != "2" })
}
} |
1511 | B | GCD Length | You are given three integers $a$, $b$ and $c$.
Find two positive integers $x$ and $y$ ($x > 0$, $y > 0$) such that:
- the decimal representation of $x$ without leading zeroes consists of $a$ digits;
- the decimal representation of $y$ without leading zeroes consists of $b$ digits;
- the decimal representation of $gcd... | The easiest way to force some gcd to be of some fixed length is to use the divisibility rules for $2$, $5$ or $10$: if the number produced by the last $y$ digits $x$ is divisible by $2^y$, then $x$ is also divisible by $2^y$ (same goes for $5^y$ and $10^y$). One of the possible constructions is the following: let $x=1\... | [
"constructive algorithms",
"math",
"number theory"
] | 1,100 | for t in range(int(input())):
a, b, c = map(int, input().split())
print("1" + "0" * (a - 1), "1" * (b - c + 1) + "0" * (c - 1)) |
1511 | C | Yet Another Card Deck | You have a card deck of $n$ cards, numbered from top to bottom, i. e. the top card has index $1$ and bottom card — index $n$. Each card has its color: the $i$-th card has color $a_i$.
You should process $q$ queries. The $j$-th query is described by integer $t_j$. For each query you should:
- find the highest card in ... | Let's look at one fixed color. When we search a card of such color, we take the card with minimum index and after we place it on the top of the deck it remains the one with minimum index. It means that for each color we take and move the same card - one card for each color. In other words, we need to keep track of only... | [
"brute force",
"data structures",
"implementation",
"trees"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, q;
scanf("%d%d", &n, &q);
vector<int> a(n);
for (int& x : a) scanf("%d", &x);
while (q--) {
int x;
scanf("%d", &x);
int p = find(a.begin(), a.end(), x) - a.begin();
printf("%d ", p + 1);
rotate(a.begin(), a.begin() + p, a.... |
1511 | D | Min Cost String | Let's define the cost of a string $s$ as the number of index pairs $i$ and $j$ ($1 \le i < j < |s|$) such that $s_i = s_j$ and $s_{i+1} = s_{j+1}$.
You are given two positive integers $n$ and $k$. Among all strings with length $n$ that contain only the first $k$ characters of the Latin alphabet, find a string with min... | Consider all possible strings of length $2$ on the alphabet of size $k$ (there are $k^2$ of them). Let $cnt_i$ be the number of occurrences of the $i$-th of them in the string $s$. The cost of the string $s$ by definition is $\sum \limits_{i} \frac{cnt_i(cnt_i - 1)}{2}$. Now, let's suppose there are two strings $i$ and... | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"strings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int n, k;
int cur[26];
vector<int> path;
void dfs(int v) {
while (cur[v] < k) {
int u = cur[v]++;
dfs(u);
path.push_back(u);
}
}
int main() {
scanf("%d%d", &n, &k);
dfs(0);
printf("a");
for (int i = 0; i < n - 1; ++i)
printf("%c", path[i % pa... |
1511 | E | Colorings and Dominoes | You have a large rectangular board which is divided into $n \times m$ cells (the board has $n$ rows and $m$ columns). Each cell is either white or black.
You paint each white cell either red or blue. Obviously, the number of different ways to paint them is $2^w$, where $w$ is the number of white cells.
After painting... | There are different solutions to this problem involving combinatorics and/or dynamic programming, but, in my opinion, it's a bit easier to look at the problem from the perspective of probability theory. Let's suppose a coloring is already chosen. Then it can be covered with dominoes greedily: red and blue cells are ind... | [
"combinatorics",
"dp",
"greedy",
"math"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int N = 300043;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD)
x -= MOD;
while(x < 0)
x += MOD;
return x;
}
int sub(int x, int y)
{
return add(x, MOD - y);
}
int mul(int x, i... |
1511 | F | Chainword | A chainword is a special type of crossword. As most of the crosswords do, it has cells that you put the letters in and some sort of hints to what these letters should be.
The letter cells in a chainword are put in a single row. We will consider chainwords of length $m$ in this task.
A hint to a chainword is a sequenc... | Let's use a trie to store the given words. Now let's imagine a procedure that checks if some string of length $m$ can be represented as a concatenation of some of these words. If the words were prefix-independent - no word was a prefix of another word, that task would be solvable with a greedy algorithm. We could itera... | [
"brute force",
"data structures",
"dp",
"matrices",
"string suffix structures",
"strings"
] | 2,700 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = 998244353;
const int K = 161;
const int AL = 26;
struct node{
int nxt[AL];
bool term;
node(){
memset(nxt, -1, sizeof(nxt));
term = false;
};
int& operator [](const int x){
return nxt[x];
}
}... |
1511 | G | Chips on a Board | Alice and Bob have a rectangular board consisting of $n$ rows and $m$ columns. \textbf{Each row contains exactly one chip.}
Alice and Bob play the following game. They choose two integers $l$ and $r$ such that $1 \le l \le r \le m$ and cut the board in such a way that only the part of it between column $l$ and column ... | The model solution is $O(N \sqrt{N \log N})$, where $N = \max(n, m, q)$, but it seems that there are faster ones. I'll explain the model solution nevertheless. It's easy to see (using simple Nim theory) that the answer for a query $i$ is B iff the xor of $c_j - L_i$ for all chips such that $L_i \le c_j \le R_i$ is equa... | [
"bitmasks",
"brute force",
"data structures",
"dp",
"games",
"two pointers"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
const int N = 200043;
const int K = 10;
const int Z = 1 << K;
int rem[Z];
int t[N];
int get(int r)
{
int result = 0;
for (; r >= 0; r = (r & (r + 1)) - 1)
result ^= t[r];
return result;
}
void change(int i, int delta)
{
for (; i < N; i = (i | (i... |
1512 | A | Spy Detected! | You are given an array $a$ consisting of $n$ ($n \ge 3$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $[4, 11, 4, 4]$ all numbers except one are equal to $4$).
Print the index of the element that does not equal others. The numbers in the array ar... | To find a number that differs from the rest of the numbers in the array, you need to iterate through the array, maintaining two pairs of numbers $(x_1, c_1)$ and $(x_2, c_2)$, where $x_i$ is a number from the array, $c_i$ is how many times the number $x_i$ occurs in the array. Then, to get an answer, you need to find t... | [
"brute force",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve() {
int n;
cin >> n;
vector<int> v(n);
for (int &e : v) {
cin >> e;
}
vector<int> a = v;
sort(a.begin(), a.end());
for (int i = 0; i < n; i++) {
if (v[i] != a[1]) {
cout << i + 1... |
1512 | B | Almost Rectangle | There is a square field of size $n \times n$ in which two cells are marked. These cells can be in the same row or column.
You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.
For example, if $n=4$ and a rectangular field looks like this (there are aste... | f two asterisks are in the same row, then it is enough to select any other row and place two asterisks in the same columns in it. If two asterisks are in the same column, then you can do the same. If none of the above conditions are met and the asterisks are at positions $(x1, y1)$, $(x2, y2)$, then you can place two m... | [
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n;
cin >> n;
vector<string> f(n);
vector<pair<int,int>> p;
forn(i, n) {
cin >> f[i];
forn(j... |
1512 | C | A-B Palindrome | You are given a string $s$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and has \textbf{exactly} $a$ characters '0' and \textbf{exactly} $b$ characters '1'. Note that each of the characters '?' is ... | First, let's find such positions $i$ ($1 \le i \le n$) such that $s[i]\ne$'?' (symbols in symmetric positions are uniquely determined): If $s[n-i+1]=$'?', then $s[n-i+1] = s[i]$; If $s[i] \ne s[n-i+1]$, then at the end we will not get a palindrome in any way, so the answer is '-1'. Note that after such a replacement, t... | [
"constructive algorithms",
"implementation",
"strings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
void no() {
cout << "-1" << endl;
}
void solve() {
int a, b;
cin >> a >> b;
string s;
cin >> s;
for (int times = 0; times < 2; times++) {
for (int i = 0; i < (int) s.size(); i++) {
int j = (int) s.size() - i - 1;
if (s[i] != '?') {
if (... |
1512 | D | Corrupted Array | You are given a number $n$ and an array $b_1, b_2, \ldots, b_{n+2}$, obtained according to the following algorithm:
- some array $a_1, a_2, \ldots, a_n$ was guessed;
- array $a$ was written to array $b$, i.e. $b_i = a_i$ ($1 \le i \le n$);
- The $(n+1)$-th element of the array $b$ is the sum of the numbers in the arra... | What is the sum of all the elements in $b$? This is twice the sum of all the elements in $a$ + $x$. Denote by $B$ the sum of all the elements of $b$. Let's iterate over which of the array elements was added as the sum of the elements $a$ (let's denote, for $a$). Then, $x$ = $B-2 \cdot A$. It remains to check that the e... | [
"constructive algorithms",
"data structures",
"greedy"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
void no() {
cout << "-1" << endl;
}
void solve() {
int n;
cin >> n;
vector<int> b(n + 2);
for (int &x : b) {
cin >> x;
}
multiset<int> have(b.begin(), b.end());
long long sum = accumulate(b.begin(), b.end(), 0LL);
for (int x : b) {
have.erase(ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.