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 ⌀ |
|---|---|---|---|---|---|---|---|
1512 | E | Permutation by Sum | A permutation is a sequence of $n$ integers from $1$ to $n$, in which all the 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 given four integers $n$, $l$, $r$ ($1 \le l \le r \le n)$ and $s$ ($1 \le s \le \frac{... | It is easy to show that if we choose $k$ numbers from a permutation of length $n$, then the minimum sum of $k$ numbers is $\frac{k(k+1)}{2}$, the maximum sum is $\frac{k(2n+1-k)}{2}$ and any sum between them is achievable (that is, you can choose exactly $k$ numbers from $n$ so that their sum is equal to the desired on... | [
"brute force",
"greedy",
"math"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n, l, r, s;
cin >> n >> l >> r >> s;
l--; r--;
for (int first = 1; first + (r - l) <= n; first++) {
int sum = 0;
for (int i = l; i <= r; i++) {
sum += first + (i - l);
}
i... |
1512 | F | Education | Polycarp is wondering about buying a new computer, which costs $c$ tugriks. To do this, he wants to get a job as a programmer in a big company.
There are $n$ positions in Polycarp's company, numbered starting from one. An employee in position $i$ earns $a[i]$ tugriks every day. The higher the position number, the more... | Since the array $a$ does not decrease, if we want to get the position $x$ at some point, it is best to get it as early as possible, because if we get it earlier, we will earn no less money. Therefore, the solution looks like this - rise to some position and earn money on it for a laptop. Let's go through the number of ... | [
"brute force",
"dp",
"greedy",
"implementation"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve() {
int n, c;
cin >> n >> c;
vector<int> a(n);
vector<int> b(n - 1);
for (int &e : a) {
cin >> e;
}
for (int &e : b) {
cin >> e;
}
b.push_back(0);
ll ans = 1e18;
ll cur = 0;
... |
1512 | G | Short Task | Let us denote by $d(n)$ the sum of all divisors of the number $n$, i.e. $d(n) = \sum\limits_{k | n} k$.
For example, $d(1) = 1$, $d(4) = 1+2+4=7$, $d(6) = 1+2+3+6=12$.
For a given number $c$, find the minimum $n$ such that $d(n) = c$. | Note that $n \le d(n) \le {10}^7$ (${10}^7$ is the maximum value of $c$ in the problem), so it is enough for every $n=1..{10}^7$ to calculate the value of $d(n)$. To calculate the value of $d(n)$, you can use the sieve of Eratosthenes and get the solution for $\mathcal{O}({10}^7 \log ({10}^7))$. Also, you can use the l... | [
"brute force",
"dp",
"math",
"number theory"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int N = (int) 1e7 + 100;
long long s[N];
int d[N];
int ans[N];
int main() {
fill(d, d + N, -1);
d[1] = 1;
for (int i = 2; i * i < N; i++) {
if (d[i] == -1) {
d[i] = i;
for (int j = i * i; j < N; j += i) {
if (d[j] == -1) {
d[... |
1513 | A | Array and Peaks | A sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.
Given two integers $n$ and $k$, construct a permutation $a$ of numbers from $1$ to $n$ which has \textbf{exactly} $k$ peaks. An index $i$ of an array $a$ of size $n$ is said to be a peak if $1 < i < n$ and $a_i... | There are many ways to solve this problem. The key idea is we try to use the first $k$ largest elements from $n$ to $n-k+1$ to construct the $k$ peaks. So try constructing the array like this: $1, n, 2, n-1, 3, n-2,..., n-k+1, k+1, k+2,..., n-k$. For this answer to be possible $n-k+1 \gt k+1$ which means $2 \cdot k \lt... | [
"constructive algorithms",
"implementation"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int main()
{
int tests;
cin>>tests;
while(tests--)
{
int n,k;
cin>>n>>k;
vector<int> ans(n+1);
int num=n;
for(int i=2;i<n;i+=2)
{
if(k==0)break;
ans[i]=num--;
... |
1513 | B | AND Sequences | A sequence of $n$ non-negative integers ($n \ge 2$) $a_1, a_2, \dots, a_n$ is called good if for all $i$ from $1$ to $n-1$ the following condition holds true: $$a_1 \: \& \: a_2 \: \& \: \dots \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: \dots \: \& \: a_n,$$ where $\&$ denotes the bitwise AND operation.
You are g... | Consider an arbitrary sequence $b_1,b_2,\dots,b_n$. First let us define the arrays $AND\_pref$ and $AND\_suf$ of length $n$ where $AND\_pref_i = b_1 \: \& \: b_2 \: \& \: \dots \: \& \: b_i$ and $AND\_suf_i = b_{i} \: \& \: b_{i+1} \: \& \: \dots \: \& \: b_n$ . According to the definition of good sequence: $AND\_pref_... | [
"bitmasks",
"combinatorics",
"constructive algorithms",
"math"
] | 1,400 |
#include<bits/stdc++.h>
using namespace std;
void solveTestCase()
{
int MOD=1e9+7;
int n;
cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++)cin>>a[i];
int min1=*min_element(a.begin(),a.end());
int cnt=0;
for(int x:a)
{
if(min1==x)cnt++;
if((min1&x)!=min1)
... |
1513 | C | Add One | You are given an integer $n$. You have to apply $m$ operations to it.
In a single operation, you \textbf{must} replace every digit $d$ of the number with the decimal representation of integer $d + 1$. For example, $1912$ becomes $21023$ after applying the operation once.
You have to find the length of $n$ after apply... | We can solve this problem using 1D dp. Let $dp_i$ be defined as the length of the string after applying operation $i$-times to the number $10$. Then, $dp_i =2$, $\forall$ $i$ in $[0,8]$ $dp_i =3$, if $i=9$ (The final number after applying $9$ operations to the number $10$ is $109$.) (The final number after applying $9$... | [
"dp",
"matrices"
] | 1,600 |
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int max_n = 200005, mod = 1000000007;
int dp[max_n];
signed main(){
for(int i=0; i<9; i++)dp[i] = 2;
dp[9] = 3;
for(int i=10; i<max_n; i++){
dp[i] = (dp[i-9] + dp[i-10])%mod;
}
ios_base::sync_with_stdio(false);
... |
1513 | D | GCD and MST | You are given an array $a$ of $n$ ($n \geq 2$) positive integers and an integer $p$. Consider an undirected weighted graph of $n$ vertices numbered from $1$ to $n$ for which the edges between the vertices $i$ and $j$ ($i<j$) are added in the following manner:
- If $gcd(a_i, a_{i+1}, a_{i+2}, \dots, a_{j}) = min(a_i, a... | We will iterate from smallest to largest number like in krushkal's algorithm. By this, we will consider the edges with the smallest weight first. Now, while iterating, we will assume the current value as the gcd we want to get, let's say $g$ and we will go left and then right while going left/right, if $gcd(new\_elemen... | [
"constructive algorithms",
"dsu",
"graphs",
"greedy",
"number theory",
"sortings"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
void solveTestCase()
{
int n,x;
cin>>n>>x;
vector<int> a(n);
for(int i=0;i<n;i++)cin>>a[i];
//tells whether vertices i and i+1 are connected for 0<=i<n-1
vector<bool> isConnected(n);
vector<pair<int,int>> vals;
for(int i=0... |
1513 | E | Cost Equilibrium | An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
- Choose two indices $i$ and $j$ ($1 \leq i,j \leq n$), and an integer $x$ ($1 \leq x \leq a_i$). Let $i$ be the source index and $j$ be the sink index.
- Decrease the $i$... | let $S$ = $\sum_0^{n-1}(a_i)$. The first and foremost condition is that $S\%n=0$, and the final values in the beautiful array will be equal to $x=S/n$. Since a node cannot operate as both, a source and a sink, therefore: Nodes with $values > x$ can only be the source vertices. Nodes with $values < x$ can only be the si... | [
"combinatorics",
"constructive algorithms",
"math",
"sortings"
] | 2,300 | #include "bits/stdc++.h"
#define ll long long
#define MOD 1000000007
ll power(ll x,ll y, ll md=MOD){ll res = 1;x%=md;while(y){if(y&1)res = (res*x)%md;x *= x; if(x>=md) x %= md; y >>= 1;}return res;}
using namespace std;
#define int long long
#define MAX 100005
vector<int> f(MAX);
vector<int> inv(MAX);
void init()... |
1513 | F | Swapping Problem | You are given 2 arrays $a$ and $b$, both of size $n$. You can swap two elements in $b$ at most \textbf{once} (or leave it as it is), and you are required to minimize the value $$\sum_{i}|a_{i}-b_{i}|.$$
Find the minimum possible value of this sum. | Let's form 2 sets $X$ and $Y$. $X$ contains those indices $i$ such that $A_i$ < $B_i$ and $Y$ contains those indices $i$ such that $A_i$ > $B_i$. We call a segment $L_i$, $R_i$ as $L_i = min(A_i, B_i)$ and $R_i = max(A_i, Bi_i)$ Let break this Question into a series of observation: Observation 1: The answer will reduce... | [
"brute force",
"constructive algorithms",
"data structures",
"sortings"
] | 2,500 | // created by mtnshh
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
#define ll long long
#define ld long double
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>=b;i--)
#define pb push_back
#define all(A) A.begin(),A.end()
#define allr(A) A.rbegin(),A.rend()
#define f... |
1514 | A | Perfectly Imperfect Array | Given an array $a$ of length $n$, tell us whether it has a non-empty subsequence such that the product of its elements is \textbf{not} a perfect square.
A sequence $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by deleting some (possibly zero) elements. | If any element is not a perfect square, the answer is yes. Otherwise, the answer is no, because $a^2*b^2*...=(a*b*...)^2$. | [
"math",
"number theory"
] | 800 | "#include <bits/stdc++.h>\nusing namespace std;\n#define MX 10000\nbool sq[MX+5];\nint main()\n{\n\tfor (int i=1;i*i<=MX;i++)\n\tsq[i*i]=1;\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tint n;\n\t\tscanf(\"%d\",&n);\n\t\tbool ok=1;\n\t\twhile (n--)\n\t\t{\n\t\t\tint a;\n\t\t\tscanf(\"%d\",&a);\n\t\t\tok&=sq[a... |
1514 | B | AND 0, Sum Big | Baby Badawy's first words were "AND 0 SUM BIG", so he decided to solve the following problem. Given two integers $n$ and $k$, count the number of arrays of length $n$ such that:
- all its elements are integers between $0$ and $2^k-1$ (inclusive);
- the bitwise AND of all its elements is $0$;
- the sum of its elements ... | Let's start with an array where every single bit in every single element is $1$. It clearly doesn't have bitwise-and equal to $0$, so for each bit, we need to turn it off (make it $0$) in at least one of the elements. However, we can't turn it off in more than one element, since the sum would then decrease for no reaso... | [
"bitmasks",
"combinatorics",
"math"
] | 1,200 | "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n,k;\nconst int MOD=1e9+7;\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile(t--)\n\t{\n\t\tscanf(\"%d %d\",&n,&k);\n\t\tlong long ans=1;\n\t\tfor(int i=0;i<k;i++) ans=(ans*n)%MOD;\n\t\tprintf(\"%lld\\n\",ans);\n\t}\n}" |
1514 | C | Product 1 Modulo N | Now you get Baby Ehab's first words: "Given an integer $n$, find the longest subsequence of $[1,2, \ldots, n-1]$ whose product is $1$ modulo $n$." Please solve the problem.
A sequence $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by deleting some (possibly all) elements. The product of an empty ... | So first observe that the subsequence can't contain any element that isn't coprime with $n$. Why? Because then its product won't be coprime with $n$, so when you take it modulo $n$, it can't be $1$. In mathier words, $gcd(prod \space mod \space n,n)=gcd(prod,n) \neq 1$. Now, let's take all elements less than $n$ and co... | [
"greedy",
"number theory"
] | 1,600 | "#include <bits/stdc++.h>\nusing namespace std;\nbool ok[100005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tlong long prod=1;\n\tfor (int i=1;i<n;i++)\n\t{\n\t\tif (__gcd(n,i)==1)\n\t\t{\n\t\t\tok[i]=1;\n\t\t\tprod=(prod*i)%n;\n\t\t}\n\t}\n\tif (prod!=1)\n\tok[prod]=0;\n\tprintf(\"%d\\n\",count(ok+1,ok+n,1));\n\... |
1514 | D | Cut and Stick | Baby Ehab has a piece of Cut and Stick with an array $a$ of length $n$ written on it. He plans to grab a pair of scissors and do the following to it:
- pick a range $(l, r)$ and cut out every element $a_l$, $a_{l + 1}$, ..., $a_r$ in this range;
- stick some of the elements together in the same order they were in the ... | Suppose the query-interval has length $m$. Let's call an element super-frequent if it occurs more than $\lceil\frac{m}{2}\rceil$ times in it, with frequency $f$. If there's no super-frequent element, then we can just put all the elements in $1$ subsequence. Otherwise, we need the partitioning. Let's call the rest of th... | [
"binary search",
"data structures",
"greedy",
"implementation",
"sortings"
] | 2,000 | "#include <bits/stdc++.h>\nusing namespace std;\nint a[300005],tree[1200005];\nvector<int> v[300005];\nint cnt(int l,int r,int c)\n{\n\treturn upper_bound(v[c].begin(),v[c].end(),r)-lower_bound(v[c].begin(),v[c].end(),l);\n}\nvoid build(int node,int st,int en)\n{\n\tif (st==en)\n\ttree[node]=a[st];\n\telse\n\t{\n\t\tin... |
1514 | E | Baby Ehab's Hyper Apartment | This is an interactive problem.
Baby Ehab loves crawling around his apartment. It has $n$ rooms numbered from $0$ to $n-1$. For every pair of rooms, $a$ and $b$, there's either a direct passage from room $a$ to room $b$, or from room $b$ to room $a$, but never both.
Baby Ehab wants to go play with Baby Badawy. He wan... | Throughout the editorial, I'll call the first type of queries OneEdge and the second type ManyEdges. The basic idea behind this problem is to find a few edges such that every path that could be traversed in your graph could be traversed using only these edges. With that motivation in mind, let's get started. The first ... | [
"binary search",
"graphs",
"interactive",
"sortings",
"two pointers"
] | 2,700 | "#include <bits/stdc++.h>\nusing namespace std;\nbool ManyEdges(int x,vector<int> s)\n{\n\tprintf(\"2 %d %d\",x,s.size());\n\tfor (int i:s)\n\tprintf(\" %d\",i);\n\tprintf(\"\\n\");\n\tfflush(stdout);\n\tint ret;\n\tscanf(\"%d\",&ret);\n\tif (ret==-1)\n\texit(0);\n\treturn ret;\n}\nbool OneEdge(int a,int b)\n{\n\tprint... |
1515 | A | Phoenix and Gold | Phoenix has collected $n$ pieces of gold, and he wants to weigh them together so he can feel rich. The $i$-th piece of gold has weight $w_i$. All weights are \textbf{distinct}. He will put his $n$ pieces of gold on a weight scale, one piece at a time.
The scale has an unusual defect: if the total weight on it is \text... | Note that if the sum of all the weights is $x$, the scale will always explode and the answer will be NO. Otherwise, we claim there is always an answer. Basically, at each point, we choose an arbitrary gold piece to add to the scale so that it doesn't explode. There is always a valid gold piece to add because the weight... | [
"constructive algorithms",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve(){
int n,x;
int w[101];
cin>>n>>x;
int sum=0;
for (int i=0;i<n;i++){
cin>>w[i];
sum+=w[i];
}
//if the sum is x, we cannot avoid the explosion
if (sum==x){
cout<<"NO"<<endl;
return;
}
cout<<"YES"<<endl;
//otherwise, the answe... |
1515 | B | Phoenix and Puzzle | Phoenix is playing with a new puzzle, which consists of $n$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.
\begin{center}
{\small A puzzle piece}
\end{center}
The goal of the puzzle is to create a \textbf{square} using the $n$ pieces. He is allowed to rotate and move the piec... | If $n$ can be written as $2x$ or $4x$, where $x$ is a square number, then the answer is YES. Otherwise it is NO. To visualize this construction, we start by first building a smaller square using exactly $2$ or $4$ pieces (the drawings are in the sample test explanation). We can just use $x$ of those smaller squares to ... | [
"brute force",
"geometry",
"math",
"number theory"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
bool isSquare(int x){
int y=sqrt(x);
return y*y==x;
}
void solve(){
int n;
cin>>n;
if (n%2==0 && isSquare(n/2))
cout<<"YES"<<endl;
else if (n%4==0 && isSquare(n/4))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
int main(){
int t; cin>>t;
while... |
1515 | C | Phoenix and Towers | Phoenix has $n$ blocks of height $h_1, h_2, \dots, h_n$, and all $h_i$ don't exceed some value $x$. He plans to stack all $n$ blocks into $m$ separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly mo... | Greedily adding blocks to the current shortest tower will always give a valid solution. Let's prove it with contradiction. If the towers weren't beautiful, then some two towers would have a height difference of more than $x$. Since a single block cannot exceed a height of $x$, the difference would be more than one bloc... | [
"constructive algorithms",
"data structures",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int N,M,X;
int H[100001];
void solve(){
cin>>N>>M>>X;
cout<<"YES"<<endl;
set<pair<int,int>>s; //stores pairs of (height, index)
for (int i=1;i<=M;i++)
s.insert({0,i});
for (int i=0;i<N;i++){
cin>>H[i];
pair<int,int>p=*s.begin();
s.erase(p);
c... |
1515 | D | Phoenix and Socks | To satisfy his love of matching socks, Phoenix has brought his $n$ socks ($n$ is even) to the sock store. Each of his socks has a color $c_i$ and is either a left sock or right sock.
Phoenix can pay one dollar to the sock store to either:
- recolor a sock to any color $c'$ $(1 \le c' \le n)$
- turn a left sock into a... | First, let's remove all pairs that are already matching because an optimal solution will never change them. Suppose there remain $l$ left socks and $r$ right socks. Without loss of generality, assume $l \geq r$. If not, we can just swap all left and right socks. We know that regardless of other operations, we will alwa... | [
"greedy",
"sortings",
"two pointers"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int N,L,R;
int C[200001];
int lcnt[200001],rcnt[200001];
void solve(){
cin>>N>>L>>R;
for (int i=1;i<=N;i++){
lcnt[i]=0;
rcnt[i]=0;
}
for (int i=1;i<=N;i++){
cin>>C[i];
if (i<=L)
lcnt[C[i]]++;
else
rcnt[C[i]]++;
}
//remove pairs ... |
1515 | E | Phoenix and Computers | There are $n$ computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer $i-1$ and computer $i+1$ are both on, computer $i$ $(2 \le i \le n-1)$ will turn on automatically if it is not already on. Note that Phoenix cannot ... | Let's first determine how many ways there are to turn on a segment of $k$ computers without any of them turning on automatically (we manually enable all $k$). We have two methods: Method 1: If we turn on computer $1$ first, then we must turn on $2$, $3$, $\dots$, $k$ in that order. There are $k-1 \choose 0$ ways to do ... | [
"combinatorics",
"dp",
"math"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll MOD;
int N;
ll dp[405][405];
ll fastexp(ll b, ll exp){
if (exp==0)
return 1;
ll temp=fastexp(b,exp/2);
temp=(temp*temp)%MOD;
if (exp%2==1)
temp*=b;
return temp%MOD;
}
ll fact[405],inv[405],choose[405][405],pow2[405];
void preco... |
1515 | F | Phoenix and Earthquake | Phoenix's homeland, the Fire Nation had $n$ cities that were connected by $m$ roads, but the roads were all destroyed by an earthquake. The Fire Nation wishes to repair $n-1$ of these roads so that all the cities are connected again.
The $i$-th city has $a_i$ tons of asphalt. $x$ tons of asphalt are used up when repai... | First, note that cities connected by roads behave as one city with the total amount of asphalt. This means building a road is equivalent to merging two cities and summing their asphalt. If the total asphalt is less than $(n-1)$ $\cdot$ $x$, then we don't have enough asphalt to repair all the roads. It turns out that if... | [
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs",
"greedy",
"trees"
] | 2,600 | // Fix a spanning tree
// Pick a leaf, either merge it into its parent or postpone it to the end
#include <cstdio>
#include <vector>
#include <algorithm>
const int MAXV=300005;
const int MAXE=300005;
int N,M,X;
long long as[MAXV];
int elist[MAXE*2];
int head[MAXV];
int prev[MAXE*2];
int tot=0;
bool vis[MAXV];
int ... |
1515 | G | Phoenix and Odometers | In Fire City, there are $n$ intersections and $m$ one-way roads. The $i$-th road goes from intersection $a_i$ to $b_i$ and has length $l_i$ miles.
There are $q$ cars that may only drive along those roads. The $i$-th car starts at intersection $v_i$ and has an odometer that begins at $s_i$, increments for each mile dri... | We can solve for each strongly-connected component independently. From now on, we will assume the graph is strongly-connected. Define the length of a walk to be the sum of the weights of its edges, modulo $MOD$, the distance at which the odometer resets. This is different for different queries, but the important thing ... | [
"dfs and similar",
"graphs",
"math",
"number theory"
] | 2,700 | #include <cstdio>
#include <vector>
#include <cassert>
#include <algorithm>
#include <cmath>
using ll = long long;
std::vector<std::pair<int,int> > fwd[200005];
std::vector<std::pair<int,int> > rev[200005];
int vis[200005];
int cc[200005];
ll offset[200005];
int ncc;
ll loop[200005];
std::vector<int> ord;
ll gcd(ll... |
1515 | H | Phoenix and Bits | Phoenix loves playing with bits — specifically, by using the bitwise operations AND, OR, and XOR. He has $n$ integers $a_1, a_2, \dots, a_n$, and will perform $q$ of the following queries:
- replace all numbers $a_i$ where $l \le a_i \le r$ with $a_i$ AND $x$;
- replace all numbers $a_i$ where $l \le a_i \le r$ with $... | We store the binary representation of all the numbers in a trie. To perform operations on a range, we split the trie to extract the range, perform the operation, and merge everything back. AND $x$ is equivalent to the sequence XOR $2^{20}-1$, OR $x\oplus(2^{20}-1)$, XOR $2^{20}-1$. XOR does not affect the number of num... | [
"bitmasks",
"brute force",
"data structures",
"sortings"
] | 3,500 | #include <cstdio>
#include <cassert>
#include <utility>
#include <functional>
//numbers up to 2^MAXLOGX-1
const int MAXLOGX=20;
template<int k>
struct Trie{
Trie<k-1>* chd[2];
int cnt;
int lazy;
int has[2];
int get_cnt(){
assert(this!=NULL);
return cnt;
}
int get_has(int d){
assert(this!=NUL... |
1515 | I | Phoenix and Diamonds | Phoenix wonders what it is like to rob diamonds from a jewelry store!
There are $n$ types of diamonds. The $i$-th type has weight $w_i$ and value $v_i$. The store initially has $a_i$ diamonds of the $i$-th type.
Each day, for $q$ days, one of the following will happen:
- A new shipment of $k_i$ diamonds of type $d_i... | Suppose the largest weight of an item is less than $2^k$. Call an item heavy if its weight is in the range $[2^{k-1},2^k)$ and light if its weight is in the range $(0,2^{k-1})$. Sort the items in decreasing order by value. As the thief moves left to right, his remaining capacity is nonincreasing. Consider the point whe... | [
"binary search",
"data structures",
"sortings"
] | 3,400 | #include <cstdio>
#include <algorithm>
#include <functional>
#include <utility>
#include <numeric>
#include <cassert>
using ll=long long;
const ll INF=1e18+7;
struct Diamond{
int w,v,t;
ll a;
}diamonds[200005];
int index[200005];
int N;
struct Node{
ll sum_w[31];//sum of weights of all diamonds with weight <2... |
1516 | A | Tit for Tat | Given an array $a$ of length $n$, you can do at most $k$ operations of the following type on it:
- choose $2$ different elements in the array, add $1$ to the first, and subtract $1$ from the second. However, all the elements of $a$ have to remain non-negative after this operation.
What is lexicographically the smalle... | The general approach to minimizing an array lexicographically is to try to make the first element as small as possible, then the second element, and so on. So greedily, in each operation, we'll pick the first non-zero element and subtract $1$ from it, and we'll add that $1$ to the very last element. You can make the im... | [
"greedy"
] | 800 | "#include <bits/stdc++.h>\nusing namespace std;\nint a[105];\nint main()\n{\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tint n,k;\n\t\tscanf(\"%d%d\",&n,&k);\n\t\tfor (int i=0;i<n;i++)\n\t\tscanf(\"%d\",&a[i]);\n\t\tfor (int i=0;i<n-1;i++)\n\t\t{\n\t\t\tif (a[i]<k)\n\t\t\t{\n\t\t\t\tk-=a[i];\n\t\t\t\ta[n-1]+... |
1516 | B | AGAGA XOOORRR | Baby Ehab is known for his love for a certain operation. He has an array $a$ of length $n$, and he decided to keep doing the following operation on it:
- he picks $2$ adjacent elements; he then removes them and places a single integer in their place: their bitwise XOR. Note that the length of the array decreases by on... | So let's try to understand what the final array looks like in terms of the initial array. The best way to see this is to look at the process backwards. Basically, start with the final array, and keep replacing an element with the $2$ elements that xor-ed down to it, until you get the initial array. You'll see that the ... | [
"bitmasks",
"brute force",
"dp",
"greedy"
] | 1,500 | "#include <bits/stdc++.h>\nusing namespace std;\nint pre[2005];\nint main()\n{\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tint n;\n\t\tscanf(\"%d\",&n);\n\t\tfor (int i=1;i<=n;i++)\n\t\t{\n\t\t\tint a;\n\t\t\tscanf(\"%d\",&a);\n\t\t\tpre[i]=(pre[i-1]^a);\n\t\t}\n\t\tbool yes=!pre[n];\n\t\tfor (int i=1;i<=n;... |
1516 | C | Baby Ehab Partitions Again | Baby Ehab was toying around with arrays. He has an array $a$ of length $n$. He defines an array to be good if there's no way to partition it into $2$ subsequences such that the sum of the elements in the first is equal to the sum of the elements in the second. Now he wants to remove the minimum number of elements in $a... | First of all, let's check if the array is already good. This can be done with knapsack dp. If it is, the answer is $0$. If it isn't, I claim you can always remove one element to make it good, and here's how to find it: Since the array can be partitioned, its sum is even. So if we remove an odd element, it will be odd, ... | [
"bitmasks",
"constructive algorithms",
"dp",
"math"
] | 1,700 | "#include <bits/stdc++.h>\nusing namespace std;\nint n;\nbool bad(vector<int> v)\n{\n\tint s=0;\n\tfor (int i:v)\n\ts+=i;\n\tif (s%2)\n\treturn 0;\n\tbitset<200005> b;\n\tb[0]=1;\n\tfor (int i:v)\n\tb|=(b<<i);\n\treturn b[s/2];\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tvector<int> v(n);\n\tfor (int i=0;i<n;i++)\n\tscan... |
1516 | D | Cut | This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array $a$ of length $n$ written on it, and then he does the following:
- he picks a range $(l, r)$ and cuts the subsegment $a_l, a_{l + 1}, \ldots, a_r$ out, removing the rest of the array.
- he then cuts this range into multiple ... | Let's understand what "product=LCM" means. Let's look at any prime $p$. Then, the product operation adds up its exponent in all the numbers, while the LCM operation takes the maximum exponent. Hence, the only way they're equal is if every prime divides at most one number in the range. Another way to think about it is t... | [
"binary search",
"data structures",
"dp",
"graphs",
"number theory",
"two pointers"
] | 2,100 | "#include <bits/stdc++.h>\nusing namespace std;\n#define MX 100000\nvector<int> p[100005];\nint a[100005],nex[100005],dp[20][100005];\nint main()\n{\n int n,q;\n\tscanf(\"%d%d\",&n,&q);\n\tfor (int i=1;i<=n;i++)\n\tscanf(\"%d\",&a[i]);\n\tfor (int i=2;i<=MX;i++)\n\t{\n\t\tif (p[i].empty())\n\t\t{\n\t\t nex[i]=n+1... |
1516 | E | Baby Ehab Plays with Permutations | This time around, Baby Ehab will play with permutations. He has $n$ cubes arranged in a row, with numbers from $1$ to $n$ written on them. He'll make \textbf{exactly} $j$ operations. In each operation, he'll pick up $2$ cubes and switch their positions.
He's wondering: how many different sequences of cubes can I have ... | Let's think about the problem backwards. Let's try to count the number of permutations which need exactly $j$ swaps to be sorted. To do this, I first need to refresh your mind (or maybe introduce you) to a greedy algorithm that does the minimum number of swaps to sort a permutation. Look at the last mismatch in the per... | [
"combinatorics",
"dp",
"math"
] | 2,500 | "#include <bits/stdc++.h>\nusing namespace std;\n#define MX 200\n#define mod 1000000007\nlong long inv[MX+5];\nlong long ncr(int n,int r)\n{\n\tlong long ret=1;\n\tfor (int i=n-r+1;i<=n;i++)\n\tret=(ret*i)%mod;\n\tfor (int i=1;i<=r;i++)\n\tret=(ret*inv[i])%mod;\n\treturn ret;\n}\nint main()\n{\n\tinv[1]=1;\n\tfor (int ... |
1517 | A | Sum of 2050 | A number is called 2050-number if it is $2050$, $20500$, ..., ($2050 \cdot 10^k$ for integer $k \ge 0$).
Given a number $n$, you are asked to represent $n$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that. | First, we need to check whether $n$ is the multiple of $2050$. If $n$ is not the multiple of $2050$, the answer is always $-1$. Then we can divide $n$ by $2050$, the problem now is how to represent $n$ as the sum of powers of $10$. So the answer is the sum of its digits in decimal representation. | [
"greedy",
"math"
] | 800 | null |
1517 | B | Morning Jogging | The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.
There are $n+1$ checkpoints on the trail. They are numbered by $0$, $1$, ..., $n$. A runner must start at checkpoint $0$ and finish at checkpoint $n$. N... | The minimum sum is the sum of $m$ smallest of all $nm$ numbers. To construct the answer, we can just mark these $m$ smallest numbers and put them in $m$ different columns. A possible way is that for each row, you can sort all numbers from small to large, and rotate the marked number in this row to unmarked columns. For... | [
"constructive algorithms",
"greedy",
"sortings"
] | 1,200 | null |
1517 | C | Fillomino 2 | Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:
Consider an $n$ by $n$ chessboard. Its rows are numbered from $1$ to $n$ from the top to the bottom. Its columns are numbered ... | The answer is unique and always exists. There are two ways to construct the answer. Construction 1: Start with the main diagonal. There is one cell $(x, x)$ with number $1$ on it. That cell must form a region by itself. For each cell $(y, y)$ on the main diagonal that is above $(x, x)$, the cell $(y+1, y)$ belongs to t... | [
"constructive algorithms",
"dfs and similar",
"greedy",
"implementation"
] | 1,400 | null |
1517 | D | Explorer Space | You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size $n\times m$. The set of vertices is $\{(i, j)|1\le i\le n, 1\le j\le m\}$. Two vertices $(i_1,j_1)$ and $(i_2, j_2)$ are connected by an edge if and only if $|i_1-i_2|+|j_1-j_... | Since the graph is bipartite, when $k$ is odd, it is impossible to go back to the vertex after $k$ steps. Since the graph is undirected, we can always find a path with length $k/2$, walk along this path and return. We can use dynamic programming to compute the shortest path from $u$ with length $k$. $dp_{u,k} = \min_{(... | [
"dp",
"graphs",
"shortest paths"
] | 1,800 | null |
1517 | E | Group Photo | In the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The $n$ people form a line. They are numbered from $1$ to $n$ from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'.
Let $C=\{c_1,c_2,\d... | There can't be two $i$'s such that $c_i-c_{i-1}>2$, or $p_i-p_{i-1}$ won't be non-increasing. And there can't be two $i$'s such that $p_i-p_{i-1}>2$, or $c_i-c_{i-1}$ won't be non-decreasing. So for any $2\leq i<m$, $c_i-c_{i-1}\leq 2$, and for any $2\leq i<k$, $p_i-p_{i-1}\leq 2$. Then we can find out that there are o... | [
"binary search",
"data structures",
"implementation",
"two pointers"
] | 2,500 | null |
1517 | F | Reunion | It is reported that the 2050 Conference will be held in Yunqi Town in Hangzhou from April 23 to 25, including theme forums, morning jogging, camping and so on.
The relationship between the $n$ volunteers of the 2050 Conference can be represented by a tree (a connected undirected graph with $n$ vertices and $n-1$ edges... | Let $B(u,r) = \{v | \mathrm{dis}(u,v) \leq r \}$. And a vertex is colored black iff the volunteer is not attend. First, we enumerate $r$ and count the number of ways that the answer is no larger than $r$. That is equivalent to for all black vertices $u$, the union of $B(u,r)$ will cover all vertices. So a typical tree ... | [
"combinatorics",
"dp",
"trees"
] | 3,200 | null |
1517 | G | Starry Night Camping | At the foot of Liyushan Mountain, $n$ tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky.
The $i$-th tent is located at the point of $(x_i, y_i)$ and has a weight of $w_i$. A tent is im... | We can label all the integer points in the plane as follow: ...2323... ...1010... ...2323... ...1010... Where all the good points are labeled with 1. If we draw an edge between every adjacent points, all the forbidden patterns form all paths of length 4 with label 0-1-2-3. So we transform the problem to another problem... | [
"constructive algorithms",
"flows",
"graphs"
] | 3,300 | null |
1517 | H | Fly Around the World | After hearing the story of Dr. Zhang, Wowo decides to plan his own flight around the world.
He already chose $n$ checkpoints in the world map. Due to the landform and the clouds, he cannot fly too high or too low. Formally, let $b_i$ be the height of Wowo's aircraft at checkpoint $i$, $x_i^-\le b_i\le x_i^+$ should be... | Consider the DP idea: dp[i][x][y] represests whether there exists a sequence $b_1, \ldots, b_i$ satisfying all the constraints. (Constraints about $b_{i+1}, b_{i+2}, \ldots$ are ignored.) Then $R(i)=\{(x, y) | dp[i][x][y] = true\}$ is a region on the plane. We will prove that it is convex and then show that we can effi... | [
"dp",
"geometry"
] | 3,500 | null |
1519 | A | Red and Blue Beans | You have $r$ red and $b$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:
- has at least one red bean (or the number of red beans $r_i \ge 1$);
- has at least one blue bean (or the number of blue beans $b_i \ge 1$);
- the number of red and blue beans should d... | Without loss of generality, let's say $r \le b$ (otherwise, we can swap them). Note that you can't use more than $r$ packets (at least one red bean in each packet), so $b$ can't exceed $r \cdot (d + 1)$ (at most $d + 1$ blue beans in each packet). So, if $b > r \cdot (d + 1)$ then asnwer is NO. Otherwise, we can form e... | [
"math"
] | 800 | fun main() {
repeat(readLine()!!.toInt()) {
val (r, b, d) = readLine()!!.split(' ').map { it.toInt() }
println(if (minOf(r, b) * (d + 1).toLong() >= maxOf(r, b)) "YES" else "NO")
}
} |
1519 | B | The Cake Is a Lie | There is a $n \times m$ grid. You are standing at cell $(1, 1)$ and your goal is to finish at cell $(n, m)$.
You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $(x, y)$. You can:
- move right to the cell $(x, y + 1)$ — it costs $x$ burles;
- move down to the c... | Note that whichever path you choose, the total cost will be the same. If you know that the cost is the same, then it's not hard to calculate it. It's equal to $n \cdot m - 1$. So the task is to check: is $k$ equal to $n \cdot m - 1$ or not. The constant cost may be proved by induction on $n + m$: for $n = m = 1$ cost i... | [
"dp",
"math"
] | 800 | fun main() {
repeat(readLine()!!.toInt()) {
val (n, m, k) = readLine()!!.split(' ').map { it.toInt() }
println(if (n * m - 1 == k) "YES" else "NO")
}
} |
1519 | C | Berland Regional | Polycarp is an organizer of a Berland ICPC regional event. There are $n$ universities in Berland numbered from $1$ to $n$. Polycarp knows all competitive programmers in the region. There are $n$ students: the $i$-th student is enrolled at a university $u_i$ and has a programming skill $s_i$.
Polycarp has to decide on ... | There are two important observations to make. The first one is that you can calculate the answers for each university independently of each other and sum them up to obtain the true answer. The second one is that if there are $x$ students in an university, then that university can only contribute to answers for $k$ from... | [
"brute force",
"data structures",
"greedy",
"number theory",
"sortings"
] | 1,400 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int t;
scanf("%d", &t);
forn(_, t){
int n;
scanf("%d", &n);
vector<int> s(n), u(n);
forn(i, n){
scanf("%d", &s[i]);
--s[i];
}
... |
1519 | D | Maximum Sum of Products | You are given two integer arrays $a$ and $b$ of length $n$.
You can reverse \textbf{at most one} subarray (continuous subsegment) of the array $a$.
Your task is to reverse such a subarray that the sum $\sum\limits_{i=1}^n a_i \cdot b_i$ is \textbf{maximized}. | The naive approach is to iterate over $l$ and $r$, reverse the subsegment of the array $[l, r]$ and calculate the answer. But this solution is too slow and works in $O(n^3)$. Instead, we can iterate over the center of the reversed segment and its length. If the current segment is $[l, r]$, and we want to go to $[l - 1,... | [
"brute force",
"dp",
"implementation",
"math",
"two pointers"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
using li = long long;
int main() {
int n;
cin >> n;
vector<li> a(n), b(n);
for (auto& x : a) cin >> x;
for (auto& x : b) cin >> x;
vector<li> pr(n + 1, 0);
for (int i = 0; i < n; ++i)
pr[i + 1] = pr[i] + a[i] * b[i];
li ans = pr[n];
for (int c = 0; ... |
1519 | E | Off by One | There are $n$ points on an infinite plane. The $i$-th point has coordinates $(x_i, y_i)$ such that $x_i > 0$ and $y_i > 0$. The coordinates are not necessarily integer.
In one move you perform the following operations:
- choose two points $a$ and $b$ ($a \neq b$);
- move point $a$ from $(x_a, y_a)$ to either $(x_a + ... | At first the problem sounds like some sort of matching. However, it seems like you first want to match each point with either of its moves and then some pairs of points to each other. That doesn't sound viable but since the matchings are often connected with graphs, the graph idea might come handy. Let's first consider... | [
"constructive algorithms",
"dfs and similar",
"geometry",
"graphs",
"sortings",
"trees"
] | 2,700 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define x first
#define y second
using namespace std;
struct point{
int a, b, c, d;
};
typedef pair<long long, long long> frac;
typedef pair<int, int> pt;
int n;
vector<point> a;
map<frac, int> sv;
frac norm(long long x, long long y)... |
1519 | F | Chests and Keys | Alice and Bob play a game. Alice has got $n$ treasure chests (the $i$-th of which contains $a_i$ coins) and $m$ keys (the $j$-th of which she can sell Bob for $b_j$ coins).
Firstly, Alice puts some locks on the chests. There are $m$ types of locks, the locks of the $j$-th type can only be opened with the $j$-th key. T... | Firstly, let's try to find some naive solution for this problem. Let's iterate on the subset of locks Alice puts on the chests. After choosing the subset of locks, how to check whether Bob can gain positive profit? We can iterate on the subset of keys he can buy as well, but in fact, this problem has a polynomial solut... | [
"bitmasks",
"brute force",
"dfs and similar",
"dp",
"flows"
] | 3,200 | #include<bits/stdc++.h>
using namespace std;
const int N = 6;
const int M = 400;
const int INF = int(1e9);
int a[N];
int b[N];
int c[N][N];
int n, m;
struct state
{
vector<int> need;
int v2;
int v1;
int rem;
state() {};
state(vector<int> need, int v1, int v2, int rem) : need(need), v1(v1), v... |
1520 | A | Do Not Be Distracted! | Polycarp has $26$ tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot ... | The simplest solution - go through the problem, because of which the teacher might have suspicions. Now you can find the first day when Polycarp solved this problem and the last such day. Between these two days, all problems should be the same. If this is not the case, the answer is "NO". | [
"brute force",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using cd = complex<ld>;
void solve() {
int n;
cin >> n;
string s;
cin >> s;
for (char c = 'A'; c <= 'Z'; c++) {
int first = n;
int last = -1;
for (int i ... |
1520 | B | Ordinary Numbers | Let's call a positive integer $n$ ordinary if in the decimal notation all its digits are the same. For example, $1$, $2$ and $99$ are ordinary numbers, but $719$ and $2021$ are not ordinary numbers.
For a given number $n$, find the number of ordinary numbers among the numbers from $1$ to $n$. | Note that every ordinary number can be represented as $d \cdot (10^0 + 10^1 + \ldots + 10^k)$. Therefore, to count all ordinary numbers among the numbers from $1$ to $n$, it is enough to count the number of $(d, k)$ pairs such that $d \cdot (10^0 + 10^1 + \ldots + 10^k) \le n$. In the given constraints, it is enough to... | [
"brute force",
"math",
"number theory"
] | 800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n;
cin >> n;
int res = 0;
for (ll pw = 1; pw <= n; pw = pw * 10 + 1) {
for (int d = 1; d <= 9; d++) {
if (pw * d <= n) {
res++;
}
}
}
cout << res << endl;
}
int main() {
int tests;
cin ... |
1520 | C | Not Adjacent Matrix | We will consider the numbers $a$ and $b$ as adjacent if they differ by exactly one, that is, $|a-b|=1$.
We will consider cells of a square matrix $n \times n$ as adjacent if they have a common side, that is, for cell $(r, c)$ cells $(r, c-1)$, $(r, c+1)$, $(r-1, c)$ and $(r+1, c)$ are adjacent to it.
For a given numb... | Note that $n = 2$ is the only case where there is no answer. For other cases, consider the following construction: Let's say that the cell $(i, j)$ is white if $i + j$ is an even number, otherwise, we will say that the cell $(i, j)$ is black; Let's arrange the cells so that all white cells are first, and if the colors ... | [
"constructive algorithms"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
if (n == 1) {
cout << "1" << endl;
return;
} else if (n == 2) {
cout << "-1" << endl;
return;
}
vector<vector<int>> a(n, vector<int>(n));
a[0][0] = 1;
a[n - 1][n - 1] = n * n;
int x = n * n - 1;
for (int i... |
1520 | D | Same Differences | You are given an array $a$ of $n$ integers. Count the number of pairs of indices $(i, j)$ such that $i < j$ and $a_j - a_i = j - i$. | Let's rewrite the original equality a bit: $a_j - a_i = j - i,$ $a_j - j = a_i - i$ Let's replace each $a_i$ with $b_i = a_i - i$. Then the answer is the number of pairs $(i, j)$ such that $i < j$ and $b_i = b_j$. To calculate this value you can use map or sorting. | [
"data structures",
"hashing",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
map<int, int> a;
long long res = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
x -= i;
res += a[x];
a[x]++;
}
cout << res << endl;
}
int main() {
int tests;
cin >> tests;
while (tests-- > 0) {
... |
1520 | E | Arranging The Sheep | You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $n$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the ... | Let's denote by $k$ the number of sheep in the string, and by $x_1, x_2, \ldots, x_k$ ($1 \le x_1 < x_2 < \ldots < x_k \le n$) their positions in the string. Note that in the optimal solution the sheep with the number $m = \lceil\frac{n}{2}\rceil$ will not make moves. This can be proved by considering the optimal solut... | [
"greedy",
"math"
] | 1,400 | #include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
string s;
cin >> s;
int cnt = 0;
for(auto x : s)
cnt += (x == '*' ? 1 : 0);
int pos = -1;
int cur = -1;
for(int i = 0; i < n; i++)
{
if(s[i] == '*')
{
cur++;
if(cur == cnt / 2)
pos = i;
}
}
lon... |
1520 | F1 | Guess the K-th Zero (Easy version) | \textbf{This is an interactive problem.}
\textbf{This is an easy version of the problem. The difference from the hard version is that in the easy version $t=1$ and the number of queries is limited to $20$.}
Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wi... | This problem can be solved by binary search. Let's maintain a segment that is guaranteed to contain the $k$-th zero and gradually narrow it down. Let the current segment be - $[l, r]$ and we want to find $k$-th zero on it. Let's make a query on the half of the segment $[l, m]$, where $m = \frac{l+r}{2}$. If there are a... | [
"binary search",
"interactive"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using cd = complex<ld>;
void calc(int l, int r, int k) {
if (l == r) {
cout << "! " << l << endl;
return;
}
int m = (l + r) / 2;
cout << "? " << l << " " << m << end... |
1520 | F2 | Guess the K-th Zero (Hard version) | \textbf{This is an interactive problem.}
\textbf{This is a hard version of the problem. The difference from the easy version is that in the hard version $1 \le t \le \min(n, 10^4)$ and the total number of queries is limited to $6 \cdot 10^4$.}
Polycarp is playing a computer game. In this game, an array consisting of ... | In this problem, you can apply the same solution as in the previous one, but you need to remember the responses to the requests and not make the same requests several times. Why does it work? Imagine a binary tree with a segment at each vertex, and its children - the left and right half of the segment. We will leave on... | [
"binary search",
"constructive algorithms",
"data structures",
"interactive"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
map<pair<int,int>, int> cache;
void dec(int pos, int L, int R) {
cache[{L, R}]--;
if (L != R) {
int M = (L + R) / 2;
if (pos <= M)
dec(pos, L, M);
else
dec(pos, ... |
1520 | G | To Go Or Not To Go? | Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the \textbf{minimum time} it will take him to get from home to school.
The city where Dima lives is a rectangular field of $n \times m$ size. Each cell... | There is no point in using two transitions between portals, because if you want to go from portal $A$ to portal $B$, and then from portal $C$ to portal $D$, then you can immediately go from portal $A$ to portal $D$ for less. Then there are two possible paths. First - do not use portals. Here it is enough to find the sh... | [
"brute force",
"dfs and similar",
"graphs",
"greedy",
"implementation",
"shortest paths"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using cd = complex<ld>;
const int MAX_N = 2010;
int dd[4][2] = {
{1, 0},
{0, 1},
{-1, 0},
{0, -1}
};
void bfs(int sx, int sy, vector<vector<int>> &d, vector<vector... |
1521 | A | Nastia and Nearly Good Numbers | Nastia has $2$ positive integers $A$ and $B$. She defines that:
- The integer is good if it is divisible by $A \cdot B$;
- Otherwise, the integer is nearly good, if it is divisible by $A$.
For example, if $A = 6$ and $B = 4$, the integers $24$ and $72$ are good, the integers $6$, $660$ and $12$ are nearly good, the i... | There are $2$ cases: if $B = 1$, then the answer doesn't exist. Here we cannot get the nearly good numbers at all. Otherwise, we can construct the answer as $A + A \cdot B = A \cdot (B + 1)$. | [
"constructive algorithms",
"math",
"number theory"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int q;
cin >> q;
while (q--) {
int a, b; cin >> a >> b;
if (b == 1) {
cout << "NO" << endl;
} else {
cout << "YES" << ... |
1521 | B | Nastia and a Good Array | Nastia has received an array of $n$ positive integers as a gift.
She calls such an array $a$ good that for all $i$ ($2 \le i \le n$) takes place $gcd(a_{i - 1}, a_{i}) = 1$, where $gcd(u, v)$ denotes the greatest common divisor (GCD) of integers $u$ and $v$.
You can perform the operation: select two \textbf{different... | There are many ways to solve the problem. Here is one of them: We will use the fact that $gcd(i, i + 1) = 1$ for any integer $i \ge 1$. Let's find the minimum element $x$ of the array $a$ that is located in the position $pos$. Then for all integer $i$ ($1 \le i \le n$) perform the following operation: $(pos,\ i,\ x,\ x... | [
"constructive algorithms",
"math",
"number theory"
] | 1,300 | #include "bits/stdc++.h"
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int q;
cin >> q;
while (q--) {
int n; cin >> n;
int x = 1e9 + 7, pos = -1;
for (int i = 0; i < n; ++i) {
int a; cin >> a;
... |
1521 | C | Nastia and a Hidden Permutation | \textbf{This is an interactive problem!}
Nastia has a hidden permutation $p$ of length $n$ consisting of integers from $1$ to $n$. You, for some reason, want to figure out the permutation. To do that, you can give her an integer $t$ ($1 \le t \le 2$), two \textbf{different} indices $i$ and $j$ ($1 \le i, j \le n$, $i ... | Solution $1$: Let's fix $2$ indices $i$ and $j$ $(1 \le i, j \le n,$ $i \neq j)$. Then restore $p_{i}$ and $p_{j}$. Let's assume we know the maximum element among $p_i$ and $p_j$: $mx = \max(p_i, p_j)$. Now we can figure out where exactly the maximum is by asking the following query: $val = \max{(\min{(mx - 1, p_i)}, \... | [
"constructive algorithms",
"interactive"
] | 2,000 | #include "bits/stdc++.h"
using namespace std;
int ask(int t, int i, int j, int x) {
cout << "? " << t << ' ' << i + 1 << ' ' << j + 1 << ' ' << x << endl;
int val; cin >> val;
if (val == -1) exit(0);
return val;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullp... |
1521 | D | Nastia Plays with a Tree | Nastia has an unweighted tree with $n$ vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
- Remove any existing edge.
- Add an edge between any pair of vertices.
What is the \textbf{minimum} number of operations Nastia needs to get a bamboo from a t... | Let's define the variable $x$ as a minimum number of operations that we need to get bamboo from a tree. Let's remove $x$ edges first and then add $x$ new ones to the graph. Consider the structure of the graph after removing $x$ edges. This is a forest with a $x + 1$ connected components. Easy to notice each of the $x +... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"dp",
"dsu",
"greedy",
"implementation",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
struct edge {
int v, u;
};
vector<pair<edge, edge>> operations;
int dp[N], answer = 0;
bool isDeleted[N];
vector<pair<int, int>> g[N];
void dfs(int v, int p = -1) {
int sz = (int)g[v].size() - (p != -1);
for (auto to : g[v]) {
... |
1521 | E | Nastia and a Beautiful Matrix | You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?
Let $a_i$ be how many numbers $i$ ($1 \le i \le k$) you have.
An $n \times n$ matrix is called beautiful if it contains \textbf{all} the numbers you have, and for \textbf{each} $2 \times 2$ submatrix of th... | Let's fix $n$ and will check whether we build a beautiful matrix or not. Let's define the variable $mx$ as a maximum element among all elements from the array $a$. In other words, the amount of the most frequently occurring number we have. Also, define the variable $sum$ as an amount of numbers we have. We can single o... | [
"binary search",
"constructive algorithms",
"dp",
"greedy"
] | 2,700 | #include "bits/stdc++.h"
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int q;
cin >> q;
while (q--) {
int m, k; cin >> m >> k;
pair<int, int> a[k];
for (int i = 0; i < k; ++i) {
cin >> a[i].first, a[i... |
1523 | A | Game of Life | William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $n$ cells, with each cell either being alive or dead.
Evolution of the array in William's cellular automaton occurs iterativel... | Notice that evolution will go on for no more than $n$ iterations, since on each iteration at least one new living cell will appear, and if it doesn't this would mean that we remain in the same state as on the previous step and the simulation is over. Knowing this we can write a simple simulation of the process describe... | [
"implementation"
] | 800 | null |
1523 | B | Lord of the Values | While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $a_1, a_2, \ldots, a_n$ to $-a_1, -a_2, \ldots, ... | Notice that for transforming any pair of numbers $(a, b)$ into a pair $(-a, -b)$ a sequence of operations such as $(1, 2, 1, 2, 1, 2)$ can be performed. Since $n$ is even we can apply this sequence of operations for all pairs of numbers $(a_{i \cdot 2 - 1}, a_{i \cdot 2})$ for all $i$ from $1$ to $\frac{n}{2}$. Final c... | [
"constructive algorithms"
] | 1,100 | null |
1523 | C | Compression and Expansion | William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.
A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, \textbf{on a new line}, just... | Let's maintain the current depth of the list in a stack. Initially the stack is empty. For each new $a_i$ there are two options: $a_i=1$. In this case we just add the given number to the end of the stack and it will point to a new subitem in the list. $a_i > 1$. In this case we need to find the subitem, the last number... | [
"brute force",
"data structures",
"greedy",
"implementation",
"trees"
] | 1,600 | null |
1523 | D | Love-Hate | William is hosting a party for $n$ of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.
For each William's friend $i$ it is known whether he likes currency $j$. There are $m... | Notice that the final answer will be a submask of one of $\lceil \frac{n}{2} \rceil$ friends. Knowing this, random generation may be used to pick a random mask. If we check a randomly-generated index 50 times then the probability of not hitting a single index of a friend from the required group is $(\frac{1}{2})^{50}$.... | [
"bitmasks",
"brute force",
"dp",
"probabilities"
] | 2,400 | null |
1523 | E | Crypto Lights | To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of $n$ lights arranged in a row. The device functions in the following way:
Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, pick... | Let's consider all states of the device where $p$ lights are turned on, and when at the current moment the algorithm has not yet finished working. We will be checking all values for $p$ from 1 to $n$. Notice that for a state where $p$ lights are turned on the probability of getting to that state is $\frac{p!}{n \cdot (... | [
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,600 | null |
1523 | F | Favorite Game | After William is done with work for the day, he enjoys playing his favorite video game.
The game happens in a 2D world, starting at turn $0$. William can pick any cell in the game world and spawn in it. Then, each turn, William may remain at his current location or move from the current location (x, y) to one of the f... | For convenience we will sort quests by time. Let's make two DP: $F(mask, done_q)$ - minimum amount of time it takes to visit the set of $mask$ towers and complete $done_q$ quests. William is in one of the towers. $G(mask, q)$ - maximum number of quests that William can complete if he visited a set of $mask$ towers, and... | [
"bitmasks",
"dp"
] | 3,300 | null |
1523 | G | Try Booking | William owns a flat in central London. He decided to rent his flat out for the next $n$ days to earn some money.
Since his flat is in the center of the city, he instantly got $m$ offers in the form $(l_i, r_i)$, which means that someone wants to book the flat from day $l_i$ until day $r_i$ inclusive. To avoid spending... | Note that if you think of the answer as the number accepted offers for rent, the sum of the answers in the worst case will be no more than $\frac{n}{n}+\frac{n}{n - 1}+\ldots+\frac{n}{1}$. This value can be estimated in $n \cdot log (n)$. So for each $i$ we can try to learn how to process only those offers that are act... | [
"data structures",
"divide and conquer"
] | 3,200 | null |
1523 | H | Hopping Around the Array | William really wants to get a pet. Since his childhood he dreamt about getting a pet grasshopper. William is being very responsible about choosing his pet, so he wants to set up a trial for the grasshopper!
The trial takes place on an array $a$ of length $n$, which defines lengths of hops for each of $n$ cells. A gras... | Let's look into all jumps in the optimal answer except the last one with $k = 0$. Thereafter, from the position $i$ it is most effective to jump at such position $best$ that: $i \le best \le i+a_i$ and $a_{best} + best$ is the maximal possible. For each $i$ we can use a segment tree for maximum to find that optimal $be... | [
"data structures",
"dp"
] | 3,500 | null |
1525 | A | Potion-making | You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly $k\ \%$ magic essence and $(100 - k)\ \%$ water.
In one step, you can pour either one liter of magic essence or one liter of wat... | Since you need $e$ liters of essence to be exactly $k\ \%$ of potion then we can write an equality: $\frac{e}{e + w} = \frac{k}{100}$ or $k = x \cdot e$ and $100 = x \cdot (e + w)$ for some integer $x$. Since we need to minimize $e + w$ and $x(e + w) = 100$, then we should maximize $x$, but both $k$ and $100$ should be... | [
"math",
"number theory"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
while (t--) {
int k; cin >> k;
cout << 100 / gcd(100, k) << endl;
}
return 0;
}
|
1525 | B | Permutation Sort | You are given a permutation $a$ consisting of $n$ numbers $1$, $2$, ..., $n$ (a permutation is an array in which each element from $1$ to $n$ occurs exactly once).
You can perform the following operation: choose some subarray (contiguous subsegment) of $a$ and rearrange the elements in it in any way you want. But this... | To solve the problem, it is enough to consider several cases: if the array is already sorted, the answer is $0$; if $a[1] = 1$ (or $a[n] = n$), then you can sort the array in one operation by selecting the subarray $[1, n-1]$ (or $[2, n]$); if $a[1] = n$ and $a[n] = 1$, you can perform the sequence of operations $[1, n... | [
"constructive algorithms",
"greedy"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
vector<int> a(n);
for (int &x : a) scanf("%d", &x);
int ans = 2;
if (is_sorted(a.begin(), a.end()))
ans = 0;
else if (a[0] == 1 || a[n - 1] == n)
ans =... |
1525 | C | Robot Collisions | There are $n$ robots driving along an OX axis. There are also two walls: one is at coordinate $0$ and one is at coordinate $m$.
The $i$-th robot starts at an integer coordinate $x_i~(0 < x_i < m)$ and moves either left (towards the $0$) or right with the speed of $1$ unit per second. No two robots start at the same co... | Notice that the robots that start at even coordinates can never collide with the robots that start at odd coordinates. You can see that if a robot starts at an even coordinate, it'll be at an even coordinate on an even second and at an odd coordinate on an odd second. Thus, we'll solve the even and the odd cases separa... | [
"data structures",
"greedy",
"implementation",
"sortings"
] | 2,000 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct bot{
int x, d;
};
int main() {
int t;
cin >> t;
forn(_, t){
int n, m;
scanf("%d%d", &n, &m);
vector<bot> a(n);
forn(i, n) scanf("%d", &a[i].x);
forn(i, n){
char c;
scanf(" %c", &c);
a[i].d... |
1525 | D | Armchairs | There are $n$ armchairs, numbered from $1$ to $n$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $\frac{n}{2}$.
For some reason, you would like to tell people to move from their armchairs to some other on... | Let's say that the starting position of people are $x_1, x_2, \dots, x_k$ (in sorted order) and ending positions of people are $y_1, y_2, \dots, y_k$ (also in sorted order). It's always optimal to match these starting and ending positions in sorted order: the leftmost starting position is matched with the leftmost endi... | [
"dp",
"flows",
"graph matchings",
"greedy"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
const int INF = int(1e9);
int main()
{
int n;
cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++)
cin >> a[i];
vector<int> pos;
for(int i = 0; i < n; i++)
if(a[i] == 1)
pos.push_back(i);
int k = pos.size();
vector<vector<int>> dp(n + 1, vector<int>... |
1525 | E | Assimilation IV | Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has $n$ cities. In order to conquer new lands he plans to build \textbf{one Monument in each city}. The game is turn-based and, since Monocarp is still amateur, he builds exactl... | Let $I(j)$ be the indicator function equal to $1$ if the $j$-th point is controlled by any city and $0$ otherwise. Then the expected number of controlled points $ans$ can be written as $E(\sum\limits_{j=1}^{m}{I(j)}) = \sum\limits_{j=1}^{m}{E(I(j))}$ (by linearity of expected value). The expected value of the indicator... | [
"combinatorics",
"dp",
"math",
"probabilities",
"two pointers"
] | 2,100 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
const int MOD = 998244353;
int norm(int a) {
while (a >= MOD)
a -= MOD;
while (a < 0)
a += M... |
1525 | F | Goblins And Gnomes | Monocarp plays a computer game called "Goblins and Gnomes". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.
The city consists of $n$ halls and $m$ one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall... | First of all, let's try to solve the following problem: given a DAG, cover its vertices with the minimum number of vertex-disjoint paths. Solving this problem allows us to calculate the number of goblins that can pillage all of the halls when the tunnel network is fixed. This problem is a fairly classical one; since th... | [
"brute force",
"dp",
"flows",
"graph matchings"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
const int N = 543;
const long long INF = (long long)(1e18);
struct Matching
{
int n1, n2;
vector<set<int>> g;
vector<int> mt, used;
void init()
{
mt = vector<int>(n2, -1);
}
int kuhn(int x)
{
if(used[x] == 1) return 0;
used[x] = 1;
... |
1526 | A | Mean Inequality | You are given an array $a$ of $2n$ \textbf{distinct} integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $2$ neighbours.
More formally, find an array $b$, such that:
- $b$ is a permutation of $a$.
- For every $i$ from $1$ to $2n$, $b_i \n... | Notice that the array size is even length. Usually in such problems, we would split the array into $2$ equal parts. Can you figure out what those $2$ parts are? We sort the array and split it into the big half and the small half. The main idea is that we can split the numbers into the two halves, the big half and small... | [
"constructive algorithms",
"sortings"
] | 800 | [(lambda n: (lambda arr : [print(f'{arr[i]} {arr[i+n]}', end = ' \n'[i==n-1]) for i in range(n)])(sorted(list(map(int,input().split())))))(int(input())) for _ in range(int(input()))] |
1526 | B | I Hate 1111 | You are given an integer $x$. Can you make $x$ by summing up some number of $11, 111, 1111, 11111, \ldots$? (You can use any number among them any number of times).
For instance,
- $33=11+11+11$
- $144=111+11+11+11$ | Read the name of the problem ;) $1111=11 \cdot 101$ All numbers other than $11$ and $111$ are useless. Notice that $1111=11 \cdot 100+11$ and similarly $11111=111 \cdot 100 + 11$. This implies that we can construct $1111$ and all bigger numbers using only $11$ and $111$. So it suffices to check whether we can construct... | [
"dp",
"math",
"number theory"
] | 1,400 | [(lambda n : print("YES" if (n >= 111*(n%11)) else "NO"))(int(input())) for _ in range(int(input()))] |
1526 | C2 | Potions (Hard Version) | \textbf{This is the hard version of the problem. The only difference is that in this version $n \leq 200000$. You can make hacks only if both versions of the problem are solved.}
There are $n$ potions in a line, with potion $1$ on the far left and potion $n$ on the far right. Each potion will increase your health by $... | Try dp! The dp states are position and number of potions drank. Speedup dp or use greedy for full solution. Let's consider a dynamic programming solution. Let $dp[i][k]$ be the maximum possible health achievable if we consider only the first $i$ potions, and $k$ is the total number of potions taken. The transition is a... | [
"data structures",
"greedy"
] | 1,600 | import heapq
H = []
n=int(input())
for i in list(map(int,input().split())):
tot = (tot+i if 'tot' in locals() or 'tot' in globals() else i)
tot -= ((heapq.heappush(H,i) if tot >= 0 else heapq.heappushpop(H,i)) or 0)
print(len(H)) |
1526 | D | Kill Anton | After rejecting $10^{100}$ data structure problems, Errorgorn is very angry at Anton and decided to kill him.
Anton's DNA can be represented as a string $a$ which only contains the characters "ANTON" (there are only $4$ distinct characters).
Errorgorn can change Anton's DNA into string $b$ which must be a \textbf{per... | The time it takes for Anton's body to revert the string is related to inversion number. We claim that in the optimal answer all characters of some type will appear consecutively. Consider the character at position $i$ in string $s$. We define $C_i$ as the position in which that character will be in string $t$. For $s=\... | [
"brute force",
"constructive algorithms",
"data structures",
"math",
"strings"
] | 2,200 | import itertools
TC=int(input())
m={"A":0,"N":1,"O":2,"T":3}
st="ANOT"
for _ in range(TC):
s=input()
arr=[]
for ch in s:
arr.append(m[ch])
cnt=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
cnt1=[0,0,0,0]
for i in arr:
for j in range(4):
cnt[j][i]+=cnt1[j]
cnt1[i]+=1
val=-1
best=[]
for perm in... |
1526 | E | Oolimry and Suffix Array | Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array.
More formally, given a suffix array of length $n$ and having an alphabet size $k$, count the number of strings that produce such a suffix array.
Let $s$ be a string of length $n$. Then the $i$-th suffix of $s$ is... | Try to solve the problem of the minimal $K$ needed to make a string with such a suffix array. First, let's consider a simpler problem. Is it possible to make a string with a certain suffix array given an alphabet size $k$. Consider two adjacent suffixes in the suffix array "xy" and "ab" where $b$ and $y$ are some strin... | [
"combinatorics",
"constructive algorithms",
"math"
] | 2,400 | MOD=998244353
n,k=map(int,input().split())
arr=list(map(int,input().split()))
pos=[0]*(n+1)
for i in range(n):
pos[arr[i]]=i
pos[n]=-1
cnt=0
for i in range(n-1):
if (pos[arr[i]+1]>pos[arr[i+1]+1]): cnt+=1
#k-cnt+n-1 choose n
num,denom=1,1
for i in range(n):
num=num*(k-cnt+n-1-i)%MOD
denom=denom*(i+1)%MOD
pr... |
1526 | F | Median Queries | \textbf{This is an interactive problem.}
There is a secret permutation $p$ ($1$-indexed) of numbers from $1$ to $n$. More formally, for $1 \leq i \leq n$, $1 \leq p[i] \leq n$ and for $1 \leq i < j \leq n$, $p[i] \neq p[j]$. \textbf{It is known that $p[1]<p[2]$}.
In $1$ query, you give $3$ \textbf{distinct} integers ... | Find elements $1$ and $2$ in $N+420$ queries. Find a pair $(a,b)$ such that $|p[b]-p[a]| \leq \frac{n}{3}-c$, where $c$ is some constant. The problem can be broken into $2$ main parts: Finding a pair $(a,b)$ such that $|p[a]-p[b]|$ is roughly less than a third. Finding elements $1$ and $2$ (actually we may find $N$ and... | [
"constructive algorithms",
"interactive",
"probabilities"
] | 3,000 | import sys, random
print = sys.stdout.write
input = sys.stdin.readline
def query(a, b, c):
print("? " + str(a+1) + " " + str(b+1) + " " + str(c+1) + "\n")
sys.stdout.flush()
return int(input())
def answer():
print("! " + " ".join([str(i) for i in ans]) + "\n")
sys.stdout.flush()
return int(in... |
1527 | A | And Then There Were K | Given an integer $n$, find the maximum value of integer $k$ such that the following condition holds:
\begin{center}
$n$ & ($n-1$) & ($n-2$) & ($n-3$) & ... ($k$) = $0$
\end{center}
where & denotes the bitwise AND operation. | Let $T =$ $n$ & ($n-1$) & ($n-2$) & ($n-3$) & ... ($k$) If there is at least one integer from $K$ to $N$ whose bit at the $i_{th}$ index is $0$, then the value of the $i_{th}$ bit in $T$ will also be $0$. We can easily observe that the $msb$ (Highest set bit in $n$) in $N$ will become $0$ for the first time when $K = 2... | [
"bitmasks"
] | 800 | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define pb push_back
#define ppb pop_back
#define endl '\n'
#define mii map<ll,ll>
#define msi map<string,ll>
#define mis map<ll, string>
#d... |
1527 | B1 | Palindrome Game (easy version) | \textbf{The only difference between the easy and hard versions is that the given string $s$ in the easy version is initially a palindrome, this condition is not always true for the hard version.}
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while ... | If the count of zeros in the string $s$ is even then Bob always win Proof Bob can restrict Alice from performing operation $2$ by making string $s$ palindrome (if Alice changes $s[i]$ to '1' then Bob will change $s[n-i+1]$ to '1'). However, when the last '0' is remaining, Bob will reverse the string, eventually forcing... | [
"constructive algorithms",
"games"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
#define int long long int
#define mp(a,b) make_pair(a,b)
#define vi vector<int>
#define mii map<int,int>
#define mpi map<pair<int,int>,int>
#define vp vector<pair<int,int> >
#define pb(a) push_back(a)
#define fr(i,n) for(i=0;i<n;i++)
#define rep(i,a,n) for(i=a;i<n;i++)
#defi... |
1527 | B2 | Palindrome Game (hard version) | \textbf{The only difference between the easy and hard versions is that the given string $s$ in the easy version is initially a palindrome, this condition is not always true for the hard version.}
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while ... | Solution 1: The case when $s$ is a palindrome is discussed in B1. Otherwise, Alice will win or the game will end with a draw. Proof If it is optimal for Alice to perform operation $1$ in the first move, she will perform it else she will perform operation $2$ forcing Bob to perform operation $1$ (which is not optimal ot... | [
"constructive algorithms",
"games"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
double pi = acos(-1);
#define _time_ 1.0 * clock() / CLOCKS_PER_SEC
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define all(a) a.begin(),a.end()
mt19937 rng(chrono::high_re... |
1527 | C | Sequence Pair Weight | The weight of a sequence is defined as the number of unordered pairs of indexes $(i,j)$ (here $i \lt j$) with same value ($a_{i} = a_{j}$). For example, the weight of sequence $a = [1, 1, 2, 2, 1]$ is $4$. The set of unordered pairs of indexes with same value are $(1, 2)$, $(1, 5)$, $(2, 5)$, and $(3, 4)$.
You are giv... | First of all, it can be proved that the maximum possible answer occurs when $n = 10^5$ and all the elements are identical which comes out to be of the order $4 \cdot 10^{18}$, which fits in the long long integer range, thus preventing overflow. The brute force approach is just to find the weight of each subarray and su... | [
"hashing",
"implementation",
"math"
] | 1,600 | t = int(input())
for j in range(t):
n = int(input())
a = list(map(int,input().split()))
value = {}
fa, ca = 0, 0
for i in range(n):
if a[i] in value:
ca += value[a[i]]
else:
value[a[i]]=0
value[a[i]] += i+1
fa += ca
print(fa) |
1527 | D | MEX Tree | You are given a tree with $n$ nodes, numerated from $0$ to $n-1$. For each $k$ between $0$ and $n$, inclusive, you have to count the number of unordered pairs $(u,v)$, $u \neq v$, such that the \textbf{MEX} of all the node labels in the shortest path from $u$ to $v$ (including end points) is $k$.
The \textbf{MEX} of a... | This problem can be solved with two pointer approach. We will use the following simple formula to evaluate the number of paths with MEX = i, $ans_i$ = (Number of paths with $MEX \ge i$) - (Number of paths with $MEX > i$). First we root the tree at node $0$ and calculate the subtree sizes using a basic subtree DP. Now w... | [
"combinatorics",
"dfs and similar",
"implementation",
"math",
"trees"
] | 2,400 | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define pb push_back
#define ppb pop_back
#define endl '\n'
#define mii map<ll,ll>
#define msi map<string,ll>
#define mis map<ll, string>
#d... |
1527 | E | Partition Game | You are given an array $a$ of $n$ integers. Define the cost of some array $t$ as follows:
$$cost(t) = \sum_{x \in set(t) } last(x) - first(x),$$
where $set(t)$ is the set of all values in $t$ without repetitions, $first(x)$, and $last(x)$ are the indices of the first and last occurrence of $x$ in $t$, respectively. I... | Let's use dynamic programming to solve this problem. Consider $dp[i][j]$ be the answer for prefix $j$ with $i$ subsegments. Transitions are fairly straightforward. Let $c[i][j]$ be the cost of subarray starting at $i^{th}$ index and ending at $j^{th}$ index. $dp[i][j] = \min\limits_{k \lt j}(dp[i-1][k] + c[k+1][j])$ If... | [
"binary search",
"data structures",
"divide and conquer",
"dp"
] | 2,500 | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define pb push_back
#define ppb pop_back
#define endl '\n'
#define mii map<ll,ll>
#define msi map<string,ll>
#define mis map<ll, string>
#d... |
1528 | A | Parsa's Humongous Tree | Parsa has a humongous tree on $n$ vertices.
On each vertex $v$ he has written two integers $l_v$ and $r_v$.
To make Parsa's tree look even more majestic, Nima wants to assign a number $a_v$ ($l_v \le a_v \le r_v$) to each vertex $v$ such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rat... | The solution is based on the fact that an optimal assignment for $a$ exists such that for each vertex $v$, $a_v \in {l_v, r_v}$. Proving this fact isn't hard, pick any assignment for $a$. Assume $v$ is a vertex in this assignment such that $a_v \notin {l_v, r_v}$. Let $p$ be the number of vertices $u$ adjacent to $v$ s... | [
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"trees"
] | 1,600 | // Call my Name and Save me from The Dark
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> pii;
#define SZ(x) (int) x.size()
#define F first
#define S second
const int N = 2e5 + 10;
ll dp[2][N... |
1528 | B | Kavi on Pairing Duty | Kavi has $2n$ points lying on the $OX$ axis, $i$-th of which is located at $x = i$.
Kavi considers all ways to split these $2n$ points into $n$ pairs. Among those, he is interested in \textbf{good} pairings, which are defined as follows:
Consider $n$ segments with ends at the points in correspondent pairs. The pairin... | Let $dp_i$ be the number of good pairings of $2i$ points. Clearly, the answer is $dp_n$. Lemma: Denote $x$ as the point matched with the point $1$. Notice that each point $p$ $(x < p \le 2n)$ belongs to a segment with length equal to $[1 , x]$'s length. Proof: Assume some point $p$ $(x < p \le 2n)$ is paired with a poi... | [
"combinatorics",
"dp",
"math"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
#define X first
#define Y second
#define endl '\n'
const int N = 1e6 + 10;
const int MOD = 998244353;
int n, dp[N], S;
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
... |
1528 | C | Trees of Tranquillity | Soroush and Keshi each have a labeled and rooted tree on $n$ vertices. Both of their trees are rooted from vertex $1$.
Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial gra... | Let's start with some observations. Take any clique $C$ in the memorial graph. Notice that the vertices of $C$ are a subset of a path from root to some leaf in Soroush's tree. So it's sufficient to solve the task for every leaf in Soroush's tree, specifically we should consider subsets of the paths starting from the ro... | [
"data structures",
"dfs and similar",
"greedy",
"trees"
] | 2,300 | #include<bits/stdc++.h>
#define lc (id * 2)
#define rc (id * 2 + 1)
#define md ((s + e) / 2)
#define dm ((s + e) / 2 + 1)
#define ln (e - s + 1)
using namespace std;
typedef long long ll;
const ll MXN = 3e5 + 10;
const ll MXS = MXN * 4;
ll n, timer, ans, Ans;
ll lazy[MXS], seg[MXS];
ll Stm[MXN], Ftm[MXN];
vector<ll> ... |
1528 | D | It's a bird! No, it's a plane! No, it's AaParsa! | There are $n$ cities in Shaazzzland, numbered from $0$ to $n-1$. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.
As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.
AaParsa has planted $m$ transpo... | Suppose we did normal dijkstra, the only case that might be missed is when we wait in a vertex for some time. To handle the 'waiting' concept, we can add $n$ fake edges, $i$-th of which is from the $i$-th vertex to the $(i+1 \mod n)$ -th vertex with weight equal to one. Note that unlike the cannons, fake edges do not r... | [
"constructive algorithms",
"graphs",
"shortest paths"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 600 + 5;
int n;
int dp[maxn];
bool mark[maxn];
vector<pair<int,int>> g[maxn];
int go[maxn];
int dis(int s, int t) {
if (s <= t)
return t - s;
return n - (s - t);
}
void dijkstra(int src) {
memset(dp, 63, sizeof dp);
m... |
1528 | E | Mashtali and Hagh Trees | Today is Mashtali's birthday! He received a \textbf{Hagh} tree from Haj Davood as his birthday present!
A directed tree is called a \textbf{Hagh} tree iff:
- The length of the longest directed path in it is exactly $n$.
- Every vertex has \textbf{at most three edges} attached to it independent of their orientation.
-... | Let $dp_i$ be the answer for all trees such that there exists a root and all edges are directed in the same direction from root and the root has at most $2$ children. We transition: $dp_i = dp_{i-1}+dp_{i-1} \cdot pdp_{i-2}+\frac{dp_{i-1} \cdot (dp_{i-1}+1)}{2}$ where $pdp_i = \sum_{j = 0}^{i}{dp_j}$. Then let $dp2_i$ ... | [
"combinatorics",
"dp",
"trees"
] | 2,900 | #include <bits/stdc++.h>
#pragma GCC optimize ("O2,unroll-loops")
//#pragma GCC optimize("no-stack-protector,fast-math")
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<pii, int> piii;
typedef pair<ll, ll> pll;
#define debug(x) cerr<<#x<<'='<<(x)<<endl;
#def... |
1528 | F | AmShZ Farm | To AmShZ, all arrays are equal, but some arrays are \textbf{more-equal} than others. Specifically, the arrays consisting of $n$ elements from $1$ to $n$ that can be turned into permutations of numbers from $1$ to $n$ by adding a non-negative integer to each element.
Mashtali \sout{who wants to appear in every problem ... | Consider the following problem: $n$ cars want to enter a parking lot one by one. The parking lot has $n$ slots numbered $1, 2 , \ldots , n$, the $i$-th of the $n$ cars wants to park in the $a_i$-th slot. When the $i$-th car drives in, it will park in the first empty slot $s$ such that $s \ge a_i$. An array $a$ is Good ... | [
"combinatorics",
"fft",
"math"
] | 3,300 | # include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <pii, int> ppi;
typedef pair <int, pii>... |
1529 | A | Eshag Loves Big Arrays | Eshag has an array $a$ consisting of $n$ integers.
Eshag can perform the following operation any number of times: choose some subsequence of $a$ and delete every element from it which is \textbf{strictly} larger than $AVG$, where $AVG$ is the average of the numbers in the chosen subsequence.
For example, if $a = [1 ,... | We state that every element except for the elements with the smallest value can be deleted. Proof: denote $MN$ as the minimum element (s) of the array $a$, in each operation pick $MN$ and some other element, say $X$, which is bigger than $MN$, since $AVG = \frac{X + MN}{2} < X$, then $X$ will be deleted. Doing this for... | [
"constructive algorithms",
"greedy",
"math"
] | 800 | // khodaya khodet komak kon
# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <pii, int> ... |
1529 | B | Sifid and Strange Subsequences | A sequence $(b_1, b_2, \ldots, b_k)$ is called \textbf{strange}, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $(i, j)$ with $1 \le i<j \le k$, we have $|a_i-a_j|\geq MAX$, where $MAX$ is the... | It's easy to prove that a strange subsequence can't contain more than one positive element. So it's optimal to pick all of the non-positive elements, now we can pick at most one positive element. Assume $x$ is the minimum positive element in the array. We can pick $x$ if no two elements in the already picked set such a... | [
"greedy",
"math",
"sortings"
] | 1,100 | // khodaya khodet komak kon
// Nightcall - London Grammer
# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <pii, int> ... |
1530 | A | Binary Decimal | Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $0$ or $1$. For example, $1\,010\,111$ is a binary decimal, while $10\,201$ and $787\,788$ are not.
Given a number $n$, you are asked to represent $n$ as a sum of some (not necessarily distinct) binary dec... | Let $d$ be the largest decimal digit of $n$. Note that we need at least $d$ binary decimals to represent $n$ as a sum. Indeed, if we only use $k < d$ binary decimals, no digit of the sum will ever exceed $k$. However, we need at least one digit equal to $d$. At the same time, it is easy to construct an answer with exac... | [
"greedy",
"math"
] | 800 | null |
1530 | B | Putting Plates | To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.
The table can be represented as a rectangle with height $h$ and width $w$, divided into $h \times w$ cells. Let $(i, j)$ denote the cell in the $i$-th row and the $j$-th column of the rectangle ($1 \le i \le ... | There are many ways to solve this problem and even more ways to get it accepted. Let's consider a provable solution that minimizes the amount of casework. We'll call a valid solution optimal if it has the largest possible number of plates. Claim. There exists an optimal solution that contains a plate in every corner of... | [
"constructive algorithms",
"implementation"
] | 800 | null |
1530 | C | Pursuit | You and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between $0$ and $100$ points, inclusive, for each stage, independently of other contestants.
Points received by contestants in different stages are used for forming overall contest result... | The first thing to notice is that since we're chasing Ilya and we want to reach his score as soon as possible, it only makes sense to add $100$'s to our scores and $0$'s to his. We can also notice that the answer never exceeds $n$. No matter how bad a stage is for us in terms of points, adding a single stage where we s... | [
"binary search",
"brute force",
"greedy",
"sortings"
] | 1,200 | null |
1530 | D | Secret Santa | Every December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.
$n$ employees numbered from $1$ to $n$ take part in the event. Each employee $i$ is assigned a different employee $b_i$, to which employee $i$ has to make a new year gift. Each employee is assigned to exactly... | Let $m$ be the number of different values among $a_i$ (that is, the number of distinct employees someone wishes to make a gift to). It's easy to see that the answer, $k$, can not exceed $m$: each employee mentioned in $a_i$ allows us to fulfill at most one wish. It turns out that $k$ can always be equal to $m$, and her... | [
"constructive algorithms",
"flows",
"graphs",
"greedy",
"math"
] | 1,600 | null |
1530 | E | Minimax | Prefix function of string $t = t_1 t_2 \ldots t_n$ and position $i$ in it is defined as the length $k$ of the longest proper (not equal to the whole substring) prefix of substring $t_1 t_2 \ldots t_i$ which is also a suffix of the same substring.
For example, for string $t = $ abacaba the values of the prefix function... | This problem required careful case analysis. First of all, if all characters of $s$ are the same, there is nothing to reorder: $t = s$, and $f(t) = |t| - 1$. Second, if the first character of $t$ appears somewhere else in the string, $f(t) \ge 1$. Otherwise, $f(t) = 0$. Thus, if some character has only one occurrence i... | [
"constructive algorithms",
"greedy",
"strings"
] | 2,100 | null |
1530 | F | Bingo | Getting ready for VK Fest 2021, you prepared a table with $n$ rows and $n$ columns, and filled each cell of this table with some event related with the festival that could either happen or not: for example, whether you will win a prize on the festival, or whether it will rain.
Forecasting algorithms used in VK have al... | Let $l_1, l_2, \ldots, l_{2n+2}$ denote the $2n+2$ possible lines that can be formed. Let $L_i$ denote the event that line $l_i$ is formed, and $\overline{L_i}$ denote the event that line $l_i$ is not formed (i.e., $P(L_i) + P(\overline{L_i}) = 1$). Let's find the probability that our table is not winning. It is equal ... | [
"bitmasks",
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,600 | null |
1530 | G | What a Reversal | You have two strings $a$ and $b$ of equal length $n$ consisting of characters 0 and 1, and an integer $k$.
You need to make strings $a$ and $b$ equal.
In one step, you can choose any substring of $a$ containing exactly $k$ characters 1 (and arbitrary number of characters 0) and reverse it. Formally, if $a = a_1 a_2 \... | First of all, the number of 1's in $a$ and $b$ must match. Let $c$ be the number of 1's in $a$. If $k = 0$ or $k > c$, we can not do a meaningful reversal, so we just check if $a = b$. If $k = c$, we can not change the contents of $a$ between the leftmost and the rightmost 1's, we can only reverse it and shift with reg... | [
"constructive algorithms"
] | 3,300 | null |
1530 | H | Turing's Award | Alan Turing is standing on a tape divided into cells that is infinite in both directions.
Cells are numbered with consecutive integers from left to right. Alan is initially standing in cell $0$. Every cell $x$ has cell $x - 1$ on the left and cell $x + 1$ on the right.
Each cell can either contain an integer or be em... | Let's look at Alan's moves in reverse. The process can be reformulated as follows. Initially, $a_n$ is written down into the cell where Alan is located. Then, for each $i$ from $n-1$ down to $1$, first Alan decides whether to stay or move to a neighboring cell, and then $a_i$ is written down into Alan's cell only if th... | [
"data structures",
"dp"
] | 3,400 | null |
1534 | A | Colour the Flag | Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).
You are given an $n \times m$ grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it ... | Observe that there are only two valid grids, one where the top left cell is "R" and one where it's "W". We can just test those two grids and see if they conform with the requirements. Time complexity: $\mathcal{O}(nm)$ | [
"brute force",
"implementation"
] | 800 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#ifdef LOCAL
template<typename T> void pr(T a){std::cerr<<a<<std::endl;}
template<typename T, typename... Args> void pr(T a, Args... args){std::cerr<<a<<' ',pr(args...);}
#else
template<typename... Args> void pr(Args... args){}
#endif
using namespace st... |
1534 | B | Histogram Ugliness | Little Dormi received a histogram with $n$ bars of height $a_1, a_2, \ldots, a_n$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.
To modify the histogram, Little Dormi is able to perform the following operation an... | It's only optimal to decrease a column $i$ if $a_i > a_{i+1}$ and $a_i > a_{i-1}$, as that would reduce the vertical length of the outline by $2$ while only costing $1$ operation. Additionally, observe that decreasing a column will never affect whether it is optimal to decrease any other column, so we can treat the ope... | [
"greedy",
"implementation",
"math"
] | 1,100 | #include "bits/stdc++.h"
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
template<typename T>
int sz(const T &a){return int(a.size());}
const int MN=4e5+2;
ll arr[MN];
int main(){
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int t;
cin>>t;
while(t--... |
1534 | C | Little Alawn's Puzzle | When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $2 \times n$ grid where each row is a permutation of the numbers $1,2,3,\ldots,n$.
The goal of Little Alawn's puzzle is to make sure no numbers on the s... | Define the "direction" of a column as the orientation of its numbers. Swapping the numbers in a column will flip its direction. Let's create a simple, undirected graph where the nodes are the $n$ columns on the puzzle and we draw one edge connecting it to the $2$ other columns that share a number with it. Notice that t... | [
"combinatorics",
"dp",
"dsu",
"graphs",
"math"
] | 1,300 | #include "bits/stdc++.h"
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
template<typename T>
int sz(const T &a){return int(a.size());}
const int MN=4e5+1;
const ll mod=1e9+7;
bool gone[MN];
vector<int> adj[MN];
int arr[MN][2];
void dfs(int loc){
gone[loc]=true;
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.