contest_id
stringlengths 1
4
| index
stringclasses 43
values | title
stringlengths 2
63
| statement
stringlengths 51
4.24k
| tutorial
stringlengths 19
20.4k
| tags
listlengths 0
11
| rating
int64 800
3.5k
⌀ | code
stringlengths 46
29.6k
⌀ |
|---|---|---|---|---|---|---|---|
1174
|
D
|
Ehab and the Expected XOR Problem
|
Given two integers $n$ and $x$, construct an array that satisfies the following conditions:
- for any element $a_i$ in the array, $1 \le a_i<2^n$;
- there is no \textbf{non-empty} subsegment with bitwise XOR equal to $0$ or $x$,
- its length $l$ should be maximized.
A sequence $b$ is a subsegment of a sequence $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
|
The main idea is to build the prefix-xor of the array, not the array itself, then build the array from it. Let the prefix-xor array be called $b$. Now, $a_l \oplus a_{l+1} \dots \oplus a_r=b_{l-1} \oplus b_{r}$. Thus, the problem becomes: construct an array such that no pair of numbers has bitwise-xor sum equal to 0 or $x$, and its length should be maximal. Notice that "no pair of numbers has bitwise-xor sum equal to 0" simply means "you can't use the same number twice". If $x \ge 2^n$, no pair of numbers less than $2^n$ will have bitwise-xor sum equal to $x$, so you can just use all the numbers from 1 to $2^n-1$ in any order. Otherwise, you can think of the numbers forming pairs, where each pair consists of 2 numbers with bitwise-xor sum equal to $x$. From any pair, if you add one number to the array, you can't add the other. However, the pairs are independent from each other: your choice in one pair doesn't affect any other pair. Thus, you can just choose either number in any pair and add them in any order you want. After you construct $b$, you can construct $a$ using the formula: $a_i=b_i \oplus b_{i-1}$. Time complexity: $O(2^n)$.
|
[
"bitmasks",
"constructive algorithms"
] | 1,900
|
"#include <iostream>\n#include <vector>\nusing namespace std;\nbool ex[(1<<18)];\nint main()\n{\n\tint n,x;\n\tscanf(\"%d%d\",&n,&x);\n\tex[0]=1;\n\tvector<int> v({0});\n\tfor (int i=1;i<(1<<n);i++)\n\t{\n\t\tif (ex[i^x])\n\t\tcontinue;\n\t\tv.push_back(i);\n\t\tex[i]=1;\n\t}\n\tprintf(\"%d\\n\",v.size()-1);\n\tfor (int i=1;i<v.size();i++)\n\tprintf(\"%d \",(v[i]^v[i-1]));\n}"
|
1174
|
E
|
Ehab and the Expected GCD Problem
|
Let's define a function $f(p)$ on a permutation $p$ as follows. Let $g_i$ be the greatest common divisor (GCD) of elements $p_1$, $p_2$, ..., $p_i$ (in other words, it is the GCD of the prefix of length $i$). Then $f(p)$ is the number of \textbf{distinct} elements among $g_1$, $g_2$, ..., $g_n$.
Let $f_{max}(n)$ be the maximum value of $f(p)$ among all permutations $p$ of integers $1$, $2$, ..., $n$.
Given an integers $n$, count the number of permutations $p$ of integers $1$, $2$, ..., $n$, such that $f(p)$ is equal to $f_{max}(n)$. Since the answer may be large, print the remainder of its division by $1000\,000\,007 = 10^9 + 7$.
|
Let's call the permutations from the statement good. For starters, we'll try to find some characteristics of good permutations. Let's call the first element in a good permutation $s$. Then, $s$ must have the maximal possible number of prime divisors. Also, every time the $gcd$ changes as you move along prefixes, you must drop only one prime divisor from it. That way, we guarantee we have as many distinct $gcd$s as possible. Now, there are 2 important observations concerning $s$: Observation #1: $s=2^x*3^y$ for some $x$ and $y$. In other words, only $2$ and $3$ can divide $s$. That's because if $s$ has some prime divisor $p$, you can divide it by $p$ and multiply it by $4$. That way, you'll have more prime divisors. Observation #2: $y \le 1$. That's because if $s=2^x*3^y$, and $y \ge 2$, you can instead replace it with $2^{x+3}*3^{y-2}$ (divide it by $9$ and multiply it by $8$), and you'll have more prime divisors. Now, we can create $dp[i][x][y]$, the number of ways to fill a good permutation up to index $i$ such that its $gcd$ is $2^x*3^y$. Let $f(x,y)=\lfloor \frac{n}{2^x*3^y} \rfloor$. It means the number of multiples of $2^x*3^y$ less than or equal to $n$. Here are the transitions: If your permutation is filled until index $i$ and its $gcd$ is $2^x*3^y$, you can do one of the following $3$ things upon choosing $p_{i+1}$: Add a multiple of $2^x*3^y$. That way, the $gcd$ won't change. There are $f(x,y)$ numbers you can add, but you already added $i$ of them, so: $dp[i+1][x][y]=dp[i+1][x][y]+dp[i][x][y]*(f(x,y)-i)$. Add a multiple of $2^x*3^y$. That way, the $gcd$ won't change. There are $f(x,y)$ numbers you can add, but you already added $i$ of them, so: $dp[i+1][x][y]=dp[i+1][x][y]+dp[i][x][y]*(f(x,y)-i)$. Reduce $x$ by $1$. To do that, you can add a multiple of $2^{x-1}*3^y$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x-1][y]=dp[i+1][x-1][y]+dp[i][x][y]*(f(x-1,y)-f(x,y))$. Reduce $x$ by $1$. To do that, you can add a multiple of $2^{x-1}*3^y$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x-1][y]=dp[i+1][x-1][y]+dp[i][x][y]*(f(x-1,y)-f(x,y))$. Reduce $y$ by $1$. To do that, you can add a multiple of $2^x*3^{y-1}$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x][y-1]=dp[i+1][x][y-1]+dp[i][x][y]*(f(x,y-1)-f(x,y))$. Reduce $y$ by $1$. To do that, you can add a multiple of $2^x*3^{y-1}$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x][y-1]=dp[i+1][x][y-1]+dp[i][x][y]*(f(x,y-1)-f(x,y))$. As for the base case, let $x=\lfloor log_2(n) \rfloor$. You can always start with $2^x$, so $dp[1][x][0]=1$. Also, if $2^{x-1}*3 \le n$, you can start with it, so $dp[1][x-1][1]=1$. The answer is $dp[n][0][0]$. Time complexity: $O(nlog(n))$.
|
[
"combinatorics",
"dp",
"math",
"number theory"
] | 2,500
|
"#include <iostream>\nusing namespace std;\n#define mod 1000000007\nint n,dp[1000005][21][2];\nint f(int x,int y)\n{\n\tint tmp=(1<<x);\n\tif (y)\n\ttmp*=3;\n\treturn n/tmp;\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tint p=0;\n\twhile ((1<<p)<=n)\n\tp++;\n\tp--;\n\tdp[1][p][0]=1;\n\tif ((1<<(p-1))*3<=n)\n\tdp[1][p-1][1]=1;\n\tfor (int i=1;i<n;i++)\n\t{\n\t\tfor (int x=0;x<=p;x++)\n\t\t{\n\t\t\tfor (int y=0;y<=1;y++)\n\t\t\t{\n\t\t\t\tdp[i+1][x][y]=(dp[i+1][x][y]+1LL*dp[i][x][y]*(f(x,y)-i))%mod;\n\t\t\t\tif (x)\n\t\t\t\tdp[i+1][x-1][y]=(dp[i+1][x-1][y]+1LL*dp[i][x][y]*(f(x-1,y)-f(x,y)))%mod;\n\t\t\t\tif (y)\n\t\t\t\tdp[i+1][x][y-1]=(dp[i+1][x][y-1]+1LL*dp[i][x][y]*(f(x,y-1)-f(x,y)))%mod;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"%d\",dp[n][0][0]);\n}"
|
1174
|
F
|
Ehab and the Big Finale
|
This is an interactive problem.
You're given a tree consisting of $n$ nodes, rooted at node $1$. A tree is a connected graph with no cycles.
We chose a hidden node $x$. In order to find this node, you can ask queries of two types:
- d $u$ ($1 \le u \le n$). We will answer with the distance between nodes $u$ and $x$. The distance between two nodes is the number of edges in the shortest path between them.
- s $u$ ($1 \le u \le n$). We will answer with the second node on the path from $u$ to $x$. However, there's a plot twist. If $u$ is \textbf{not} an ancestor of $x$, you'll receive "Wrong answer" verdict!
Node $a$ is called an ancestor of node $b$ if $a \ne b$ and the shortest path from node $1$ to node $b$ passes through node $a$. \textbf{Note that in this problem a node is not an ancestor of itself}.
Can you find $x$ in no more than $36$ queries? The hidden node is fixed in each test beforehand and does not depend on your queries.
|
Let $dep_a$ be the depth of node $a$ and $sz_a$ be the size of the subtree of node $a$. First, we'll query the distance between node 1 and node $x$ to know $dep_x$. The idea in the problem is to maintain a "search scope", some nodes such that $x$ is one of them, and to try to narrow it down with queries. From this point, I'll describe two solutions: Assume that your search scope is the subtree of some node $u$ (initially, $u$=1). How can we narrow it down efficiently? I'll pause here to add some definitions. The heavy child of a node $a$ is the child that has the maximal subtree size. The heavy path of node $a$ is the path that starts with node $a$ and every time moves to the heavy child of the current node. Now back to our algorithm. Let's get the heavy path of node $u$. Assume its other endpoint is node $v$. We know that a prefix of this path contains ancestors of node $x$. Let the deepest node in the path that is an ancestor of node $x$ be node $y$ (the last node in this prefix). I'll now add a drawing to help you visualize the situation. So, recapping, $u$ is the root of your search scope, $v$ is the endpoint of the heavy path starting from $u$, $x$ is the hidden node, and $y$ the last ancestor of $x$ in the heavy path. Notice that $y$ is $lca(x,v)$. Now, we know that $dist(x,v)=dep_x+dep_v-2*dep_y$. Since we know $dep_x$, and we know $dep_v$, we can query $dist(x,v)$ to find $dep_y$. Since all nodes in the path have different depths, that means we know $y$ itself! Observation #1: $dist(u,x)+dist(v,x)=dist(u,v)+2*dist(x,y)$. In both sides of the equation, every edge in the heavy path appears once, and every edge in the path from $x$ to $y$ appears twice. We know $dist(u,x)=dep_x-dep_u$. We also know $dist(u,v)=dep_v-dep_u$. Additionally, we can query $dist(v,x)$. From these 3 pieces of information and the equation above, we can find $dist(x,y)$. Observation #2: $dist(u,y)=dist(u,x)-dist(x,y)$. Now we know $dist(u,y)$. Since all nodes in the heavy path have different distances from node $u$, we know $y$ itself! Now, if $dep_x=dep_y$, $x=y$, so we found the answer. Otherwise, we know, by definition, that $y$ is an ancestor of $x$, so it's safe to use the second query type. Let the answer be node $l$. We can repeat the algorithm with $u=l$! How long will this algorithm take? Note that $l$ can't be the heavy child of $y$ (because $y$ is the last ancestor of $x$ in the heavy path), so $sz_l \le \lfloor\frac{sz_y}{2} \rfloor$, since it's well-known that only the heavy child can break that condition. So with only 2 queries, we managed to cut down at least half of our search scope! So this algorithm does no more than $34$ queries (actually $32$ under these constraints, but that's just a small technicality). As I said, assume we have a search scope. Let's get the centroid, $c$, of that search scope. If you don't know, the centroid is a node that, if removed, the tree will be broken down to components, and each component's size will be at most half the size of the original tree. Now, $c$ may and may not be an ancestor of $x$. How can we determine that? Let's query $dist(c,x)$. $c$ is an ancestor of $x$ if and only if $dep_c+dist(c,x)=dep_x$. Now, if $c$ is an ancestor of $x$, we can safely query the second node on the path between them. Let the answer be $s$, then its component will be the new search scope. What if $c$ isn't an ancestor of $x$? That means node $x$ can't be in the subtree of $c$, so it must be in the component of $c$'s parent. We'll make the component of $c$'s parent the new search scope! Every time, the size of our search scope is, at least, halved, so the solution does at most $36$ queries.
|
[
"constructive algorithms",
"divide and conquer",
"graphs",
"implementation",
"interactive",
"trees"
] | 2,400
|
"#include <iostream>\n#include <vector>\nusing namespace std;\nbool del[200005];\nvector<int> v[200005];\nint par[200005],sz[200005],dep[200005],depx;\nvoid pre(int node,int p)\n{\n\tfor (int u:v[node])\n\t{\n\t\tif (u!=p)\n\t\t{\n\t\t\tpar[u]=node;\n\t\t\tdep[u]=dep[node]+1;\n\t\t\tpre(u,node);\n\t\t}\n\t}\n}\nvector<int> h;\nint query(char c,int u)\n{\n\tprintf(\"%c %d\\n\",c,u);\n\tfflush(stdout);\n\tint ans;\n\tscanf(\"%d\",&ans);\n\treturn ans;\n}\nint getsz(int node,int p)\n{\n\tsz[node]=1;\n\tfor (int u:v[node])\n\t{\n\t\tif (!del[u] && u!=p)\n\t\tsz[node]+=getsz(u,node);\n\t}\n\treturn sz[node];\n}\nint find(int node,int p,int nn)\n{\n\tfor (int u:v[node])\n\t{\n\t\tif (!del[u] && u!=p && sz[u]>nn/2)\n\t\treturn find(u,node,nn);\n\t}\n\treturn node;\n}\nint dfs(int node)\n{\n\tgetsz(node,0);\n\tint c=find(node,0,sz[node]),d=query('d',c);\n\tif (!d)\n\treturn c;\n\tdel[c]=1;\n\tif (dep[c]+d==depx)\n\treturn dfs(query('s',c));\n\treturn dfs(par[c]);\n}\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=1;i<n;i++)\n\t{\n\t\tint a,b;\n\t\tscanf(\"%d%d\",&a,&b);\n\t\tv[a].push_back(b);\n\t\tv[b].push_back(a);\n\t}\n\tdepx=query('d',1);\n\tpre(1,0);\n\tprintf(\"! %d\\n\",dfs(1));\n\tfflush(stdout);\n}"
|
1175
|
A
|
From Hero to Zero
|
You are given an integer $n$ and an integer $k$.
In one step you can do one of the following moves:
- decrease $n$ by $1$;
- divide $n$ by $k$ if $n$ is divisible by $k$.
For example, if $n = 27$ and $k = 3$ you can do the following steps: $27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$.
You are asked to calculate the minimum number of steps to reach $0$ from $n$.
|
It's always optimal to divide by $k$ whenever it's possible, since dividing by $k$ equivalent to decreasing $n$ by $\frac{n}{k}(k - 1) \ge 1$. The only problem is that it's too slow to just subtract $1$ from $n$ each time, since in the worst case we can make $O(n)$ operations (Consider case $n = 10^{18}$ and $k = \frac{n}{2} + 1$). But if we'd look closer then we can just replace $x$ times of subtract $1$ with one subtraction of $x$. And to make $n$ is divisible by $k$ we should make $x = (n \mod{k})$ subtractions.
|
[
"implementation",
"math"
] | 900
|
#include<bits/stdc++.h>
using namespace std;
long long n, k;
int main(){
int tc;
cin >> tc;
for(int i = 0; i < tc; ++i){
cin >> n >> k;
long long res = 0;
while(n > 0){
if(n % k == 0){
n /= k;
++res;
}
else{
long long rem = n % k;
res += rem;
n -= rem;
}
}
cout << res << endl;
}
return 0;
}
|
1175
|
B
|
Catch Overflow!
|
You are given a function $f$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $x$. $x$ is an integer variable and can be assigned values from $0$ to $2^{32}-1$. The function contains three types of commands:
- for $n$ — for loop;
- end — every command between "for $n$" and corresponding "end" is executed $n$ times;
- add — adds 1 to $x$.
After the execution of these commands, value of $x$ is returned.
Every "for $n$" is matched with "end", thus the function is guaranteed to be valid. "for $n$" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of $x$! It means that the value of $x$ becomes greater than $2^{32}-1$ after some "add" command.
Now you run $f(0)$ and wonder if the resulting value of $x$ is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $x$.
|
One can notice (or actually derive using some maths) that the answer is the sum of products of nested for loops iterations for every "add" command. Let's learn to simulate that in linear complexity. Maintain the stack of multipliers: on "for $n$" push the top of stack multiplied by $n$ to the stack, on "end" pop the last value, on "add" add the top of the stack to the answer. The problem, however, is the values are really large. Notice that once you add the value greater or equal to $2^{32}$ to the answer, it immediately becomes "OVERFLOW!!!". Thus let's push not the real multiplier to the stack but min(multiplier, $2^{32}$). That way the maximum value you can achieve is about $2^{32} \cdot 50000$, which fits into the 64-bit integer. Overall complexity: $O(n)$.
|
[
"data structures",
"expression parsing",
"implementation"
] | 1,600
|
#include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
using namespace std;
const long long INF = 1ll << 32;
int main(){
int l;
cin >> l;
stack<long long> cur;
cur.push(1);
long long res = 0;
forn(_, l){
string t;
cin >> t;
if (t == "for"){
int x;
cin >> x;
cur.push(min(INF, cur.top() * x));
}
else if (t == "end"){
cur.pop();
}
else{
res += cur.top();
}
}
if (res >= INF)
cout << "OVERFLOW!!!" << endl;
else
cout << res << endl;
}
|
1175
|
C
|
Electrification
|
At first, there was a legend related to the name of the problem, but now it's just a formal statement.
You are given $n$ points $a_1, a_2, \dots, a_n$ on the $OX$ axis. Now you are asked to find such an integer point $x$ on $OX$ axis that $f_k(x)$ is minimal possible.
The function $f_k(x)$ can be described in the following way:
- form a list of distances $d_1, d_2, \dots, d_n$ where $d_i = |a_i - x|$ (distance between $a_i$ and $x$);
- sort list $d$ in non-descending order;
- take $d_{k + 1}$ as a result.
If there are multiple optimal answers you can print any of them.
|
First observation: $k$ closest points to any point $x$ form a contiguous subsegment $a_i, \dots, a_{i + k - 1}$, so $f_k(x) = \min(|a_{i - 1} - x|, |a_{i + k} - x|)$. Second observation: for any contiguous subsegment $a_i, \dots, a_{i + k - 1}$ all points $x$ this subsegment closest to, also form a contiguous segment $[l_i, r_i]$. And, because of the nature of $f_k(x)$, value of $f_k(x)$ is minimal in borders $l_i$ and $r_i$. So, all we need is to check all $l_i$ and $r_i$. But what is a value of $r_i$? It's such point, that $|a_i - r_i| \le |a_{i + k} - r_i|$, but $|a_i - (r_i + 1)| > |a_{i + k} - (r_i + 1)|$. So, it's just in the middle of segment $[a_i, a_{i + k}]$. Note, that $r_i + 1 = l_{i + 1}$ and $f_k(l_{i + 1}) \ge f_k(r_i)$, so it's enough to check only $r_i$-s. In result, all we need is to find minimal possible value $|a_{i + k} - a_i|$ and resulting $x = a_i + \frac{a_{i + k} - a_{i}}{2}$.
|
[
"binary search",
"brute force",
"greedy"
] | 1,600
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
int n, k;
vector<int> a;
inline bool read() {
if(!(cin >> n >> k))
return false;
a.resize(n);
fore(i, 0, n)
cin >> a[i];
return true;
}
inline void solve() {
pair<int, int> ans = {int(1e9) + 7, -1};
fore(i, 0, n - k) {
int dist = a[i + k] - a[i];
ans = min(ans, make_pair(dist, a[i] + dist / 2));
}
cout << ans.second << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cout << fixed << setprecision(15);
int tc; cin >> tc;
while(tc--) {
read();
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1175
|
D
|
Array Splitting
|
You are given an array $a_1, a_2, \dots, a_n$ and an integer $k$.
You are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $f(i)$ be the index of subarray the $i$-th element belongs to. Subarrays are numbered from left to right and from $1$ to $k$.
Let the cost of division be equal to $\sum\limits_{i=1}^{n} (a_i \cdot f(i))$. For example, if $a = [1, -2, -3, 4, -5, 6, -7]$ and we divide it into $3$ subbarays in the following way: $[1, -2, -3], [4, -5], [6, -7]$, then the cost of division is equal to $1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$.
Calculate the maximum cost you can obtain by dividing the array $a$ into $k$ non-empty consecutive subarrays.
|
Let's denote $S(k)$ as $\sum\limits_{i = k}^{n}{a_i}$ (just a suffix sum). And let $p_i$ be the position where starts the $i$-th subarray (obviously, $p_1 = 1$ and $p_i < p_{i + 1}$). Then we can make an interesting transformation: $\sum_{i=1}^{n}{a_i \cdot f(i)} = 1 \cdot (S(p_1) - S(p_2)) + 2 \cdot (S(p_2) - S(p_3)) + \dots + k \cdot (S(p_k) - 0) = \\ = S(p_1) + (2 - 1) S(p_2) + (3 - 2) S(p_3) + \dots + (k - (k - 1))) S(p_k) = \\ = S(p_1) + S(p_2) + S(p_3) + \dots + S(p_k).$ That's why we can just greedily take $k - 1$ maximum suffix sums along with sum of all array.
|
[
"greedy",
"sortings"
] | 1,900
|
#include<bits/stdc++.h>
using namespace std;
const int N = 300009;
int n, k;
int a[N];
int main(){
cin >> n >> k;
for(int i = 0; i < n; ++i)
cin >> a[i];
long long sum = 0;
vector <long long> v;
for(int i = n - 1; i >= 0; --i){
sum += a[i];
if(i > 0) v.push_back(sum);
}
long long res = sum;
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
for(int i = 0; i < k - 1; ++i)
res += v[i];
cout << res << endl;
return 0;
}
|
1175
|
E
|
Minimal Segment Cover
|
You are given $n$ intervals in form $[l; r]$ on a number line.
You are also given $m$ queries in form $[x; y]$. What is the minimal number of intervals you have to take so that every point (\textbf{not necessarily integer}) from $x$ to $y$ is covered by at least one of them?
If you can't choose intervals so that every point from $x$ to $y$ is covered, then print -1 for that query.
|
Let's take a look at a naive approach at first. That approach is greedy. Let's find such an interval which starts to the left or at $x$ and ends as much to the right as possible. Set $x$ to its right border. Continue until either no interval can be found or $y$ is reached. The proof basically goes like this. Let there be some smaller set of intervals which cover the query, these can be sorted by left border (obviously their left borders are pairwise distinct). Compare that set to the greedy one, take a look at the first position where best set's interval has his $r$ less than the greedy set's $r$. You can see that choosing interval greedily will still allow to have the rest of best set intervals, making the greedy choice optimal. Let's implement it in $O(nlogn + nm)$. For each position from $0$ to $5 \cdot 10^5$ you can precalculate the index of such an interval that it starts to the left or at this position and ends as much to the right as possible. To do this sort all intervals by their left border, then iterate over positions, while maintaining the maximum right border achieved by intervals starting to the left or at the current position. The query is now straightforward. Now there are two main ways to optimize it. You can do it binary lifting style: for each interval (or position) precalculate the index of the interval taken last after taking $2^k$ intervals greedily and use this data to answer queries in $O(\log n)$. You can also do it path compression style. Let's process the queries in the increasing order of their right borders. Now do greedy algorithm but for each interval you use remember the index of the last reached interval. Now the part with answering queries is $O(n + m)$ in total because each interval will be jumped from no more than once. Overall complexity: $O((n + m) \log n)$ / $O(n \log n + m \log m)$.
|
[
"data structures",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"implementation",
"trees"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int N = 500 * 1000 + 13;
int n, m;
pair<int, int> a[N], q[N];
int nxt[N];
int ans[N];
pair<int, int> p[N];
pair<int, int> get(int x, int r){
if (x == -1)
return make_pair(-1, -1);
if (a[x].y >= r)
return make_pair(x, 0);
auto res = get(p[x].x, r);
if (res.x == -1)
p[x] = make_pair(-1, -1);
else
p[x] = make_pair(res.x, p[x].y + res.y);
return p[x];
}
int main(){
scanf("%d%d", &n, &m);
forn(i, n)
scanf("%d%d", &a[i].x, &a[i].y);
forn(i, m)
scanf("%d%d", &q[i].x, &q[i].y);
sort(a, a + n);
int lst = 0;
pair<int, int> mx(0, -1);
forn(i, N){
while (lst < n && a[lst].x == i){
mx = max(mx, make_pair(a[lst].y, lst));
++lst;
}
nxt[i] = (mx.x <= i ? -1 : mx.y);
}
vector<int> perm(m);
iota(perm.begin(), perm.end(), 0);
sort(perm.begin(), perm.end(), [](int a, int b){
return q[a].y < q[b].y;
});
forn(i, n)
p[i] = make_pair(nxt[a[i].y], nxt[a[i].y] == -1 ? -1 : 1);
for (auto i : perm){
int x = nxt[q[i].x];
auto res = get(x, q[i].y).y;
ans[i] = (res == -1 ? -1 : res + 1);
}
forn(i, m)
printf("%d\n", ans[i]);
}
|
1175
|
F
|
The Number of Subpermutations
|
You have an array $a_1, a_2, \dots, a_n$.
Let's call some subarray $a_l, a_{l + 1}, \dots , a_r$ of this array a subpermutation if it contains all integers from $1$ to $r-l+1$ exactly once. For example, array $a = [2, 2, 1, 3, 2, 3, 1]$ contains $6$ subarrays which are subpermutations: $[a_2 \dots a_3]$, $[a_2 \dots a_4]$, $[a_3 \dots a_3]$, $[a_3 \dots a_5]$, $[a_5 \dots a_7]$, $[a_7 \dots a_7]$.
You are asked to calculate the number of subpermutations.
|
At first, let's represent permutations in the next form. We assign to all numbers from $1$ to $n$ random 128-bit strings, so the $i$-th number gets the string $h_i$. Then the permutation of length $len$ can be hashed as $h_1 \oplus h_2 \oplus \dots \oplus h_{len}$, where $\oplus$ is bitwise exclusive OR (for example, $0110 \oplus 1010 = 1100$). This representation is convenient because if we have two sets of numbers with a total number of elements equal to $len$ (let's represent them as $s_1, s_2, \dots s_m$ and $t_1, t_2, \dots t_k$, $k + m = len$), we can easily check whether their union is a permutation of length $len$ (condition $h_{s_1} \oplus h_{s_2} \oplus \dots \oplus h_{s_m} \oplus h_{t_1} \oplus h_{t_2} \oplus \dots h_{t_k} = h_1 \oplus h_2 \oplus \dots \oplus h_{len}$ must be hold). Let's denote $f(l, r)$ as $h_{a_l} \oplus h_{a_l + 1} \oplus \dots \oplus h_{a_r}$. Now let's iterate over position $i$ such that $a_i = 1$ and calculate the number of permutations that contain this element. To do it, let's iterate over the right boundary $r$ and suppose, that maximum element of permutation $len$ (and its length at the same time) is one of positions $i + 1, i + 2, \dots , r$. If it's true, then the subpermutation should be on the positions $r - len + 1, r - len + 2, \dots , r$. And to check that this segment is a subpermutation we should just compare $f(r - len + 1, r)$ and $h_1 \oplus h_2 \oplus \dots \oplus h_{len}$. Thus, we will calculate all permutations in which the position of the maximum is to the right of the position of the $1$. To calculate all permutations we need to reverse array $a$ and repeat this algorithm, and then add the number of ones in the array $a$.
|
[
"brute force",
"data structures",
"divide and conquer",
"hashing",
"math"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<long long, long long> pt;
const int N = int(3e5) + 99;
const pt zero = make_pair(0, 0);
int n;
int a[N];
pt hsh[N], sumHsh[N];
void upd(pt &a, pt b){
a.first ^= b.first;
a.second ^= b.second;
}
int calc(int pos){
set <int> sl, sr;
set<pt> s;
int r = pos + 1, l = pos - 1;
pt curr = hsh[0], curl = zero;
s.insert(zero);
sr.insert(0), sl.insert(0);
int res = 0;
while(r < n && !sr.count(a[r])){
sr.insert(a[r]);
upd(curr, hsh[a[r]]);
++r;
while(l >= 0 && !sl.count(a[l]) && a[l] < *sr.rbegin()){
sl.insert(a[l]);
upd(curl, hsh[a[l]]);
s.insert(curl);
--l;
}
pt need = sumHsh[*sr.rbegin()];
upd(need, curr);
if(s.count(need)) ++res;
}
return res;
}
int main() {
long long x = 0;
cin >> n;
for(int i = 0; i < n; ++i){
cin >> a[i];
--a[i];
x ^= a[i];
}
mt19937_64 rnd(time(NULL));
for(int i = 0; i < N; ++i){
hsh[i].first = rnd() ^ x;
hsh[i].second = rnd() ^ x;
sumHsh[i] = hsh[i];
if(i > 0) upd(sumHsh[i], sumHsh[i - 1]);
}
int res = 0;
for(int tc = 0; tc < 2; ++tc){
for(int i = 0; i < n; ++i)
if(a[i] == 0)
res += calc(i) + (tc == 0);
reverse(a, a + n);
}
cout << res << endl;
return 0;
}
|
1175
|
G
|
Yet Another Partiton Problem
|
You are given array $a_1, a_2, \dots, a_n$. You need to split it into $k$ subsegments (so every element is included in exactly one subsegment).
The weight of a subsegment $a_l, a_{l+1}, \dots, a_r$ is equal to $(r - l + 1) \cdot \max\limits_{l \le i \le r}(a_i)$. The weight of a partition is a total weight of all its segments.
Find the partition of minimal weight.
|
Important note: the author solution is using both linear Convex hull trick and persistent Li Chao tree. As mentioned in commentaries, applying the Divide-and-Conquer technique can help get rid of Li Chao tree. More about both structures you can read in this article. Let's try to write standard dp we can come up with (arrays will be 0-indexed). Let $dp[k][i]$ be the minimal weight if we splitted prefix of length $i$ in $k$ subsegments. Then we can calculate it as: $dp[k][i] = \min\limits_{0 \le j < i}(dp[k - 1][j] + (i - j) \cdot \max\limits_{j \le k < i}(a[k]))$ [1]. Maximums on segments are inconvenient, let's try to group segments $[j, i)$ by the value of $\max{}$. So, we can find such sequence of borders $j_0 = i - 1 > j_1 > j_2 > \dots$, where for each $j \in (j_{l + 1}, j_l]$ $\max\limits_{j \le k < i}(a[k]) = a[j_l]$. In other words, $j_0 = i - 1$ and $j_{l + 1}$ is the closest from the left position, where $a[j_{l + 1}] \ge a[j_l]$. Note, that we can maintain this sequence with stack of maximums. Ok, then for each interval $(j_{l + 1}, j_l]$ equation [1] transforms to: $\min_{j_{l+1} < j \le j_l}(dp[k - 1][j] + (i - j) \cdot a[j_l]) = a[j_l] \cdot i + \min_{j_{l+1} < j \le j_l}(-j \cdot a[j_l] + dp[k - 1][j]) = \\ = a[j_l] \cdot y + \min_{j_{l+1} < j \le j_l}(-j \cdot x + dp[k - 1][j]) |_{y = i, x = a[j_l]}.$ Why did we use variables $x$ and $y$? Because there are two problems: $y$ is needed because we iterate over $i$ and can't recalculate everything; $x$ is needed because sequence $j_l$ is changing over time, so do the $a[j_l]$. But what we can already see: we can maintain for each segment Convex hull with linear functions - so we can take $f_l = \min\limits_{j_{l+1} < j \le j_l}(\dots)$ in logarithmic time. Moreover, we can store values $a[j_l] \cdot y + f_l$ in other Convex hull to take minimum over all segments in logarithmic time. The problems arise when we try modificate structures while iterating $i$. Fortunately, segments $j_l$ change not at random, but according to stack of maximums. So all we should handle are: to merge segment on top of the stack $(j_1, j_0]$ with current segment $(j_0, i]$ (in case when $a[i] > a[j_0]$); to erase segment on top of the stack along with its value $a[j_0] \cdot y + f_0$; to insert new segment on top of the stack along with its value $a[j_0] \cdot y + f_0$. To handle the third type is easy, since all Convex hulls can insert elements. There will be at most $O(n)$ such operations on a single layer $k$ and we can ask value $f_0$ in $O(\log{n})$ and insert a line with $O(\log{A})$. To handle the second type is harder, but possible, since we can make Convex hull persistent and store its versions in the stack. Persistent Convex hull - persistent Li Chao tree. There will be also $O(nk)$ operations in total and they cost us $O(1)$. To handle the first type is trickiest part. Note, that all line coefficients of one convex hull are strictly lower than all line coefficients of the other. So, we can use linear Convex hulls to make insertions to back in amortized $O(1)$. But to merge efficiently, we should use Small-to-Large technique, that's why we should be able also push front in $O(1)$, and, moreover, still be able to ask minimum in $O(\log{n})$. And here comes the hack - $deque$ in C++, which can push/pop front/back in amortized $O(1)$ and also have random access iterator to make binary search possible. So, each element of every segment will be transfered $O(\log{n})$ times with cost of amortized $O(1)$ on a single layer $k$. In the end, result complexity is $O(n k (\log{C} + \log{n}))$. Space complexity is $O(n \log{A})$.
|
[
"data structures",
"divide and conquer",
"dp",
"geometry",
"two pointers"
] | 3,000
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) (int)((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<li, li> pt;
const int INF = int(1e9);
const li INF64 = li(1e9);
pt operator -(const pt &a, const pt &b) {
return {a.x - b.x, a.y - b.y};
}
li operator *(const pt &a, const pt &b) {
return a.x * b.x + a.y * b.y;
}
li operator %(const pt &a, const pt &b) {
return a.x * b.y - a.y * b.x;
}
pt rotate(const pt &p) {
return {-p.y, p.x};
}
struct LinearHull {
deque<pt> pts, vecs;
void addRight(const pt &l) {
while(!vecs.empty() && vecs.back() * (l - pts.back()) < 0) {
vecs.pop_back();
pts.pop_back();
}
if(!pts.empty())
vecs.push_back(rotate(l - pts.back()));
pts.push_back(l);
}
void addLeft(const pt &l) {
while(!vecs.empty() && vecs.front() * (l - pts.front()) < 0) {
vecs.pop_front();
pts.pop_front();
}
if(!pts.empty())
vecs.push_front(rotate(pts.front() - l));
pts.push_front(l);
}
li getMin(const pt &x) {
auto it = lower_bound(vecs.begin(), vecs.end(), x, [](const pt &a, const pt &b) {
return a % b > 0;
});
return x * pts[it - vecs.begin()];
}
};
typedef unique_ptr<LinearHull> pHull;
void mergeHulls(pHull &a, pHull &b) {
if(sz(b->pts) >= sz(a->pts)) {
for(auto &p : a->pts)
b->addRight(p);
} else {
for(auto it = b->pts.rbegin(); it != b->pts.rend(); it++)
a->addLeft(*it);
swap(a, b);
}
}
const int M = 1000 * 1000 + 555;
int szn = 0;
struct node {
pt line;
node *l, *r;
node() : line(), l(nullptr), r(nullptr) {}
node(pt line, node *l, node *r) : line(move(line)), l(l), r(r) {}
} nodes[M];
typedef node* tree;
tree getNode(const pt &line, tree l, tree r) {
assert(szn < M);
nodes[szn] = node(line, l, r);
return &nodes[szn++];
}
tree copy(tree v) {
if(v == nullptr) return v;
return getNode(v->line, v->l, v->r);
}
li f(const pt &line, int x) {
return line * pt{x, 1};
}
tree addLine(tree v, int l, int r, pt line) {
if(!v)
return getNode(line, nullptr, nullptr);
int mid = (l + r) >> 1;
bool lf = f(line, l) < f(v->line, l);
bool md = f(line, mid) < f(v->line, mid);
if(md)
swap(v->line, line);
if(l + 1 == r)
return v;
else if(lf != md)
v->l = addLine(copy(v->l), l, mid, line);
else
v->r = addLine(copy(v->r), mid, r, line);
return v;
}
li getMin(tree v, int l, int r, int x) {
if(!v) return INF64;
if(l + 1 == r)
return f(v->line, x);
int mid = (l + r) >> 1;
if(x < mid)
return min(f(v->line, x), getMin(v->l, l, mid, x));
else
return min(f(v->line, x), getMin(v->r, mid, r, x));
}
int n, k;
vector<li> a;
inline bool read() {
if(!(cin >> n >> k))
return false;
a.resize(n);
fore(i, 0, n)
cin >> a[i];
return true;
}
struct state {
int pos;
pHull hull;
tree v;
state() : pos(-1), hull(nullptr), v(nullptr) {}
};
vector<li> d[2];
inline void solve() {
int maxn = (int)*max_element(a.begin(), a.end()) + 3;
fore(k, 0, 2)
d[k].resize(n + 1, INF64);
d[0][0] = 0;
fore(_k, 1, k + 1) {
szn = 0;
int ck = _k & 1;
int nk = ck ^ 1;
vector< state > st;
fore(i, 0, sz(d[ck])) {
d[ck][i] = INF64;
if(!st.empty())
d[ck][i] = getMin(st.back().v, 0, maxn, i);
if(i >= sz(a))
continue;
state curVal;
curVal.pos = i;
curVal.hull = make_unique<LinearHull>();
curVal.hull->addRight({-i, d[nk][i]});
curVal.v = nullptr;
while(!st.empty() && a[st.back().pos] < a[i]) {
mergeHulls(st.back().hull, curVal.hull);
st.pop_back();
}
if(!st.empty())
curVal.v = st.back().v;
li val = curVal.hull->getMin({a[i], 1});
curVal.v = addLine(copy(curVal.v), 0, maxn, {a[i], val});
st.push_back(move(curVal));
}
}
cout << d[k & 1][n] << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1176
|
A
|
Divide it!
|
You are given an integer $n$.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
- Replace $n$ with $\frac{n}{2}$ if $n$ is divisible by $2$;
- Replace $n$ with $\frac{2n}{3}$ if $n$ is divisible by $3$;
- Replace $n$ with $\frac{4n}{5}$ if $n$ is divisible by $5$.
For example, you can replace $30$ with $15$ using the first operation, with $20$ using the second operation or with $24$ using the third operation.
Your task is to find the minimum number of moves required to obtain $1$ from $n$ or say that it is impossible to do it.
You have to answer $q$ independent queries.
|
What if the given number $n$ cannot be represented as $2^{cnt_2} \cdot 3^{cnt_3} \cdot 5^{cnt_5}$? It means that the answer is -1 because all actions we can do are: remove one power of two, remove one power of three and add one power of two, and remove one power of five and add two powers of two. So if the answer is not -1 then it is $cnt_2 + 2cnt_3 + 3cnt_5$. If this formula isn't pretty clear for you, you can just simulate the process, performing actions from third to first.
|
[
"brute force",
"greedy",
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
long long n;
cin >> n;
int cnt2 = 0, cnt3 = 0, cnt5 = 0;
while (n % 2 == 0) {
n /= 2;
++cnt2;
}
while (n % 3 == 0) {
n /= 3;
++cnt3;
}
while (n % 5 == 0) {
n /= 5;
++cnt5;
}
if (n != 1) {
cout << -1 << endl;
} else {
cout << cnt2 + cnt3 * 2 + cnt5 * 3 << endl;
}
}
return 0;
}
|
1176
|
B
|
Merge it!
|
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots , a_n$.
In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $[2, 1, 4]$ you can obtain the following arrays: $[3, 4]$, $[1, 6]$ and $[2, 5]$.
Your task is to find the maximum possible number of elements divisible by $3$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.
You have to answer $t$ independent queries.
|
Let $cnt_i$ be the number of elements of $a$ with the remainder $i$ modulo $3$. Then the initial answer can be represented as $cnt_0$ and we have to compose numbers with remainders $1$ and $2$ somehow optimally. It can be shown that the best way to do it is the following: firstly, while there is at least one remainder $1$ and at least one remainder $2$, let's compose them into one $0$. After this, at least one of the numbers $cnt_1, cnt_2$ will be zero, then we have to compose remaining numbers into numbers divisible by $3$. If $cnt_1 = 0$ then the maximum remaining number of elements we can obtain is $\lfloor\frac{cnt_2}{3}\rfloor$ (because $2 + 2 + 2 = 6$), and in the other case ($cnt_2 = 0)$ the maximum number of elements is $\lfloor\frac{cnt_1}{3}\rfloor$ (because $1 + 1 + 1 = 3$).
|
[
"math"
] | 1,100
|
#include<bits/stdc++.h>
using namespace std;
int t, n;
int cnt[3];
int main(){
cin >> t;
for(int tc = 0; tc < t; ++tc){
memset(cnt, 0, sizeof cnt);
cin >> n;
for(int i = 0; i < n; ++i){
int x;
cin >> x;
++cnt[x % 3];
}
int res = cnt[0];
int mn = min(cnt[1], cnt[2]);
res += mn;
cnt[1] -= mn, cnt[2] -= mn;
res += (cnt[1] + cnt[2]) / 3;
cout << res << endl;
}
return 0;
}
|
1176
|
C
|
Lose it!
|
You are given an array $a$ consisting of $n$ integers. Each $a_i$ is one of the six following numbers: $4, 8, 15, 16, 23, 42$.
Your task is to remove the minimum number of elements to make this array \textbf{good}.
An array of length $k$ is called \textbf{good} if $k$ is divisible by $6$ and it is possible to split it into $\frac{k}{6}$ \textbf{subsequences} $4, 8, 15, 16, 23, 42$.
Examples of good arrays:
- $[4, 8, 15, 16, 23, 42]$ (the whole array is a required sequence);
- $[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements);
- $[]$ (\textbf{the empty array is good}).
Examples of bad arrays:
- $[4, 8, 15, 16, 42, 23]$ (the order of elements should be exactly $4, 8, 15, 16, 23, 42$);
- $[4, 8, 15, 16, 23, 42, 4]$ (the length of the array is not divisible by $6$);
- $[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence).
|
Let $cnt_1$ be the number of subsequences $[4]$, $cnt_2$ be the number of subsequences $[4, 8]$, $cnt_3$ - the number of subsequences $[4, 8, 15]$ and so on, and $cnt_6$ is the number of completed subsequences $[4, 8, 15, 16, 23, 42]$. Let's iterate over all elements of $a$ in order from left to right. If the current element is $4$ then let's increase $cnt_1$ by one (we staring the new subsequence). Otherwise it is always better to continue some existing subsequence (just because why not?). If the current element is $8$ then we can continue some subsequence $[4]$, if it is $16$ then we can continue some subsequence $[4, 8, 15]$ and the same for remaining numbers. Let $pos$ be the $1$-indexed position of the current element of $a$ in list $[4, 8, 15, 16, 23, 42]$. Then the case $pos = 1$ is described above, and in other case ($pos > 1$) if $cnt_{pos - 1} > 0$ then let's set $cnt_{pos - 1} := cnt_{pos - 1} - 1$ and $cnt_{pos} := cnt_{pos} + 1$ (we continue some of existing subsequences). The answer can be calculated as $n - 6 cnt_{6}$ after all $n$ iterations.
|
[
"dp",
"greedy",
"implementation"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
vector<int> p({4, 8, 15, 16, 23, 42});
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
a[i] = lower_bound(p.begin(), p.end(), a[i]) - p.begin();
}
vector<int> seq(6);
for (int i = 0; i < n; ++i) {
if (a[i] == 0) {
++seq[0];
} else {
if (seq[a[i] - 1] > 0) {
--seq[a[i] - 1];
++seq[a[i]];
}
}
}
cout << n - seq[5] * 6 << endl;
return 0;
}
|
1176
|
D
|
Recover it!
|
Authors guessed an array $a$ consisting of $n$ integers; each integer is not less than $2$ and not greater than $2 \cdot 10^5$. You don't know the array $a$, but you know the array $b$ which is formed from it with the following sequence of operations:
- Firstly, let the array $b$ be equal to the array $a$;
- Secondly, for each $i$ from $1$ to $n$:
- if $a_i$ is a \textbf{prime} number, then one integer $p_{a_i}$ is appended to array $b$, where $p$ is an infinite sequence of prime numbers ($2, 3, 5, \dots$);
- otherwise (if $a_i$ is not a \textbf{prime} number), the greatest divisor of $a_i$ which is not equal to $a_i$ is appended to $b$;
- Then the obtained array of length $2n$ is shuffled and given to you in the input.
Here $p_{a_i}$ means the $a_i$-th prime number. The first prime $p_1 = 2$, the second one is $p_2 = 3$, and so on.
Your task is to recover \textbf{any} suitable array $a$ that forms the given array $b$. It is guaranteed that the answer exists (so the array $b$ is obtained from some suitable array $a$). If there are multiple answers, you can print any.
|
Firstly, let's generate first $199999$ primes. It can be done in $O(n \sqrt{n})$ almost naively (just check all elements in range $[2; 2750131]$). It also can be done with Eratosthenes sieve in $O(n)$ or $O(n \log \log n)$. We also can calculate for each number in this range the maximum its divisor non-equal to it (if this number is not a prime). And in other case we can calculate the index of this prime. Using all this information we can restore the array $a$. Let's maintain a multiset (a set in which multiple copies of the same element are allowed) of all elements in $b$. While it is not empty, let's take the maximum element from this set $mx$. If it is prime (we can check it using the information calculated earlier) then it is some $p_{a_i}$. Let's find the index of this prime ($a_i$) using calculated information, remove this element and $a_i$, push $a_i$ in $a$ and continue. Otherwise this element is not a prime and then it is some $a_i$. Let's remove it and its maximum divisor non-equal to it from the multiset, push $a_i$ in $a$ and continue.
|
[
"dfs and similar",
"graphs",
"greedy",
"number theory",
"sortings"
] | 1,800
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 3 * 1000 * 1000 + 13;
int lst[N];
int num[N];
void sieve(){
forn(i, N) lst[i] = i;
for (int i = 2; i < N; ++i){
if (lst[i] != i){
lst[i] = i / lst[i];
continue;
}
for (long long j = i * 1ll * i; j < N; j += i)
lst[j] = min(lst[j], i);
}
int cur = 0;
for (int i = 2; i < N; ++i) if (lst[i] == i)
num[i] = ++cur;
}
int cnt[N];
int main() {
int n;
scanf("%d", &n);
forn(i, 2 * n){
int x;
scanf("%d", &x);
++cnt[x];
}
sieve();
vector<int> res;
for (int i = N - 1; i >= 0; --i){
while (cnt[i] > 0){
if (lst[i] == i){
--cnt[num[i]];
res.push_back(num[i]);
}
else{
--cnt[lst[i]];
res.push_back(i);
}
--cnt[i];
}
}
for (auto it : res)
printf("%d ", it);
return 0;
}
|
1176
|
E
|
Cover it!
|
You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose \textbf{at most} $\lfloor\frac{n}{2}\rfloor$ vertices in this graph so \textbf{each} unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.
It is guaranteed that the answer exists. If there are multiple answers, you can print any.
You will be given multiple independent queries to answer.
|
Firstly, let's run bfs on the given graph and calculate distances for all vertices. In fact, we don't need distances, we need their parities. The second part is to find all vertices with an even distance, all vertices with and odd distance, and print the smallest by size part. Why is it always true? Firstly, it is obvious that at least one of these sizes will not exceed $\lfloor\frac{n}{2}\rfloor$. And secondly, because we are checking just parities of distances, it is obvious that each vertex of some parity is connected with at least one vertex of the opposite parity (because it has this parity from some vertex of the opposite parity).
|
[
"dfs and similar",
"dsu",
"graphs",
"shortest paths",
"trees"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n, m;
vector<int> d;
vector<vector<int>> g;
void bfs(int s) {
d = vector<int>(n, INF);
d[s] = 0;
queue<int> q;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto to : g[v]) {
if (d[to] == INF) {
d[to] = d[v] + 1;
q.push(to);
}
}
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
for (int tc = 0; tc < t; ++tc){
cin >> n >> m;
g = vector<vector<int>>(n);
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
--x, --y;
g[x].push_back(y);
g[y].push_back(x);
}
bfs(0);
vector<int> even, odd;
for (int i = 0; i < n; ++i) {
if (d[i] & 1) odd.push_back(i);
else even.push_back(i);
}
if (even.size() < odd.size()) {
cout << even.size() << endl;
for (auto v : even) cout << v + 1 << " ";
} else {
cout << odd.size() << endl;
for (auto v : odd) cout << v + 1 << " ";
}
cout << endl;
}
return 0;
}
|
1176
|
F
|
Destroy it!
|
You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.
The boss battle consists of $n$ turns. During each turn, you will get several cards. Each card has two parameters: its cost $c_i$ and damage $d_i$. You may play some of your cards during each turn in some sequence (you choose the cards and the exact order they are played), as long as \textbf{the total cost of the cards you play during the turn does not exceed $3$}. After playing some (possibly zero) cards, you end your turn, and \textbf{all cards you didn't play are discarded}. Note that you can use each card \textbf{at most once}.
Your character has also found an artifact that boosts the damage of some of your actions: every $10$-th card you play deals double damage.
What is the maximum possible damage you can deal during $n$ turns?
|
The first (and crucial) observation is that we don't need all the cards that we get during each turn. In fact, since the total cost is limited to $3$, we may leave three best cards of cost $1$, one best card of cost $2$ and one best card of cost $3$, and all other cards may be discarded. So, the problem is reduced: we get only $5$ cards each turn. The problem may be solved with dynamic programming: $dp_{x, y}$ is the maximum damage we may deal if we played $x$ turns and the last card we played had remainder $y$ modulo $10$. Processing each turn may be done with auxiliary dp: $z_{c, f}$ - the maximum damage we can deal during the turn if we play $c$ cards, and $f$ denotes whether some card (there will be only one such card, obviously) deals double damage. To calculate this auxiliary dp, we may do almost anything since we are limited to $5$ cards during each turn. It is possible to calculate it in a fast way using some casework, but it is easier, for example, to try all possible permutations of $5$ cards and play some prefix of a fixed permutation. By combining these two techniques, we get a solution.
|
[
"dp",
"implementation",
"sortings"
] | 2,100
|
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long li;
const li INF64 = li(1e18);
const int N = 200043;
vector<int> cards[N][4];
li dp[N][10];
int n;
li dp2[4][2];
int main()
{
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
for(int i = 0; i < N; i++)
for(int j = 0; j < 10; j++)
dp[i][j] = -INF64;
dp[0][0] = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int k;
scanf("%d", &k);
for (int j = 0; j < k; j++)
{
int c, d;
scanf("%d %d", &c, &d);
cards[i][c].push_back(d);
}
}
for (int i = 0; i < n; i++)
{
for (int j = 1; j <= 3; j++)
{
int s = (j == 1 ? 3 : 1);
sort(cards[i][j].begin(), cards[i][j].end());
reverse(cards[i][j].begin(), cards[i][j].end());
while (cards[i][j].size() > s)
cards[i][j].pop_back();
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 4; j++)
for (int k = 0; k < 2; k++)
dp2[j][k] = -INF64;
dp2[0][0] = 0;
vector<pair<int, int> > cur;
for (int j = 1; j <= 3; j++)
for (auto x : cards[i][j])
cur.push_back(make_pair(j, x));
sort(cur.begin(), cur.end());
do
{
int mana = 3;
li score = 0;
li mx = 0;
int cnt = 0;
for (auto x : cur)
{
cnt++;
if (mana < x.first)
break;
mana -= x.first;
mx = max(mx, li(x.second));
score += x.second;
dp2[cnt][0] = max(dp2[cnt][0], score);
dp2[cnt][1] = max(dp2[cnt][1], score + mx);
}
} while (next_permutation(cur.begin(), cur.end()));
for(int j = 0; j < 10; j++)
for (int k = 0; k <= 3; k++)
{
int nxt = (j + k) % 10;
int f = (j + k >= 10 ? 1 : 0);
dp[i + 1][nxt] = max(dp[i + 1][nxt], dp[i][j] + dp2[k][f]);
}
}
li ans = 0;
for (int i = 0; i <= 9; i++)
ans = max(ans, dp[n][i]);
printf("%lld\n", ans);
return 0;
}
|
1178
|
A
|
Prime Minister
|
Alice is the leader of the State Refactoring Party, and she is about to become the prime minister.
The elections have just taken place. There are $n$ parties, numbered from $1$ to $n$. The $i$-th party has received $a_i$ seats in the parliament.
\textbf{Alice's party has number $1$}. In order to become the prime minister, she needs to build a coalition, consisting of her party and possibly some other parties. There are two conditions she needs to fulfil:
- The total number of seats of all parties in the coalition must be a strict majority of all the seats, i.e. it must have \textbf{strictly more than half} of the seats. For example, if the parliament has $200$ (or $201$) seats, then the majority is $101$ or more seats.
- Alice's party must have \textbf{at least $2$ times more} seats than any other party in the coalition. For example, to invite a party with $50$ seats, Alice's party must have at least $100$ seats.
For example, if $n=4$ and $a=[51, 25, 99, 25]$ (note that Alice'a party has $51$ seats), then the following set $[a_1=51, a_2=25, a_4=25]$ can create a coalition since both conditions will be satisfied. However, the following sets will not create a coalition:
- $[a_2=25, a_3=99, a_4=25]$ since Alice's party is not there;
- $[a_1=51, a_2=25]$ since coalition should have a strict majority;
- $[a_1=51, a_2=25, a_3=99]$ since Alice's party should have \textbf{at least $2$ times more} seats than any other party in the coalition.
\textbf{Alice does not have to minimise the number of parties in a coalition.} If she wants, she can invite as many parties as she wants (as long as the conditions are satisfied). If Alice's party has enough people to create a coalition on her own, she can invite no parties.
Note that Alice can either invite a party as a whole or not at all. It is \textbf{not possible} to invite only some of the deputies (seats) from another party. In other words, if Alice invites a party, she invites \textbf{all} its deputies.
Find and print any suitable coalition.
|
Ignore the parties that have more than half of Alice's party seats. For all other parties it is never disadvantageous to include them in the coalition, so we might as well take all of them. If the resulting number of seats is a majority, we output all involved parties, otherwise the answer is $0$. The complexity is $\mathcal O(n)$.
|
[
"greedy"
] | 800
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
int N; cin >> N;
vector<int> A(N); for (int&a:A) cin >> a;
vector<int> P{1};
int rest = 0, cur = A[0];
for (int i = 1; i < N; ++i) {
if (A[i] <= A[0]/2) {
cur += A[i];
P.push_back(i+1);
} else {
rest += A[i];
}
}
if (cur > rest) {
cout << P.size() << endl;
for (int i = 0; i < P.size(); ++i) cout << P[i] << " \n"[i==P.size()-1];
} else {
cout << 0 << endl;
}
}
|
1178
|
B
|
WOW Factor
|
Recall that string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly zero or all) characters. For example, for the string $a$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".
The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead.
Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w":
- "{\underline{\textbf{vv}}vv}"
- "{v\underline{\textbf{vv}}v}"
- "{vv\underline{\textbf{vv}}}"
For example, the wow factor of the word "vvvovvv" equals to four because there are four wows:
- "{\underline{\textbf{vv}}v\underline{\textbf{o}\textbf{vv}}v}"
- "{\underline{\textbf{vv}}v\underline{\textbf{o}}v\underline{\textbf{vv}}}"
- "{v\underline{\textbf{vv}\textbf{o}\textbf{vv}}v}"
- "{v\underline{\textbf{vv}\textbf{o}}v\underline{\textbf{vv}}}"
Note that the subsequence "{\underline{\textbf{v}}v\underline{\textbf{v}\textbf{o}\textbf{vv}}v}" does not count towards the wow factor, as the "v"s have to be consecutive.
For a given string $s$, compute and output its wow factor. Note that it is \textbf{not} guaranteed that it is possible to get $s$ from another string replacing "w" with "vv". For example, $s$ can be equal to "vov".
|
We find all maximal blocks of vs. If there are $k$ of them, we replace the block with $k-1$ copies of w. After that, we can use a simple DP for finding the number of subsequences equal to wow. Complexity $\mathcal O(n)$.
|
[
"dp",
"strings"
] | 1,300
|
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
int main() {
string S; cin >> S;
ll a = 0, b = 0, c = 0;
for (int i = 0; i < S.size(); ++i) {
if (S[i] == 'o') {
b += a;
} else if (i > 0 && S[i-1] == 'v') {
a++;
c += b;
}
}
cout << c << endl;
}
|
1178
|
C
|
Tiles
|
Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor — a square tile that is diagonally split into white and black part as depicted in the figure below.
The dimension of this tile is perfect for this kitchen, as he will need exactly $w \times h$ tiles without any scraps. That is, the width of the kitchen is $w$ tiles, and the height is $h$ tiles. As each tile can be rotated in one of four ways, he still needs to decide on how exactly he will tile the floor. There is a single aesthetic criterion that he wants to fulfil: two adjacent tiles must not share a colour on the edge — i.e. one of the tiles must have a white colour on the shared border, and the second one must be black.
\begin{center}
The picture on the left shows one valid tiling of a $3 \times 2$ kitchen. The picture on the right shows an invalid arrangement, as the bottom two tiles touch with their white parts.
\end{center}
Find the number of possible tilings. As this number may be large, output its remainder when divided by $998244353$ (a prime number).
|
Observe that for a fixed pair of tiles $(i-1, j)$ and $(i, j-1)$ there is exactly one way of placing a tile at $(i, j)$ that satisfies the conditions. As a result, when all tiles $(1,i)$ and $(j,1)$ are placed, the rest is determined uniquely. We only need to count the number of ways to tile the first row and first column. There are four ways of placing the tile on $(1,1)$. After that, each tile in the first row or first column has exactly two ways of being placed. The answer is $2^{w + h}$. The complexity is $\mathcal O(w+h)$ or $\mathcal O(\log w + \log h)$ if we use binary exponentiation. Bonus: Hexagonal tiles and hexagonal kitchen.
|
[
"combinatorics",
"greedy",
"math"
] | 1,300
|
#include <iostream>
using namespace std;
constexpr int MOD = 998244353;
int main() {
int R, C; cin >> R >> C;
int X = 1;
while (R--) X = (2*X)%MOD;
while (C--) X = (2*X)%MOD;
cout << X << endl;
}
|
1178
|
D
|
Prime Graph
|
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!
When building the graph, he needs four conditions to be satisfied:
- It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops.
- The number of vertices must be exactly $n$ — a number he selected. This number is not necessarily prime.
- The total number of edges must be prime.
- The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime.
Below is an example for $n = 4$. The first graph (left one) is invalid as the degree of vertex $2$ (and $4$) equals to $1$, which is not prime. The second graph (middle one) is invalid as the total number of edges is $4$, which is not a prime number. The third graph (right one) is a valid answer for $n = 4$.
Note that the graph can be disconnected.
Please help Bob to find any such graph!
|
A solution always exists. We show a simple construction. For $n = 3$, a triangle is (the only) solution. For $n \geq 4$ we make a cycle on $n$ vertices: $1 \leftrightarrow 2 \leftrightarrow 3 \dots n \leftrightarrow 1$. The degree of each vertex is $2$ (a prime number), but the total number of edges - $n$ - might not be. For some $k$, we add edges of form $i \leftrightarrow i + \frac{n}{2}$ for all $i$ from $1$ to $k$. If $k \leq \frac{n}{2}$, each vertex gets at most one more neighbor, having degree $3$. Fortunately for us, for each $n \geq 3$ there is a prime number in interval $[n, \frac{3n}{2}]$, simply the smallest of them will do. The time complexity is $\mathcal O(n)$.
|
[
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,500
|
#include <iostream>
using namespace std;
bool prime(int x) {
if (x < 2) return false;
for (int i = 2; i*i <= x; ++i) {
if (x%i == 0) return false;
}
return true;
}
int main(int argc, char ** argv){
int n; cin >> n;
int m = n;
while (!prime(m)) ++m;
cout << m << "\n1 " << n << '\n';
for (int i = 0; i < n-1; ++i) {
cout << i+1 << ' ' << i+2 << '\n';
}
for (int i = 0; i < m-n; ++i) {
cout << i+1 << ' ' << i+1+n/2 << '\n';
}
}
|
1178
|
E
|
Archaeology
|
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?
The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides.
Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.
A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.
|
The answer always exists. Let's prove by induction on $|s|$, giving a construction in the process. $|s| = 0 \Rightarrow t =$ empty string, $|s| \leq 3 \Rightarrow t = s[0]$, $|s| \geq 4 \Rightarrow$. Let $t'$ be solution for $s[2:-2]$, which exists due to induction. As $s[0] \neq s[1]$ and $s[-1] \neq s[-2]$, there is at least one character 'x' that occurs in one of $s[0], s[1]$ and $s[-1], s[-2]$. Then $t = x t' x$ is a palindrome and its length is $|t| = 2 + |t'| \geq 2 + \lfloor \dfrac{|s[2:-2]|}{2} \rfloor = 2 + \lfloor \dfrac{|s|-4}{2} \rfloor = \lfloor \dfrac{|s|}{2} \rfloor\,.$ $|t| = 2 + |t'| \geq 2 + \lfloor \dfrac{|s[2:-2]|}{2} \rfloor = 2 + \lfloor \dfrac{|s|-4}{2} \rfloor = \lfloor \dfrac{|s|}{2} \rfloor\,.$ The time complexity is $\mathcal O(|s|)$. Bonus: Find a subpalindrome of length at least $\lceil \frac{|s|}{2} \rceil$.
|
[
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | 1,900
|
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string S; cin >> S;
int N = S.size();
int i = 0, j = N-1;
string A;
while (j-i >= 3) {
if (S[i] == S[j]) {
A.push_back(S[i]);
++i; --j;
} else if (S[i] == S[j-1]) {
A.push_back(S[i]);
++i; j -= 2;
} else {
A.push_back(S[i+1]);
if (S[i+1] == S[j]) {
--j;
} else {
j -= 2;
}
i += 2;
}
}
string B = A;
if (j >= i) A.push_back(S[i]);
reverse(B.begin(),B.end());
cout << A << B << endl;
}
|
1178
|
F1
|
Short Colorful Strip
|
\textbf{This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of $m$ and the time limit. You need to solve both subtasks in order to hack this one.}
There are $n+1$ distinct colours in the universe, numbered $0$ through $n$. There is a strip of paper $m$ centimetres long initially painted with colour $0$.
Alice took a brush and painted the strip using the following process. For each $i$ from $1$ to $n$, \textbf{in this order}, she picks two integers $0 \leq a_i < b_i \leq m$, such that the segment $[a_i, b_i]$ is currently painted with a \textbf{single} colour, and repaints it with colour $i$.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than $0$. Formally, the segment $[i-1, i]$ is painted with colour $c_i$ ($c_i \neq 0$). Every colour other than $0$ is visible on the strip.
Count the number of different pairs of sequences $\{a_i\}_{i=1}^n$, $\{b_i\}_{i=1}^n$ that result in this configuration.
Since this number may be large, output it modulo $998244353$.
|
Let $LO[l][r]$ be the lowest ID of a colour used in the final strip on interval $[l,r]$. Let $I[c]$ be the position on which the colour $c$ occurs on the target strip. We solve this problem by computing $DP[l][r]$ - the number of ways of painting the interval $[l,r]$, given that it is painted with a single colour and all subsequent colouring intervals must be either completely inside or completely outside of this interval. The first colour used on this interval will be $c = LO[l][r]$. How can we choose to paint it? Clearly, we can choose any interval $[a,b]$ such that $l \leq a \leq I[c] \leq b \leq r$. Once we perform this operation, then $I[c]$ can never be recoloured, and the interval $[l,r]$ is split into four single coloured intervals (possibly empty) that can be solved independently. This gives us $DP[l][r] = \sum_a \sum_b DP[l][a-1] * DP[a][I[c]-1] * DP[I[c]+1][b] * DP[b+1][r]$ which can be computed naively in $\mathcal O(n^4)$. To optimise it to $\mathcal O(n^3)$ just note that the selection of $a$ and $b$ is independent.
|
[
"combinatorics",
"dfs and similar",
"dp"
] | 2,200
|
#include <iostream>
#include <vector>
using namespace std;
template <unsigned int N> class Field {
typedef unsigned int ui;
typedef unsigned long long ull;
public:
inline Field(int x = 0) : v(x) {}
inline Field<N>&operator+=(const Field<N>&o) {if (v+o.v >= N) v += o.v - N; else v += o.v; return *this; }
inline Field<N>&operator*=(const Field<N>&o) {v=(ull)v*o.v % N; return *this; }
inline Field<N> operator*(const Field<N>&o) const {Field<N>r{*this};return r*=o;}
inline explicit operator ui() const { return v; }
private: ui v;
};
template<unsigned int N>ostream &operator<<(std::ostream&os,const Field<N>&f){return os<<(unsigned int)f;}
template<unsigned int N>Field<N> operator*(int i,const Field<N>&f){return Field<N>(i)*f;}
typedef Field<998244353> F;
int main() {
ios_base::sync_with_stdio(false);
int N, M; cin >> N >> M;
vector<int> C(N); for (int &c: C) { cin >> c; --c; }
vector<vector<F>> D(N+1, vector<F>(N+1, 1));
for (int l = 1; l <= M; ++l) {
for (int a = 0; a + l <= M; ++a) {
pair<int,int> lo = {C[a],0};
for (int i = 0; i < l; ++i) lo = min(lo, {C[a+i],i});
int j = lo.second;
if (j < 0 || j >= l) { D[a][l] = 0; continue; }
F left = 0, right = 0;
for (int u = 0; u <= j; ++u) left += D[a][u] * D[a+u][j-u];
for (int v = j+1; v <= l; ++v) right += D[a+j+1][v-(j+1)] * D[a+v][l-v];
D[a][l] = left * right;
}
}
cout << D[0][N] << endl;
}
|
1178
|
F2
|
Long Colorful Strip
|
\textbf{This is the second subtask of problem F. The only differences between this and the first subtask are the constraints on the value of $m$ and the time limit. It is sufficient to solve this subtask in order to hack it, but you need to solve both subtasks in order to hack the first one.}
There are $n+1$ distinct colours in the universe, numbered $0$ through $n$. There is a strip of paper $m$ centimetres long initially painted with colour $0$.
Alice took a brush and painted the strip using the following process. For each $i$ from $1$ to $n$, \textbf{in this order}, she picks two integers $0 \leq a_i < b_i \leq m$, such that the segment $[a_i, b_i]$ is currently painted with a \textbf{single} colour, and repaints it with colour $i$.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than $0$. Formally, the segment $[i-1, i]$ is painted with colour $c_i$ ($c_i \neq 0$). Every colour other than $0$ is visible on the strip.
Count the number of different pairs of sequences $\{a_i\}_{i=1}^n$, $\{b_i\}_{i=1}^n$ that result in this configuration.
Since this number may be large, output it modulo $998244353$.
|
There are several additional observations we need compared to previous subtask. First, note that if we ever colour a pair of positions with different colours, they will forever stay coloured with different colours. In other words, if two positions have the same colour in the final strip, the set of colours they were coloured with is the same. As a result, we can compress the input by removing consecutive equal values. Next, we look at the number of changes in the strip. A change is a position $i$ such that $c_i \neq c_{i+1}$. Initially, there are $0$ changes, and each operation adds at most $2$ changes. As a result, if the length of the input after the compression is more than $2n$, we can immediately print $0$. Now we can use the DP as in previous tasks, but there is one more complication to resolve. Consider the third sample: The DP suggests that $DP[0][2] = DP[0][0] * DP[2][2] = 1$. The reason why we get a wrong answer is that we treat the intervals $[0,0]$ and $[2,2]$ as independent, but in reality they are not. To fix this, instead of finding a single value of $I[c]$, we set $I'[c]$ to be all positions (in the whole array) containing colour $c$. We can then pick $l \leq a \leq \min(I'[c])$ and $\max(I'[c]) \leq b \leq r$. For this to be possible, all occurrences of the colour $c$ must be within interval $[l,r]$, otherwise $D[l][r] = 0$. The occurrences of colour $c$ and the indices $a$ and $b$ now can split the interval $[l,r]$ into more than $4$ segments, but this does not affect the complexity. Final complexity is $\mathcal O(n^3 + m)$. Bonus (courtesy of [user:Um_nik]): Can you solve it faster?
|
[
"dp"
] | 2,600
|
#include <iostream>
#include <vector>
using namespace std;
template <unsigned int N> class Field {
typedef unsigned int ui;
typedef unsigned long long ull;
public:
inline Field(int x = 0) : v(x) {}
inline Field<N> pow(int p){return (*this)^p; }
inline Field<N>&operator+=(const Field<N>&o) {if (v+o.v >= N) v += o.v - N; else v += o.v; return *this; }
inline Field<N>&operator*=(const Field<N>&o) {v=(ull)v*o.v % N; return *this; }
inline Field<N> operator*(const Field<N>&o) const {Field<N>r{*this};return r*=o;}
inline explicit operator ui() const { return v; }
private: ui v;
};
template<unsigned int N>ostream &operator<<(std::ostream&os,const Field<N>&f){return os<<(unsigned int)f;}
template<unsigned int N>Field<N> operator+(int i,const Field<N>&f){return Field<N>(i)+f;}
template<unsigned int N>Field<N> operator*(int i,const Field<N>&f){return Field<N>(i)*f;}
typedef Field<998244353> F;
int main() {
ios_base::sync_with_stdio(false);
int N, M; cin >> N >> M;
vector<int> C(M); for (int &c: C) { cin >> c; --c; }
vector<int> W;
for (int i = 0; i < M; ++i) if (W.empty() || W.back() != C[i]) W.push_back(C[i]);
M = W.size();
if (M > 2*N) { cout << "0\n"; return 0; }
vector<vector<int>> E(N);
for (int i = 0; i < M; ++i) E[W[i]].push_back(i);
vector<vector<F>> D(M+1, vector<F>(M+1, 1));
for (int l = 1; l <= M; ++l) {
for (int a = 0; a + l <= M; ++a) {
int lo = W[a];
for (int i = 0; i < l; ++i) lo = min(lo, W[a+i]);
int j = E[lo][0] - a;
int k = E[lo].back() - a;
if (j < 0 || k >= l) { D[a][l] = 0; continue; }
F left = 0, right = 0;
for (int u = 0; u <= j; ++u) left += D[a][u] * D[a+u][j-u];
for (int v = k+1; v <= l; ++v) right += D[a+k+1][v-(k+1)] * D[a+v][l-v];
D[a][l] = left * right;
for (int m = 0; m < E[lo].size()-1; ++m) {
if (E[lo][m] + 1 != E[lo][m+1]) {
D[a][l] *= D[E[lo][m]+1][E[lo][m+1] - E[lo][m] - 1];
}
}
}
}
cout << D[0][M] << endl;
}
|
1178
|
G
|
The Awesomest Vertex
|
You are given a rooted tree on $n$ vertices. The vertices are numbered from $1$ to $n$; the root is the vertex number $1$.
Each vertex has two integers associated with it: $a_i$ and $b_i$. We denote the set of all ancestors of $v$ (including $v$ itself) by $R(v)$. The awesomeness of a vertex $v$ is defined as
$$\left| \sum_{w \in R(v)} a_w\right| \cdot \left|\sum_{w \in R(v)} b_w\right|,$$
where $|x|$ denotes the absolute value of $x$.
Process $q$ queries of one of the following forms:
- 1 v x — increase $a_v$ by a positive integer $x$.
- 2 v — report the maximum awesomeness in the subtree of vertex $v$.
|
Denote $c_v = \sum_{w \in R(v)} a_w$ and $d_v = \sum_{w \in R(v)} b_w$. Let's solve a simpler task first, where we assume that all $a_i$ and $b_i$ are positive, and all updates and queries are on the root vertex. We can see that we are looking into maximum $\left(x + c_v \right) \cdot d_v$ = $c_vd_v + xd_v$, where $x$ is the cumulative sum of updates until this point. For a given $x$, this can be solved in $\mathcal O(\log n)$ using convex hull trick. How do we handle negative values of $a_i$ and $b_i$? We simply try all the lines $-c_vd_v - xd_v$ as well. The second issue is that our updates and queries can occur on arbitrary vertices. We can linearise the tree using DFS - then subtree of a vertex corresponds to an interval in the array. Afterwards, we use sqrt-decomposition in a fairly standard way: We partition the array into blocks of size roughly $\sqrt n$, build a convex hull trick structure on each of them, and remember the value of $x$ for each of them separately. Given an update, some blocks are untouched, in some we just need to update $x$ in constant time, and there are at most two blocks which are updated partially, which we rebuild from scratch. Given a query, we can use the convex hull trick structure to get the maximum in a block that is fully covered by the query. Again, we have at most two blocks that are partially intersected - there we can brute force the maximum. This yields a $\mathcal O(n + q \sqrt n \log n)$ algorithm. You just want contribution, go away! Oh wait, you're right. This solution has a rather large constant factor, so let's not stop there. What do we need the $\log n$ factor for? Two things: sorting all the lines by slope and determining the best line in a convex hull trick structure. Let's get rid of both - firstly, as $b_i$ doesn't change, we can sort once before processing any queries. Secondly, notice that the updates only add positive values, thus we only ever query lines with increasing $x$. Hence, no binary search is needed - we can simply advance a pointer over the structure in $\mathcal O(1)$ amortised. Overall complexity becomes $\mathcal O(n \log n + q \sqrt n)$. There, no marmots harmed. One final remark - the cost of building a convex hull structure in a block is slightly higher than that of iterating over the blocks. It seems that the most efficient size of the block is $\sqrt{n/6}$. This final observation was not needed to get AC.
|
[
"data structures",
"dfs and similar"
] | 3,000
|
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cassert>
#include <cmath>
using namespace std;
#define x first
#define y second
typedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
bool fractionGreaterOrEqual(double a, double b, double c, double d) {
return a/b >= c/d;
}
int TOTAL;
/* UpperEnvelope that with O(N) build and amortized O(1) query.
* The updates need be sorted by (m,b), the queries need to be sorted by x, and
* updates need to come before queries. */
namespace LinearEnvelope {
template<typename T> struct Line { T m, b; int id; };
template <typename T>
struct Upper {
Line<T> *V;
T t; int i, s;
Upper(int w) : V(new Line<T>[w]), t(0), i(0), s(0) { TOTAL++; }
~Upper() { TOTAL--; }
//~Upper() { delete []V; }
void clear() { i = s = 0; t = 0; }
void insert_line(T m, T b, int i = 0) {
assert(t == 0);
if (s > 0 && V[s-1].m == m && V[s-1].b >= b) return;
while (s > 0 && ((V[s-1].b < b) || (V[s-1].b == b && V[s-1].m < m))) --s;
while (s >= 2 && fractionGreaterOrEqual(V[s-2].b - V[s-1].b, V[s-1].m - V[s-2].m, V[s-1].b - b, m - V[s-1].m)) --s;
V[s++] = {m,b,i};
}
pair<T,int> advance(T x) {
assert(x >= 0);
t += x;
while (i+1 < s && V[i].m * t + V[i].b < V[i+1].m * t + V[i+1].b) ++i;
return {V[i].m * t + V[i].b, V[i].id};
}
};
};
class RPPS {
public:
vector<vector<int>> E;
vector<ll> A,B,RA,RB;
vector<int> Enter,Exit;
int T;
void dfs(int u, ll a, ll b) {
A[u] += a;
B[u] += b;
Enter[u] = T++;
for (int v:E[u]) dfs(v, A[u], B[u]);
Exit[u] = T;
}
struct Block {
Block(int L, int R, const vector<ll>&A, const vector<ll>&B) : U(2*(R-L)), L(L), R(R), off(0), cur(0) {
for (int i = L; i < R; ++i) W.push_back({{B[i], A[i]*B[i]}, i});
for (int i = L; i < R; ++i) if (A[i] < 0 || B[i] < 0) W.push_back({{-B[i], -A[i]*B[i]}, i});
sort(W.begin(),W.end());
build();
}
void build() {
U.clear();
for (auto &w:W) U.insert_line(w.x.x, w.x.y);
cur = U.advance(0LL).x;
}
void add(int l, int r, ll x) {
if (l >= R || r <= L) return;
else if (l <= L && r >= R) {
cur = U.advance(x).x;
off += x;
} else {
for (auto &w:W) {
w.x.y += w.x.x * off;
if (in(l, w.y, r)) {
w.x.y += w.x.x * x;
}
}
off = 0;
build();
}
}
ll get(int l, int r) {
if (l >= R || r <= L) return numeric_limits<ll>::min();
else if (l <= L && r >= R) return cur;
else {
ll ans = numeric_limits<ll>::min();
for (auto &w:W) {
if (in(l, w.y, r)) {
ans = max(ans, w.x.x * off + w.x.y);
}
}
return ans;
}
}
LinearEnvelope::Upper<ll> U;
vector<pair<pair<ll,ll>,int>> W;
int L, R;
ll off, cur;
};
void solve(istream& cin, ostream& cout) {
TOTAL = 0;
int N, Q; cin >> N >> Q;
E.resize(N);
A.resize(N);
B.resize(N);
RA.resize(N);
RB.resize(N);
Enter.resize(N);
Exit.resize(N);
for (int i = 1; i < N; ++i) {
int p; cin >> p; --p;
E[p].push_back(i);
}
cin >> A >> B;
T = 0;
dfs(0, 0, 0);
for (int i = 0; i < N; ++i) {
RA[Enter[i]] = A[i];
RB[Enter[i]] = B[i];
}
int BS = max(1,(int)sqrt(N/6));
vector<Block> D;
D.reserve(1+(N-1)/BS);
for (int i = 0; i < N; i+=BS) D.emplace_back(i, min(i+BS,N), RA, RB);
ll diff = 0;
for (int q = 0; q < Q; ++q) {
int t,v; cin >> t >> v;
--v;
if (t == 1) {
ll x; cin >> x;
for (Block&b:D) b.add(Enter[v],Exit[v],x);
} else {
ll ans = numeric_limits<ll>::min();
for (Block&b:D) ans = max(ans, b.get(Enter[v],Exit[v]));
cout << ans << '\n';
}
}
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
RPPS solver;
std::istream& in(std::cin);
std::ostream& out(std::cout);
solver.solve(in, out);
return 0;
}
|
1178
|
H
|
Stock Exchange
|
\textbf{Warning: This problem has an unusual memory limit!}
Bob decided that he will not waste his prime years implementing GUI forms for a large corporation and instead will earn his supper on the Stock Exchange Reykjavik. The Stock Exchange Reykjavik is the only actual stock exchange in the world. The only type of transaction is to take a single share of stock $x$ and exchange it for a single share of stock $y$, provided that the current price of share $x$ is at least the current price of share $y$.
There are $2n$ stocks listed on the SER that are of interest to Bob, numbered from $1$ to $2n$. Bob owns a single share of stocks $1$ through $n$ and would like to own a single share of each of $n+1$ through $2n$ some time in the future.
Bob managed to forecast the price of each stock — in time $t \geq 0$, the stock $i$ will cost $a_i \cdot \lfloor t \rfloor + b_i$. The time is currently $t = 0$. Help Bob find the earliest moment in time in which he can own a single share of each of $n+1$ through $2n$, and the minimum number of stock exchanges he has to perform in order to do that.
You may assume that the Stock Exchange has an unlimited amount of each stock at any point in time.
|
Lemma: If there is a solution $S$ for time $T$, there is also a solution $S'$ for time $T$ using not more exchanges than $S$, in which all exchanges occur either in time $0$ or in time $T$. Proof: Induction on $n$ - the number of exchanges not happening in time $0$ or $T$. If $n = 0$, we are done. Otherwise, pick an arbitrary exchange $i \rightarrow j$ at time $t$. There are a few cases: There is an exchange $j \rightarrow k$ at time $t$. We can substitute both by exchange $i \rightarrow k$. There is an exchange $k \rightarrow i$ at time $t$. We can substitute both by exchange $k \rightarrow j$. If $a[i] \geq a[j]$ and there is an exchange $j \rightarrow k$ in time $t < t_1 < T$. We substitute both with exchange $i \rightarrow k$ in time $t_1$. otherwise, postpone the exchange to time $T$ there is an exchange $j \rightarrow k$ in time $t < t_1 < T$. We substitute both with exchange $i \rightarrow k$ in time $t_1$. otherwise, postpone the exchange to time $T$ If $a[i] < a[j]$ and there is an exchange $k \rightarrow i$ in time $0 < t_1 < t$. We substitute both with exchange $k \rightarrow j$ in time $t_1$. otherwise, prepone the exchange to time $0$ there is an exchange $k \rightarrow i$ in time $0 < t_1 < t$. We substitute both with exchange $k \rightarrow j$ in time $t_1$. otherwise, prepone the exchange to time $0$ Thanks to this lemma, and the fact that we can get rid of transitive exchanges happening at the same time, we can model this problem as min-cost max-flow on $4N+2$ vertices. Let there be vertices $u_i$ and $v_i$ for each stock, and $s$ and $t$ are source and sink, respectively. There are edges of six types: Edge $s \rightarrow u_i$ for all $0 \leq i < N$ with capacity $1$ and cost $0$ (representing the starting stock). Edge $u_i \rightarrow v_i$ for all $0 \leq i < N$ with capacity $1$ and cost $0$ (representing stock not exchanged at $t = 0$). Edge $u_i \rightarrow v_j$ for all $0 \leq i < N$ and $j$ such that $B[i] \geq B[j]$, with capacity $1$ and cost $1$ (representing an exchange at $t = 0$). Edge $v_i \rightarrow u_i$ for all $N \leq i < 2N$ with capacity $1$ and cost $0$ (representing stock not exchanged at $t = T$). Edge $v_i \rightarrow u_j$ for all $0 \leq i < 2N$ and $N \leq j < N$ sucht that $A[i]*T + B[i] \geq A[j]*T + B[j]$, with capacity $1$ and cost $1$ (representing an exchange at $t = T$). Edge $u_i \rightarrow t$ for all $N \leq i < 2N$ with capacity $1$ and cost $0$ (representing desired stock). If the flow size equals $N$, then there exists a strategy. The number of exchanges equals to the cost of the flow. This combined runs in $O(N^3 \log N \log MAX)$ using e.g. preflow-push. Even when considering the fact that the bounds on flow algorithms are often not tight, this is not very promising. Furthermore, it uses $O(N^2)$ memory, which is clearly too much. Let's improve it. Removing $\log MAX$ factor: The first observation is that we don't need to run the MCMF for every iteration of the binary search - we don't need the cost, all that is required is deciding whether max-flow size is $N$. There are many approaches to this, perhaps the simplest one is to solve it in $O(N \log N)$: At time $T$, exchange each stock to the most expensive stock at $t = T$ that we can afford to exchange at $t = 0$. Check whether at time $t = T$ the prices of stocks obtained this way dominate the prices of the desired stocks. Reducing the space complexity: Note that the edges of type $3$ and $5$ connect a stock $i$ to some subset of stocks $j$. This subset of stocks is a prefix of the array of stocks sorted by their price. We can thus connect each stock only to the most expensive stock to which it can be exchanged, and connect these in order of decreasing price with edges of capacity $N$ and cost $0$ (make sure the ties are broken correctly). This way, we reduce the number of edges from quadratic to $12N$, improving the space complexity. Reducing to $O(N^2 \log N)$ time: The maximum flow is capped by $N$. In such a setting primal methods such as Ford-Fulkerson, respectively it's MCMF version called Successive Shortest Paths Algorithm, behave quite well, needing only $O(f \cdot |E| \log |E|) = O(N^2 \log N)$ time. Reducing to $O(N^2)$ time: However, in our problem, the costs are also bounded by a small constant, namely $0$ or $1$. In Dijsktra's algorithm, the subroutine of SSPA, one can use a fixed size array instead of a priority queue, reducing the complexity even further. This last optimisation is difficult to separate, so with a reasonable implementation it is not necessary to get AC. The total complexity is thus $O(N \log N \log MAX + N^2)$.
|
[
"binary search",
"flows",
"graphs"
] | 3,500
|
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define x first
#define y second
typedef long long ll;
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
/** Successive shortest paths algorithm. Runs in O(maxFlow * (|E| + sumCosts)). */
template<typename Cap = int, typename Cost = int>
struct SSPA {
struct Edge{
Cost c; Cap f; int to, rev;
Edge(int _to, Cost _c, Cap _f, int _rev):c(_c), f(_f), to(_to), rev(_rev){}
};
int N, source, sink;
vector<vector<Edge>> G;
SSPA(int N, int source, int sink): N(N), source(source), sink(sink), G(N) {}
void addEdge(int a, int b, Cap cap, Cost cost) {
assert(cap>=0);
assert(a>=0&&a<N&&b>=0&&b<N);
if(a==b){assert(cost>=0); return;}
G[a].emplace_back(b, cost, cap, G[b].size());
G[b].emplace_back(a, -cost, 0, G[a].size()-1);
}
pair<Cap, Cost> minCostMaxFlow() {
/* Vertex potentials. These are maintained so that all edges with non-zero
* residual have non-negative length. Thus, Dijkstra can be used instead of
* Bellman-Ford in each step of the algorithm. */
vector<Cost> Pi(N, 0);
Cost infty = std::numeric_limits<Cost>::max();
Cap totFlow = 0;
Cost totCost = 0;
while (true) {
vector<Cost> D(N, infty);
vector<int> Prev(N, -1);
D[source] = 0;
vector<vector<int>> Q{{source}};
for (int i = 0; i < Q.size(); ++i) {
for (int j = 0; j < Q[i].size(); ++j) {
int u = Q[i][j];
if (D[u] < i) continue;
for (auto &e: G[u]) {
if (e.f > 0) {
Cost c = D[u] + e.c;
if (D[e.to] > c) {
D[e.to] = c;
while (c >= Q.size()) Q.emplace_back();
Q[c].push_back(e.to);
Prev[e.to] = u;
}
}
}
}
}
// if sink is unreachable, flow is optimal
if (D[sink] == infty) break;
// reconstruct some shortest path
int v = sink;
vector<int> Path;
while (v != -1) { Path.push_back(v); v = Prev[v]; }
reverse(Path.begin(),Path.end());
// found the minimum of the edge residuals along the path
Cap augment = std::numeric_limits<Cap>::max();
int L = Path.size();
for (int i = 0; i < L-1; ++i) {
int u = Path[i], v = Path[i+1];
for (auto&e: G[u]) {
// be careful, there might be multiedges
if (e.to == v && e.f > 0 && D[v] == D[u] + e.c) {
augment = min(augment, e.f);
break;
}
}
}
for (int i = 0; i < L-1; ++i) {
int u = Path[i], v = Path[i+1];
for (auto&e: G[u]) {
if (e.to == v && e.f > 0 && D[v] == D[u] + e.c) {
e.f -= augment;
G[v][e.rev].f += augment;
break;
}
}
}
// store the cost & flow size
Cost cost = Pi[source] - Pi[sink] + D[sink];
totFlow += augment;
totCost += cost * augment;
// remove potentials from costs
for (int i = 0; i < N; ++i) {
for (auto &e: G[i]) {
e.c -= Pi[e.to] - Pi[i];
}
}
// add potentials to costs again
for (int i = 0; i < N; ++i) {
for (auto &e: G[i]) {
e.c += (Pi[e.to] - D[e.to]) - (Pi[i] - D[i]);
}
}
// update potentials based on the results
for (int i = 0; i < N; ++i) Pi[i] -= D[i];
}
return {totFlow,totCost};
}
};
class Stock {
public:
void solve(istream& cin, ostream& cout) {
int N; cin >> N;
vector<int> A(2*N), B(2*N);
for (int i = 0; i < 2*N; ++i) {
cin >> A[i] >> B[i];
}
// find T: O(N log MAX log N)
int T = bsl(0, 1000000000, [&](int t) {
// ( (price at 0) x (-price at t) x (is initial stock) )
vector<pair<pair<int, ll>, bool>> Stocks(2*N);
for (int i = 0; i < 2*N; ++i) {
Stocks[i] = {{B[i], -(A[i]*ll(t) + B[i])}, i<N};
}
sort(Stocks.begin(),Stocks.end());
ll best = 0;
vector<ll> CanHave, Required;
for (int i = 0; i < 2*N; ++i) {
best = max(best, -Stocks[i].x.y);
if (Stocks[i].y) {
CanHave.push_back(best);
} else {
Required.push_back(-Stocks[i].x.y);
}
}
sort(CanHave.begin(),CanHave.end());
sort(Required.begin(),Required.end());
for (int i = 0; i < N; ++i) {
if (CanHave[i] < Required[i]) return false;
}
return true;
});
if (T == -1) {
cout << -1 << endl;
return;
}
vector<pair<pair<int,ll>,int>> Begin(2*N);
vector<pair<ll, int>> End(2*N);
for (int i = 0; i < 2*N; ++i) {
ll end = A[i]*ll(T) + B[i];
// bigger start => process later
// bigger end => process earlier
Begin[i] = {{B[i], -end}, i};
// bigger end => process later
// bigger id => process earlier
End[i] = {end, -i};
}
sort(Begin.begin(),Begin.end());
sort(End.begin(),End.end());
reverse(Begin.begin(),Begin.end());
reverse(End.begin(),End.end());
// SSPA, using O(dijkstra * flow)
SSPA<int,int> G(6*N+2, 6*N, 6*N+1);
for (int i = 0; i < 2*N; ++i) {
if (i != 2*N-1) {
int j = Begin[i].y;
int k = Begin[i+1].y;
G.addEdge(N+j, N+k, N, 0); // perform exchange at t=0
j = -End[i].y;
k = -End[i+1].y;
G.addEdge(3*N+j, 3*N+k, N, 0); // perform exchange at t=T
}
if (Begin[i].y < N) {
int j = Begin[i].y;
G.addEdge(6*N, j, 1, 0); // super source
G.addEdge(j, N+j, 1, 1); // exchange for something at t=0
G.addEdge(j, 3*N+j, 1, 0); // hold until t=T
}
if ((-End[i].y) >= N) {
int j = -End[i].y;
G.addEdge(N+j, 5*N+(j-N), 1, 0); // was kept from t=0
G.addEdge(3*N+j, 5*N+(j-N), 1, 1); // was exchanged at t=T
G.addEdge(5*N+(j-N), 6*N+1, 1, 0); // super sink
}
G.addEdge(N+i, 3*N+i, N, 0); // hold between 0 and T
}
auto res = G.minCostMaxFlow();
assert(res.x == N);
cout << T << ' ' << res.y << '\n';
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
Stock solver;
std::istream& in(std::cin);
std::ostream& out(std::cout);
solver.solve(in, out);
return 0;
}
|
1179
|
A
|
Valeriy and Deque
|
Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $n$ elements. The $i$-th element is $a_i$ ($i$ = $1, 2, \ldots, n$). He gradually takes the first two leftmost elements from the deque (let's call them $A$ and $B$, respectively), and then does the following: if $A > B$, he writes $A$ to the beginning and writes $B$ to the end of the deque, otherwise, he writes to the beginning $B$, and $A$ writes to the end of the deque. We call this sequence of actions an operation.
For example, if deque was $[2, 3, 4, 5, 1]$, on the operation he will write $B=3$ to the beginning and $A=2$ to the end, so he will get $[3, 4, 5, 1, 2]$.
The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $q$ queries. Each query consists of the singular number $m_j$ $(j = 1, 2, \ldots, q)$. It is required for each query to answer which two elements he will pull out on the $m_j$-th operation.
Note that \textbf{the queries are independent} and for each query the numbers $A$ and $B$ should be \textbf{printed in the order in which they will be pulled out of the deque}.
Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.
|
It can be noted that if the deque has the largest element of the deque in the first position, then during the next operations it will remain in the first position, and the second one will be written to the end each time, that is, all the elements of the deque starting from the second will move cyclically left. Let's go over the deque and find the largest element by value. We will perform the operation described in the statements until the maximum position is in the first position and save the elements in the first and second positions by the operation number. In order to pre-calculate all pairs until the moment when the maximum position is found, it is enough to make no more than one pass through the deque, since in the worst case, the maximum element can be located at the end of the deque. Denote as $maxIndex$ the position of the maximum element. Then if $m_j <maxIndex$, simply return a pair of numbers from the pre-calculated array, otherwise $A$ is equal to the maximum element, and $B$ is equal to the deque element with the index $(m_j - (maxIndex + 1)) \% (n - 1) + 1$ in $0$-indexing (since we performed the operations until the moment when the maximum position is in the first position, this maximum element is now recorded in the first position).
|
[
"data structures",
"implementation"
] | 1,500
|
"/// author: Mr.Hakimov\n\n#include <bits/stdc++.h>\n#include <chrono>\n\n#define all(x) (x).begin(), (x).end()\n#define fin(s) freopen(s, \"r\", stdin);\n#define fout(s) freopen(s, \"w\", stdout);\n\nusing namespace std;\n\ntypedef long long LL;\ntypedef long double LD;\n\nint TN = 1;\n\nvoid showDeque(deque<int> d) {\n int n = d.size();\n for (int i = 0; i < n; i++) {\n cout << d.front() << \" \";\n d.push_back(d.front());\n d.pop_front();\n }\n cout << endl << \"==\" << endl;\n}\n\nvoid solve() {\n int n;\n int q;\n cin >> n >> q;\n deque<int> d;\n int maxValue = -1;\n for (int i = 0; i < n; i++) {\n int a_i;\n cin >> a_i;\n d.push_back(a_i);\n maxValue = max(maxValue, a_i);\n }\n\n map<int, pair<int, int>> answer;\n\n int maxIndex = 0;\n while (true) {\n /// showDeque(d);\n int first = d.front();\n d.pop_front();\n int second = d.front();\n d.pop_front();\n\n if (first == maxValue) {\n d.push_front(second);\n d.push_front(first);\n break;\n }\n\n maxIndex++;\n answer[maxIndex] = {first, second};\n\n if (second > first) {\n swap(first, second);\n }\n\n d.push_front(first);\n d.push_back(second);\n }\n\n int a[n];\n /// showDeque(d);\n for (int i = 0; i < n; i++) {\n a[i] = d.front();\n d.pop_front();\n }\n\n for (int i = 0; i < q; i++) {\n LL m_j;\n cin >> m_j;\n if (m_j <= maxIndex) {\n cout << answer[m_j].first << \" \" << answer[m_j].second << '\\n';\n } else {\n cout << maxValue << \" \" << a[(m_j - (maxIndex + 1)) % (n - 1) + 1] << '\\n';\n }\n }\n}\n\nint main() {\n auto start = chrono::steady_clock::now();\n ios_base::sync_with_stdio(0);\n cin.tie(nullptr); cout.tie(nullptr);\n /// =========================================\n /// fin(\"input.txt\"); fout(\"output.txt\");\n /// fin(\"file.in\"); fout(\"file.out\");\n /// cin >> TN;\n /// =========================================\n while (TN--) solve();\n auto finish = chrono::steady_clock::now();\n auto elapsed_ms = chrono::duration_cast<chrono::milliseconds>(finish - start);\n cerr << endl << \"Time: \" << elapsed_ms.count() << \" ms\\n\";\n return 0;\n}"
|
1179
|
B
|
Tolik and His Uncle
|
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.
In this task you are given a cell field $n \cdot m$, consisting of $n$ rows and $m$ columns, where point's coordinates $(x, y)$ mean it is situated in the $x$-th row and $y$-th column, considering numeration from one ($1 \leq x \leq n, 1 \leq y \leq m$). Initially, you stand in the cell $(1, 1)$. Every move you can jump from cell $(x, y)$, which you stand in, by any non-zero vector $(dx, dy)$, thus you will stand in the $(x+dx, y+dy)$ cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).
Tolik's uncle is a very respectful person. Help him to solve this task!
|
First, we are going to describe how to bypass $1 \cdot m$ strip. This algorithm is pretty easy - $(1, 1)$ -> $(1, m)$ -> $(1, 2)$ -> $(1, m-1)$ -> $\ldots$. Obviously all jumps have different vectors because their lengths are different. It turns out that the algorithm for $n \cdot m$ grid is almost the same. Initially, we are going to bypass two uttermost horizontals almost the same way as above - $(1, 1)$ -> $(n, m)$ -> $(1, 2)$ -> $(n, m-1)$ -> $\ldots$ -> $(1, m)$ -> $(n, 1)$. One can realize that all vectors are different because they have different $dy$. Note that all of them have $|dx| = n-1$. Then we will jump to $(2, 1)$ (using $(-(n-2), 0)$ vector). Now we have a smaller task for $(n-2) \cdot m$ grid. One can see that we used only vectors with $|dx| \geq n-2$, so they don't influence now at all. So the task is fully brought down to a smaller one.
|
[
"constructive algorithms"
] | 1,800
|
"#include <bits/stdc++.h>\n\n#define int long long\n\n#define pii pair<int, int>\n\n#define x1 x1228\n#define y1 y1228\n\n#define left left228\n#define right right228\n\n#define pb push_back\n#define eb emplace_back\n\n#define mp make_pair \n\n#define ff first \n#define ss second \n\n#define matr vector<vector<int> > \n\n#define all(x) x.begin(), x.end()\n\n\nusing namespace std;\ntypedef long long ll; \ntypedef long double ld; \n \nconst int maxn = 3e5 + 7, mod = 1e9 + 7, inf = 1e18, MAXN = 1e6 + 7;\nconst double eps = 1e-9;\nmt19937 rnd(time(0));\nint n, m; \n\nvoid solve() { \n cin >> n >> m; \n if (n == 2 && m == 3) {\n cout << \"1 1\\n1 3\\n1 2\\n2 2\\n2 3\\n2 1\"; \n return; \n }\n for (int i = 0; i < n / 2; ++i) {\n for (int j = 0; j < m; ++j) {\n cout << i+1 << \" \" << j+1 << '\\n';\n cout << n - i - 1+1 << \" \" << m - j - 1+1 << '\\n'; \n }\n } \n if (n % 2) { \n int x = n / 2;\n deque<int> have; \n cout << x+1 << \" \" << 1 << '\\n'; \n for (int i = 1; i < m; ++i) {\n have.pb(i); \n } \n while (have.size()) {\n cout << x+1 << \" \" << have.back()+1 << '\\n'; \n have.pop_back(); \n if (have.size()) {\n cout << x+1 << \" \" << have.front()+1 << '\\n'; \n have.pop_front(); \n }\n } \n }\n} \n \nsigned main() {\n#ifdef LOCAL1\n freopen(\"TASK.in\", \"r\", stdin);\n freopen(\"TASK.out\", \"w\", stdout);\n#else \n \n#endif // LOCAL\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.precision(20); \n cout << fixed; \n int t = 1; \n for (int i = 0; i < t; ++i) { \n solve();\n }\n return 0;\n}"
|
1179
|
C
|
Serge and Dining Room
|
Serge came to the school dining room and discovered that there is a big queue here. There are $m$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.
Initially there are $n$ dishes with costs $a_1, a_2, \ldots, a_n$. As you already know, there are the queue of $m$ pupils who have $b_1, \ldots, b_m$ togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has $b_1$ togrogs and the last one has $b_m$ togrogs)
Pupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...)
But money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining.
Moreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process $q$ queries:
- change $a_i$ to $x$. It means that the price of the $i$-th dish becomes $x$ togrogs.
- change $b_i$ to $x$. It means that the $i$-th pupil in the queue has $x$ togrogs now.
Nobody leaves the queue during those queries because a saleswoman is late.
After every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or $-1$ if there are no dishes at this point, according to rules described above.
|
The main idea of the task is that the answer is minimal $x$ which satisfies the condition that the number of dishes with cost $\geq x$ is strictly more than the number of pupils who have more than $x$ togrogs. It can be proved using the fact that we can change every neighbor pair for pupils and we don't change the final set of dishes. Exact prove is left as an exercise. Now to find the answer we can use a segment tree that maintains a balance between the number of dishes and the number of pupils for all suffices of values. Now change query transforms to add in the segment tree, the answer should be found searching the last element which is less than $0$ (standard descent in the segment tree). Complexity is $O(n \cdot log(n)$).
|
[
"binary search",
"data structures",
"graph matchings",
"greedy",
"implementation",
"math",
"trees"
] | 2,200
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define int long long\n\nconst int MAXN = 3e5 + 7;\nconst int MAXV = 3 * MAXN;\n\nint n, m;\nint a[MAXN], b[MAXN];\n\nint q;\nint t[MAXN], p[MAXN], x[MAXN];\n\nvoid read() {\n cin >> n >> m;\n for (int i = 0; i < n; ++i) {\n cin >> a[i];\n }\n for (int i = 0; i < m; ++i) {\n cin >> b[i];\n } \n cin >> q;\n for (int i = 0; i < q; ++i) {\n cin >> t[i];\n if (t[i] <= 2) {\n cin >> p[i] >> x[i];\n --p[i];\n }\n } \n} \n\nint u = 0;\nint v[MAXV];\n\nvoid compr() {\n for (int i = 0; i < n; ++i) {\n v[u++] = a[i];\n } \n for (int i = 0; i < m; ++i) {\n v[u++] = b[i];\n } \n for (int i = 0; i < q; ++i) {\n if (t[i] <= 2) {\n v[u++] = x[i];\n } \n } \n sort(v, v + u);\n u = unique(v, v + u) - v;\n for (int i = 0; i < n; ++i) {\n a[i] = lower_bound(v, v + u, a[i]) - v;\n } \n for (int i = 0; i < m; ++i) {\n b[i] = lower_bound(v, v + u, b[i]) - v;\n } \n for (int i = 0; i < q; ++i) {\n if (t[i] <= 2) {\n x[i] = lower_bound(v, v + u, x[i]) - v;\n } \n } \n} \n\nint tree[MAXV << 2], add[MAXV << 2];\n\nvoid push(int v) {\n tree[v * 2 + 1] += add[v];\n add[v * 2 + 1] += add[v];\n tree[v * 2 + 2] += add[v];\n add[v * 2 + 2] += add[v];\n add[v] = 0;\n} \n\nvoid upd(int v, int tl, int tr, int l, int r, int x) {\n if (tr < l || r < tl) {\n return;\n } \n if (l <= tl && tr <= r) {\n tree[v] += x;\n add[v] += x;\n return;\n } \n int tm = (tl + tr) >> 1;\n push(v);\n upd(v * 2 + 1, tl, tm, l, r, x); \n upd(v * 2 + 2, tm + 1, tr, l, r, x);\n tree[v] = max(tree[v * 2 + 1], tree[v * 2 + 2]);\n}\n\nint get(int v, int tl, int tr) {\n if (tl == tr) {\n return tl;\n } \n int tm = (tl + tr) >> 1;\n push(v);\n if (tree[v * 2 + 2] >= 1) {\n return get(v * 2 + 2, tm + 1, tr);\n } \n else {\n return get(v * 2 + 1, tl, tm);\n } \n} \n\nvoid add1(int x) {\n //cout << x << ' ' << 1 << '\\n';\n upd(0, 0, MAXV, 0, x, 1);\n}\n\nvoid del1(int x) {\n //cout << x << ' ' << -1 << '\\n';\n upd(0, 0, MAXV, 0, x, -1);\n}\n\nvoid upd1(int p, int x) {\n del1(a[p]);\n a[p] = x;\n add1(a[p]);\n} \n\nvoid add2(int x) {\n //cout << x << ' ' << -1 << '\\n';\n upd(0, 0, MAXV, 0, x, -1);\n}\n\nvoid del2(int x) { \n //cout << x << ' ' << 1 << '\\n';\n upd(0, 0, MAXV, 0, x, 1);\n} \n\nvoid upd2(int p, int x) {\n del2(b[p]);\n b[p] = x;\n add2(b[p]);\n} \n\nint get() {\n if (tree[0] >= 1) {\n return get(0, 0, MAXV);\n } \n else {\n return -1;\n } \n} \n\nvoid solve() {\n compr();\n for (int i = 0; i < n; ++i) {\n add1(a[i]);\n } \n for (int i = 0; i < m; ++i) {\n add2(b[i]);\n } \n}\n\nvoid print() {\n for (int i = 0; i < q; ++i) {\n if (t[i] == 1) {\n upd1(p[i], x[i]);\n } \n else {\n upd2(p[i], x[i]);\n } \n {\n int ans = get();\n if (ans == -1) {\n cout << \"-1\\n\";\n } \n else {\n cout << v[ans] << '\\n';\n } \n } \n } \n}\n\nsigned main() {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n\n read();\n solve();\n print();\n\n return 0;\n}"
|
1179
|
D
|
Fedor Runs for President
|
Fedor runs for president of Byteland! In the debates, he will be asked how to solve Byteland's transport problem. It's a really hard problem because of Byteland's transport system is now a tree (connected graph without cycles). Fedor's team has found out in the ministry of transport of Byteland that there is money in the budget only for one additional road. In the debates, he is going to say that he will build this road as a way to maximize the number of distinct simple paths in the country. A simple path is a path which goes through every vertex no more than once. Two simple paths are named distinct if sets of their edges are distinct.
But Byteland's science is deteriorated, so Fedor's team hasn't succeeded to find any scientists to answer how many distinct simple paths they can achieve after adding exactly one edge on the transport system?
Help Fedor to solve it.
An edge can be added between vertices that are already connected, but it can't be a loop.
In this problem, we consider only simple paths of length at least two.
|
We suppose we add an edge $u-v$. Path $u-v$ in the tree contains vertices $t_1, \ldots, t_k$, where $k$ - length of the path, $t_1 = u, t_k = v$. For each vertex $x$ of the tree, we say that $f(x)$ - the closest to $x$ vertex of this path. Finally, we call a component of $t_i$ all vertices $x$ having $f(x) = t_i$. One can notice that after adding an edge every pair of vertices may generate not more than two simple paths - the first one had already been in the tree, the second one may be generated using added edge. One can notice that every new path is generated by every pair of vertices lying in different components. Let's consider the sizes of components - $s_1, \ldots, s_k$ respectively. So new path isn't generated for $\sum\limits_{i=1}^k \frac{s_i \cdot (s_i - 1)}{2}$ pairs of vertices. So we have the following problem - to minimize this sum. Thus, we should minimize $\sum\limits_{i=1}^k \frac{s_i \cdot (s_i - 1)}{2}$, what is the same as, $\sum\limits_{i=1}^k s_i \cdot (s_i - 1)$ = $\sum\limits_{i=1}^k s_i \cdot s_i - s_i$ = $\sum\limits_{i=1}^k s_i^{2}$ (because of $\sum\limits_{i=1}^k s_i$ = $n$). It's obvious now that $u, v$ are leafs of the tree (else we could decrease this sum increasing the path). For convenience, we will hang the tree for a non-leaf. We will consider that $t_l = lca(u, v)$ in the path. Then, the desired sum will be: $A + B + C$, where $A = sz_{t_1}^{2} + (sz_{t_2} - sz_{t_1})^{2} + \ldots + (sz_{t_l} - sz_{t_{l-1}})^{2}$ $B = (n - sz_{t_{l-1}} - sz_{t_{l+1}})^{2}$ $C = sz_{t_k}^{2} + (sz_{t_{k-1}} - sz_{t_k})^{2} + \ldots + (sz_{t_l} - sz_{t_{l+1}})^{2}$ When we fix $L = t_l$, $p_1 = t_{l+1}$ and $p_2 = t_{l-1}$, one can realize that $A$ doesn't depend on $L$ at all but depends on the subtree of $p_1$, as $C$ depends of the subtree of $p_2$. Thus these sums can easily be calculated using $DP$. Let $dp[x]$ be that optimal sum for vertex $x$. Then, when we fix $L$ - $lca(u, v)$ - we need to calculate the minimum by all different $p_1, p_2$ - children of $L$ - the following sum: $dp[p_1] + dp[p_2] + (n - sz_{p_1} - sz_{p_2})^{2}$. We get: $n^{2} + dp[p1] - 2 \cdot n \cdot sz_{p_1} + dp[p2] - 2 \cdot n \cdot sz_{p_2} + 2 \cdot sz_{p_1} \cdot sz_{p_2}$. Now one can see that if we sort all vertices by $sz$ in non-increasing order one can use Convex Hull Trick - for the next vertex $p_2$ we find minimum by all $p_1$ which are already processed by functions $2 \cdot sz_{p_1} \cdot sz_{p_2} - 2 \cdot n \cdot sz_{p_1} + dp[p1]$, i.e $k = 2 \cdot sz_{p_1}$, $b = - 2 \cdot n \cdot sz_{p_1} + dp[p1]$. $k$ decreases, thus we write usual CHT. Complexity is $O(n \cdot log(n))$.
|
[
"data structures",
"dp",
"trees"
] | 2,700
|
"#include <bits/stdc++.h>\n#define int long long\n#define double long double\nusing namespace std;\nint INF = 1e18;\ndouble DINF = 1e18;\nvector<vector<int> > data;\nint ans = INF;\nvector<int> dp, sz;\nint n;\nstruct Line{double k; double b; double l; double r;};\nvector<Line> cht;\nint ask(int x){\n int L = 0, R = cht.size();\n double cp = x;\n while (R-L>1){\n int M = (L+R)/2;\n if (cht[M].r >= cp) L = M;\n else R = M;\n }\n int K = cht[L].k, B = cht[L].b;\n return K*x+B;\n}\ndouble intersect(Line &a, Line &b){\n if (a.k == b.k) return -DINF;\n double db = a.b - b.b;\n double dk = b.k - a.k;\n return db/dk;\n}\nvoid add(double k, double b){\n Line nl = {k, b, -DINF, DINF};\n while (cht.size()){\n double inter = intersect(nl, cht.back());\n if (inter <= cht.back().l){\n cht.pop_back();\n }\n else{\n cht.back().r = inter;\n nl.l = inter;\n cht.push_back(nl);\n break;\n }\n }\n if (!cht.size()) cht.push_back(nl);\n}\nvoid calc(int vertex, int last){\n vector<pair<int, int> > children;\n int cur=0;\n for (int i=0; i < data[vertex].size(); i++){\n int to = data[vertex][i];\n if (to == last) continue;\n children.push_back({sz[to], dp[to]});\n cur++;\n }\n if (cur==1) return;\n sort(children.begin(), children.end(), greater<pair<int, int> > ());\n for (int i=0; i < children.size(); i++){\n int SZ = children[i].first, DP = children[i].second;\n if (i > 0){\n int res = ask(SZ);\n ans = min(ans, res + DP + n*n + SZ*SZ - 2*n*SZ);\n }\n int K = 2*SZ;\n int B = DP+SZ*SZ-2*n*SZ;\n add(K, B);\n }\n}\nvoid dfs(int vertex, int last){\n sz[vertex] = 1;\n for (int i=0; i < data[vertex].size(); i++){\n int to = data[vertex][i];\n if (to == last) continue;\n dfs(to, vertex);\n sz[vertex] += sz[to];\n }\n if (sz[vertex] == 1) dp[vertex] = 1;\n else{\n dp[vertex] = INF;\n for (int i=0; i < data[vertex].size(); i++){\n int to = data[vertex][i];\n if (to == last) continue;\n dp[vertex] = min(dp[vertex], dp[to] + (sz[vertex] - sz[to]) * (sz[vertex] - sz[to]));\n }\n }\n calc(vertex, last);\n}\nmain() {\n ios_base::sync_with_stdio(false), cin.tie(0);\n cin >> n;\n data.resize(n, {});\n dp.resize(n, -1);\n sz.resize(n, -1);\n for (int i=0; i < n-1; i++){\n int u, v;\n cin >> u >> v;\n data[u-1].push_back(v-1), data[v-1].push_back(u-1);\n }\n if (n==2){\n cout << 2;\n return 0;\n }\n int father = -1;\n for (int i=0; i < n; i++){\n if (data[i].size() > 1) father = i;\n }\n dfs(father, -1);\n int res = 2*n*(n-1) - (ans - n);\n cout << res/2;\n return 0;\n}"
|
1179
|
E
|
Alesya and Discrete Math
|
We call a function good if its domain of definition is some set of integers and if in case it's defined in $x$ and $x-1$, $f(x) = f(x-1) + 1$ or $f(x) = f(x-1)$.
Tanya has found $n$ good functions $f_{1}, \ldots, f_{n}$, which are defined on all integers from $0$ to $10^{18}$ and $f_i(0) = 0$ and $f_i(10^{18}) = L$ for all $i$ from $1$ to $n$. It's an notorious coincidence that $n$ is a divisor of $L$.
She suggests Alesya a game. Using one question Alesya can ask Tanya a value of any single function in any single point. To win Alesya must choose integers $l_{i}$ and $r_{i}$ ($0 \leq l_{i} \leq r_{i} \leq 10^{18}$), such that $f_{i}(r_{i}) - f_{i}(l_{i}) \geq \frac{L}{n}$ (here $f_i(x)$ means the value of $i$-th function at point $x$) for all $i$ such that $1 \leq i \leq n$ so that for any pair of two functions their segments $[l_i, r_i]$ don't intersect (but may have one common point).
Unfortunately, Tanya doesn't allow to make more than $2 \cdot 10^{5}$ questions. Help Alesya to win!
It can be proved that it's always possible to choose $[l_i, r_i]$ which satisfy the conditions described above.
It's guaranteed, that Tanya doesn't change functions during the game, i.e. interactor is not adaptive
|
We denote $T$ as $log(10^{18})$ for convenience. Let, without loss of generality, $n$ is even. Let us find such $x_i$ for function $f_i$ that $f_i(x_i) = \frac{L}{2}$ using binary search. Now we're going to renumber functions so that in new numeration $i < j$ attracts $x_i \leq x_j$. Let $x_{\frac{n}{2}} = P$. Now one can see that we have reduced the task to two smaller ones - the original task for functions with numbers $1, \ldots, \frac{n}{2}$, having only a restriction that all their segments of answer are enclosed inside segment $[0; P]$, and, similarly, for others functions and segment $[P; 10^{18}]$. Considering the original problem with all functions as a problem with the restriction that segments of the answer are enclosed inside $[0; 10^{18}]$, the task is reduced to smaller ones. Proof of correctness if left as an exercise, it's pretty easy. This works in $O(n \cdot T \cdot log(n))$. To speed it up, we're going to find $\frac{n}{2}$-th function by $x_i$ a little bit smarter. Long story short, we're going to act as in the search of $k$-th element in an array in linear time. We will take a random function $f_i$, run binary search for it, and not run binary searches for others but check how many $f_j$ so that $f_j(x_j) \leq f_i(x_i)$. It's easy to check using one query $f_j(x_i)$ for all $f_j$. It will work in $O(T \cdot log(n) + n)$ queries on the average, as we know this process will averagely converge in $O(log(n))$ steps. Let's estimate the total complexity. Let, without loss of generality, the number of functions is $n = 2^{s}$ for some $s$. So: $O(\sum\limits_{i=1}^s 2^{s-i} \cdot T \cdot i$ + $n \cdot log(n))$ is number of queries ( (we will have $2^{s-i}$ segments on the $s-i$-th level pf recursion, and for each of them log is $i$). Thus it's: $O(n \cdot log(n)$ + $T \cdot \sum\limits_{i=1}^s 2^{s-i} \cdot i)$. So: $O(n \cdot log(n)$ + $T \cdot n \cdot \sum\limits_{i=1}^s \frac{i}{2^{i}})$. It's $O(n \cdot log(n) + T \cdot n)$, cause that series converges to 2.
|
[
"divide and conquer",
"interactive"
] | 3,200
|
"#include <iostream>\n#include <vector>\n#include <functional>\n#include <numeric>\n#include <random>\n#include <map>\nusing namespace std;\n#define int long long\nconst int FSZ = 1e18;\nmt19937 rnd;\nint cntq=0;\nint ask(int id, int x) {\n cout << \"? \" << id + 1 << \" \" << x << endl;\n int ans;\n cin >> ans;\n ++cntq;\n return ans;\n}\nint n, L, value;\nvector<pair<int, int> > ans;\nint bs(int guy, int val, int l, int r){\n int ll=l, rr=r;\n while (rr - ll > 1){\n int mm = (ll+rr)/2;\n int res = ask(guy, mm);\n if (res == val) return mm;\n if (res < val) ll = mm;\n else rr = mm;\n }\n}\npair<vector<int>, vector<int> > kth(vector<int> men, int as, int K, int l, int r){\n if (men.size() == 1){\n return {men, {}};\n }\n int R = rnd() % men.size();\n vector<int> left, eql, right;\n int V = bs(men[R], (L/n)*as, l, r);\n eql.push_back(men[R]);\n int C = (L/n)*as;\n for (int i=0; i < men.size(); i++){\n if (i==R) continue;\n int T = ask(men[i], V);\n if (T < C) right.push_back(men[i]);\n if (T == C) eql.push_back(men[i]);\n if (T > C) left.push_back(men[i]);\n }\n while (left.size() < K && eql.size()){\n left.push_back(eql.back());\n eql.pop_back();\n }\n if (left.size() == K){\n value = V;\n while (eql.size()){\n right.push_back(eql.back());\n eql.pop_back();\n }\n return {left, right};\n }\n if (left.size() < K){\n pair<vector<int>, vector<int> > p = kth(right, as, K-left.size(), l, r);\n while (left.size()){\n p.first.push_back(left.back());\n left.pop_back();\n }\n return p;\n }\n while (eql.size()){\n right.push_back(eql.back());\n eql.pop_back();\n }\n pair<vector<int>, vector<int> > p = kth(left, as, K, l, r);\n while (right.size()){\n p.second.push_back(right.back());\n right.pop_back();\n }\n return p;\n}\nvoid divide(int start, int l, int r, vector<int> men){\n if (men.size() == 1){\n ans[men[0]] = {l, r};\n return;\n }\n int F = men.size() / 2;\n int as = start+F;\n pair<vector<int>, vector<int> > p = kth(men, as, F, l, r);\n int V = value;\n divide(start, l, V, p.first);\n divide(start+p.first.size(), V, r, p.second);\n}\nsigned main() {\n\t//ios_base::sync_with_stdio(false);\n\tcin >> n >> L;\n vector<int> men;\n for (int i=0; i < n;i++) men.push_back(i);\n ans.assign(n, {-1, -1});\n divide(0, 0, FSZ, men);\n cout << \"!\" << endl;\n\tfor (int i = 0; i < n; ++i)\n\t\tcout << ans[i].first << \" \" << ans[i].second << endl;\n cerr << \"Done \" << cntq << \" queries\\n\";\n\treturn 0;\n}"
|
1180
|
A
|
Alex and a Rhombus
|
While playing with geometric figures Alex has accidentally invented a concept of a $n$-th order rhombus in a cell grid.
A $1$-st order rhombus is just a square $1 \times 1$ (i.e just a cell).
A $n$-th order rhombus for all $n \geq 2$ one obtains from a $n-1$-th order rhombus adding all cells which have a common side with it to it (look at the picture to understand it better).
Alex asks you to compute the number of cells in a $n$-th order rhombus.
|
Looking into the picture attentively, one can realize that there are $2$ rows with one cell, $2$ rows with two cells, ..., and $1$ row with $n$ cells. Thus the answer can be easily computed by $O(n)$.
|
[
"dp",
"implementation",
"math"
] | 800
|
#include "bits/stdc++.h"
using namespace std;
int main() {
int n;
cin >> n;
cout << 2*n*n-2*n+1;
return 0;
}
|
1180
|
B
|
Nick and Array
|
Nick had received an awesome array of integers $a=[a_1, a_2, \dots, a_n]$ as a gift for his $5$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $a_1 \cdot a_2 \cdot \dots a_n$ of its elements seemed to him not large enough.
He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $i$ ($1 \le i \le n$) and do $a_i := -a_i - 1$.
For example, he can change array $[3, -1, -4, 1]$ to an array $[-4, -1, 3, 1]$ after applying this operation to elements with indices $i=1$ and $i=3$.
Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index.
Help Kolya and print the array with the maximal possible product of elements $a_1 \cdot a_2 \cdot \dots a_n$ which can be received using only this operation in some order.
If there are multiple answers, print any of them.
|
Initially, we are going to make a product maximal by absolute value. It means that if $a_i \geq 0$ we are going to apply described operation (i.e to increase the absolute value). Now if the product is already positive, it's the answer. Else to apply the operation to the minimal number is obviously optimal (if we applied the operation to any other number the result would not be greater by absolute value, but applying to the minimum we have received non-negative product already). Thus the solution works in $O(n)$.
|
[
"greedy",
"implementation"
] | 1,500
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nmain(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int n;\n cin >> n;\n vector<int> v(n);\n for (int i=0;i<n;i++) cin >> v[i];\n if (n != 3 || (v[0] != -3 || v[1] != -3 || v[2] != 2)){\n for (int i=0;i<n;i++){\n if (v[i] >= 0) v[i] = -v[i]-1;\n }\n if (n%2!=0){\n int mx = -1, ind = -1;\n for (int i=0;i < n; i++){\n if (abs(v[i]) > mx){\n mx = abs(v[i]);\n ind = i;\n }\n }\n v[ind] = -v[ind]-1;\n }\n }\n for (int i=0;i<n;i++) cout << v[i] << \" \";\n}"
|
1181
|
A
|
Chunga-Changa
|
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price $z$ chizhiks per coconut. Sasha has $x$ chizhiks, Masha has $y$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has $5$ chizhiks, Masha has $4$ chizhiks, and the price for one coconut be $3$ chizhiks. If the girls don't exchange with chizhiks, they will buy $1 + 1 = 2$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $6$ chizhiks, Masha will have $3$ chizhiks, and the girls will buy $2 + 1 = 3$ coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
|
It's easy to calculate how much coconuts we will buy: $k = \lfloor \frac{x + y}{z} \rfloor$ (suppose that all money transferred to a single person, this way the number of bought coconuts would be clearly maximal) If $k = \lfloor \frac{x}{z} \rfloor + \lfloor \frac{y}{z} \rfloor$, then the answer is $\langle k, 0 \rangle$. The remaining case is a bit harder. Let's notice, that there is no need to transfer $\ge z$ chizhiks, since the one transferring money could have used $z$ chizhiks to buy one more coconut herself. Also it's optimal to transfer coins such that the remainder modulo $z$ of the receiving part will turn to be exactly zero (we could have simply transfer less for the same effect). So the answer is $\langle k, \min (z - (x \bmod z), z - (y \bmod z)) \rangle$.
|
[
"greedy",
"math"
] | 1,000
| null |
1181
|
B
|
Split a Number
|
Dima worked all day and wrote down on a long paper strip his favorite number $n$ consisting of $l$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.
To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a \textbf{positive} integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.
Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.
|
Suppose that the number doesn't contain any zeros (that is, we can split it at any point). Than it is easy to show that it is enough to check only the following cuts: $k$; $k$, if the length of the number is $2k$. $k + 1$; $k$ and $k$; $k + 1$, if the length of the number is $2k + 1$. Some intuition behind this: it's not optimal to make "inbalanced" cuts. Because the sum $a + b$ is at least $max(a, b)$. And in case the maximum is large already, we could have built a more optimal answer if we would make a cut in a less "inbalanced" way. One can also examine not only $1-2$ possible cuts, but rather $\mathcal{O}(1)$ different options around the center, this way solution is a bit easier to proof. In case we have zeros, the solution is mostly the same: we just simply need to consider the closest valid cut to the left from center and closest valid cut to the right. And take a minimum of them. One can note that in the solution above we need to add and compare "long integers". One could have used a programming language in which they are already implemented (Python/Java) or implemented the required functions themselves. The number can be simply stored as a sequence of digits from least-important digit to the most-important. It's simple to implement the summation and comparing of such integers.
|
[
"greedy",
"implementation",
"strings"
] | 1,500
| null |
1181
|
C
|
Flag
|
Innokenty works at a flea market and sells some \sout{random stuff} rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $n \cdot m$ colored pieces that form a rectangle with $n$ rows and $m$ columns.
The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of \textbf{equal} heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.
Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.
\begin{center}
{\small These subrectangles are flags.}
\end{center}
\begin{center}
{\small These subrectangles are not flags.}
\end{center}
|
To start with, let's find a way to calculate the number of flags of width $1$. Let's bruteforce the row $r$ and column $c$ of the topmost cell of the middle part of the flag. So if the cell above has the same color as $(r, c)$ then clearly there can't be a flag here. Otherwise we are standing at the topmost position of the consecutive segment of cells of some color. Let's walk all this segment down and find its length $l$. Note, that all mentioned above works in $\mathcal{O}(nm)$, since each cell would be walked exactly once. And now we can spend additional $\Theta(l)$ time to check whether there exist a unicolored segments of length $l$ above our segment and below our segment, the solution still works in $\mathcal{O}(nm)$. So now we managed to find all "narrow" flags. The wide flag is simply a sequence of "narrow" flags of the common type (with the same value of $l$ and colors $color_1$, $color_2$, $color_3$ - color of the top, middle and bottom part of the flag). Let's bruteforce the topmost row $r$ of the middle part of the flag. Now bruteforce $c$ and find a narrowflag as suggested above (there might be no flag in $(r, c)$ though). And also maintain $w$: a maximum possible length of the flag backwards. In case $(l, color_1, color_2, color_3)$ are same as in $(r, c - 1)$, then we increase $w$ by one. Otherwise assign $1$ to $w$. Note that we in fact are iterating over all possible right-borders of the flag. And there are exactly $w$ possible left-borders. So we simply increase our answer by $w$ each time.
|
[
"brute force",
"combinatorics",
"dp",
"implementation"
] | 1,900
| null |
1181
|
D
|
Irrigation
|
Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first $n$ olympiads the organizers introduced the following rule of the host city selection.
The host cities of the olympiads are selected in the following way. There are $m$ cities in Berland wishing to host the olympiad, they are numbered from $1$ to $m$. The host city of each next olympiad is determined as the city that hosted the olympiad the \textbf{smallest} number of times before. If there are several such cities, the city with the \textbf{smallest} index is selected among them.
Misha's mother is interested where the olympiad will be held in some specific years. The only information she knows is the above selection rule and the host cities of the first $n$ olympiads. Help her and if you succeed, she will ask Misha to avoid flooding your house.
|
Let's solve all the queries simultaneously. For this purpose sort them all in increasing order. Sort all the countries based on the number of hosted competitions in the first $n$ years (see picture) How this diagram changes after several more years of the competition? The cells are filled from lower rows to the higher, while inside one row we order cells based on the country number. Let's fill this table from bottom upwards. For the queries which won't be replied in the current row, it is not important in which order the cells in the current row are colored, only the quantity is important. So for such queries we can simply accumulate the number of already painted cells so far. Now let's discuss the queries, which need to be answered in the current row. If we subtract from $k$ (the query parameter) the number $S$ of cells painted in previous rows, then we simply need to return the $k-s$-th element in this set. So in other words we need to add countries in the set and sometimes compute $i$-th element in it. One can use cartesian tree "treap" or a segment tree to do that. It may also turn out, that after we fill all the diagram, there are some questions unanswered yet. In this case we can notice, that all the subsequent rows look like the whole set of countries. So the answer is simply the remainder of $k - S$ modulo $m$. Since we only need to consider at most $n$ lines until the diagram is filled-up, the solution works in $\mathcal{O}((q + n + m) \log)$.
|
[
"binary search",
"data structures",
"implementation",
"sortings",
"trees",
"two pointers"
] | 2,200
| null |
1181
|
E2
|
A Story of One Country (Hard)
|
This problem differs from the previous problem only in constraints.
Petya decided to visit Byteland during the summer holidays. It turned out that the history of this country is quite unusual.
Initially, there were $n$ different countries on the land that is now Berland. Each country had its own territory that was represented as a rectangle on the map. The sides of the rectangle were parallel to the axes, and the corners were located at points with integer coordinates. Territories of no two countries intersected, but it was possible that some territories touched each other. As time passed, sometimes two countries merged into one. It only happened if the union of their territories was also a rectangle. In the end only one country remained — Byteland.
Initially, each country had a rectangular castle inside its territory. Its sides were parallel to the axes and its corners had integer coordinates. Some castles might touch the border of the corresponding country and sides or other castles. Miraculously, after all the unions the castles are still intact. Unfortunately, their locations are the only information we have to restore the initial territories of the countries.
\begin{center}
The possible formation of Byteland. The castles are shown in blue.
\end{center}
Petya wonders why no information about the initial countries remained. He suspected that the whole story is a fake. You were recommended to him as a smart person. Please check whether or not there exists a possible set of initial territories that could make the story true.
|
We can rephrase the problem as follows: There is a set of non-intersecting rectangles on the plane. Let's say, that some rectangular area on the plane is good, if it contains exactly one rectangle in it or there exists a vertical or horizontal cut, which cuts the area into two good areas. You are asked to check whether the area $[0; 10^9] \times [0; 10^9]$ is good. It's easy to see that it is exactly the same process as in the statement, except we don't merge countries into one, we look at the reversed process, where we split one country into many. Also let's notice, that when we found some cutting line, which doesn't goes through inner part of any rectangle, we can always apply it to separate our area into two. We can do that, since our predicate of set of rectangles being nice is monotonic: if we replace set of rectangles with its subset, it only can make better. Now let's analyze when the cut is good: This already gives us a solution in $\mathcal{O}(n^2 \log)$, which passes the easy version of the problem. Simply solve the problem recursively, sorting rectangles as shown above. (and symmetrically for horizontal cuts) and try finding a cut. Once we find it, solve the problem recursively. Now we have working time: $T(n) = T(x) + T(n - x) + \mathcal{O}(n \log n)$, where $x$ is a size of one part of the cut. The worse case is $x = 1$, so $T(n) = \mathcal{O}(n^2 \log)$. $\square$ For the full version we need a faster solution. The key idea is: let's cut always "smaller from larger". Suppose we are magically able to find any valid cut in $\mathcal{O}(1)$ (basically the number $x$). Then we could have spent $\mathcal{O}(x)$ to cut out the smaller part into new recursive call. While we can continue the process of cutting with the remaining rectangles in this recursion call. This solution works in $\mathcal{O}(n \log n)$: Each time the size of problem reduces at least twice when we go into recursion, so there are only $\log$ levels. However we need to handle "magic" here. For example one could have used a segment tree to implement all mentioned above (it would give a $\mathcal{O}(n \log^2)$ time). But there is a simpler solution! Let's sort rectangles using all $4$ possible sortings. And let's iterate over all this sortings simultaneously. We need $4$ directions instead of $2$, because if we would e.g. only iterate from let to right, we wouldn't be able to cut out the "smaller" from "larger", in case the "smaller" is to the right of "larger". So we want to both go from left to right and from right to left. When in one of the directions we see a valid place to make a cut, we remove all the rectangles into the separate recursion call. We also mark all those rectangles in the current recursion call as deleted and start the procedure of cutting again. We can simply skip the rectangles marked as deleted when we encounter them. For example we could use a linked list for that: So now we got a solution in $\mathcal{O}(n \log^2)$: one logarithm is from cutting smaller from larger and one logarithm is from sorting. One could drop the second logarithm. For that we should sort all rectangles at the beginning and then carefully pass the correct ordering down the recursion. But that wasn't required.
|
[
"brute force",
"greedy",
"sortings"
] | 3,000
| null |
1182
|
A
|
Filling Shapes
|
You have a given integer $n$. Find the number of ways to fill all $3 \times n$ tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
\begin{center}
This picture describes when $n = 4$. The left one is the shape and the right one is $3 \times n$ tiles.
\end{center}
|
If you want to have no empty spaces on $3 \times n$ tiles, you should fill leftmost bottom tile. Then you have only 2 choices; Both cases force you to group leftmost $3 \times 2$ tiles and fill. By this fact, we should group each $3 \times 2$ tiles and fill independently. So the answer is - if $n$ is odd, then the answer is $0$ (impossible), otherwise, the answer is $2^{\frac{n}{2}}$. Time complexity is $O(1)$ with bit operation or $O(n)$ with iteration.
|
[
"dp",
"math"
] | 1,000
|
#include <stdio.h>
int main(void){
int n; scanf("%d", &n);
if(n%2==0) printf("%d", 1<<(n/2));
else printf("0");
return 0;
}
|
1182
|
B
|
Plus from Picture
|
You have a given picture with size $w \times h$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:
- A "+" shape has one center nonempty cell.
- There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.
- All other cells are empty.
Find out if the given picture has single "+" shape.
|
First, try to find if there is any nonempty space which has 4 neighbors are all nonempty spaces. (Giant black star in the picture below.) If there is no such nonempty space, the answer is "NO". Second, try to search the end of the "+" shape from the center. (White stars in the picture below.) Third, try to find if there is any nonempty space outside of "+" shape(the area filled with "?"). If found then the answer is "NO". If you validated all steps, then the answer is "YES". Time complexity is $O(wh)$.
|
[
"dfs and similar",
"implementation",
"strings"
] | 1,300
|
#include <iostream>
#include <string>
#include <vector>
int main(void){
int w, h; std::cin >> h >> w;
std::vector<std::string> picture(h);
for(int i=0; i<h; i++) std::cin >> picture[i];
std::vector<std::vector<bool>> should_be_plus(h, std::vector<bool>(w, false));
for(int i=1; i<h-1; i++){
for(int j=1; j<w-1; j++){
if(picture[i][j] == '*' && picture[i-1][j] == '*' && picture[i+1][j] == '*'
&& picture[i][j+1] == '*' && picture[i][j-1] == '*'){ // Center found
int upend = i, downend = i, leftend = j, rightend = j;
while(upend >= 0 && picture[upend][j] == '*') should_be_plus[upend--][j] = true;
while(downend < h && picture[downend][j] == '*') should_be_plus[downend++][j] = true;
while(leftend >= 0 && picture[i][leftend] == '*') should_be_plus[i][leftend--] = true;
while(rightend < w && picture[i][rightend] == '*') should_be_plus[i][rightend++] = true;
//printf("End: up %d down %d left %d right %d\n", upend, downend, leftend, rightend);
// If there is outside area exist then NO.
for(int i2=0; i2<h; i2++) for(int j2=0; j2<w; j2++){
if(should_be_plus[i2][j2] != (picture[i2][j2] == '*')){
//std::cout << "Outside found ";
std::cout << "NO\n";
return 0;
}
}
// Ok
std::cout << "YES\n";
return 0;
}
}
}
//std::cout << "No center found ";
std::cout << "NO\n";
return 0;
}
|
1182
|
C
|
Beautiful Lyrics
|
You are given $n$ words, each of which consists of lowercase alphabet letters. Each word \textbf{contains at least} one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.
Each lyric consists of two lines. Each line consists of two words separated by whitespace.
A lyric is beautiful if and only if it satisfies all conditions below.
- The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line.
- The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line.
- The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel.
Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is \textbf{never} vowel.
For example of a beautiful lyric,
\begin{center}
"hello hellooowww" "whatsup yowowowow"
\end{center}
is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o".For example of a not beautiful lyric,
\begin{center}
"hey man""iam mcdic"
\end{center}
is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.
|
Let's make some definitions; $s_{1}$ and $s_{2}$ are complete duo if two word $s_{1}$ and $s_{2}$ have same number of vowels and the last vowels of $s_{1}$ and $s_{2}$ are same. For example, "hello" and "hollow" are complete duo. $s_{1}$ and $s_{2}$ are semicomplete duo if two word $s_{1}$ and $s_{2}$ have same number of vowels but the last vowels of $s_{1}$ and $s_{2}$ are different. For example, "hello" and "hola" are semicomplete duo. If you want to form a beautiful lyric with $4$ words, then the lyric must be one of the things listed below; Consist of two complete duos. Consist of one semicomplete duo and one complete duo. Since the order of lyrics is not important, make complete duos as many as possible, then make semicomplete duos as many as possible. This can be done with the greedy approach with the usage of the red-black tree or hashmap. After you formed all duos, make beautiful lyrics using one semicomplete duo and one complete duo first, then make beautiful lyrics using two complete duos. With this method, you can make the maximum possible number of beautiful lyrics. Time complexity is $O(n \text{ log } n)$ or $O(n)$.
|
[
"data structures",
"greedy",
"strings"
] | 1,700
|
#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <map>
// Typedef
typedef std::pair<std::string, std::string> strduo;
// Vowel related
bool isVowel(char c){
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int vowelCount(std::string &word){
int count = 0;
for(auto ch: word) if(isVowel(ch)) count++;
return count;
}
char lastVowel(std::string &word){
for(int i=word.length()-1; i>=0; i--){
if(isVowel(word[i])) return word[i];
} throw "No vowels";
}
int main(void){
// Get input
int n; std::cin >> n;
std::vector<std::string> totalwords;
std::map<int, std::map<char, std::vector<std::string>>> strings_by_vowels;
for(int i=0; i<n; i++){
std::string word; std::cin >> word;
totalwords.push_back(word);
int vowelcount = vowelCount(word);
char lastvowel = lastVowel(word);
strings_by_vowels[vowelcount][lastvowel].push_back(word);
}
/*for(auto it: strings_by_vowels){
printf("Vowel count %2d:\n", it.first);
for(auto it2: it.second){
printf(" %c: ", it2.first);
for(auto it3: it2.second) printf("%s ", it3.c_str()); printf("\n");
}
}
printf("===============\n");*/
// Construct duos; Complete: SameCount+SameLast, Semicomplete: SameCount
std::vector<strduo> complete_duos, semicomplete_duos;
for(auto &same_counts: strings_by_vowels){
// Complete duos
for(auto &same_lasts: same_counts.second){
while(same_lasts.second.size() >= 2){
std::string firstline = same_lasts.second.back();
same_lasts.second.pop_back();
std::string secondline = same_lasts.second.back();
same_lasts.second.pop_back();
complete_duos.push_back({firstline, secondline});
}
}
// Semicomplete duos
std::vector<std::string> remainings;
for(auto &same_lasts: same_counts.second){
for(auto &word: same_lasts.second) remainings.push_back(word);
same_lasts.second.clear();
}
while(remainings.size() >= 2){
std::string firstline = remainings.back(); remainings.pop_back();
std::string secondline = remainings.back(); remainings.pop_back();
semicomplete_duos.push_back({firstline, secondline});
}
}
// Construct lyrics
std::vector<strduo> wholeLyric;
while(!semicomplete_duos.empty() && !complete_duos.empty()){
strduo semicomplete_duo = semicomplete_duos.back();
semicomplete_duos.pop_back();
strduo complete_duo = complete_duos.back();
complete_duos.pop_back();
wholeLyric.push_back({semicomplete_duo.first, complete_duo.first});
wholeLyric.push_back({semicomplete_duo.second, complete_duo.second});
}
while(complete_duos.size() >= 2){
strduo complete_duo1 = complete_duos.back(); complete_duos.pop_back();
strduo complete_duo2 = complete_duos.back(); complete_duos.pop_back();
wholeLyric.push_back({complete_duo1.first, complete_duo2.first});
wholeLyric.push_back({complete_duo1.second, complete_duo2.second});
}
// Print
std::cout << wholeLyric.size() / 2 << '\n';
for(strduo &lyric: wholeLyric) std::cout << lyric.first << ' ' << lyric.second << '\n';
return 0;
}
|
1182
|
D
|
Complete Mirror
|
You have given tree consist of $n$ vertices. Select a vertex as root vertex that satisfies the condition below.
- For all vertices $v_{1}$ and $v_{2}$, if $distance$($root$, $v_{1}$) $= distance$($root$, $v_{2})$ then $degree$($v_{1}$) $= degree$($v_{2}$), where $degree$ means the number of vertices connected to that vertex, and $distance$ means the number of edges between two vertices.
Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them.
|
First, the valid tree should form like the picture below unless the whole tree is completely linear. top: This node is the top of the tree. This node has always degree $1$. This node is always one of the possible answers of valid tree. There might be no top node in the tree. semitop: This node is the closest children from the top node that satisfies $degree >= 3$. In other words, this node is the end of the leaf branch which includes top node as leaf. This node can be one of the possible answers of valid tree. If there is no semitop in the tree, the whole tree is invalid. mid level: This is the area of nodes between semitop node and semibottom nodes. semibottom: These nodes are the closest ancestors from each leaf nodes which satisfies $degree >= 3$. In other words, these nodes are the end of each leaf branches. bottom: These nodes are the leaves except top node. And also let's define $u_{1}$ and $u_{2}$ are directly reachable if there are only nodes with $degree = 2$ between $u_{1}$ and $u_{2}$ exclusive. There are two ways to find the top node and the semitop node. Lawali's solution. Find the diameter path and validate for two leaves of the diameter path. If no valid vertex found(i.e. top is not in the diameter path), then the semitop should be the middle of the diameter path. Now validate for the semitop and the closest directly reachable leaf from semitop. If any valid vertex found, print it. Otherwise print $-1$. The first case of diameter path in valid tree. Semitop node is the middle of diameter path. The second case of diameter path in valid tree. Top node is the end of diameter path. The first case of diameter path in valid tree. Semitop node is the middle of diameter path. The second case of diameter path in valid tree. Top node is the end of diameter path. The second case of diameter path in valid tree. Top node is the end of diameter path. McDic's solution. Clone the whole tree and cut the leaf branches(include top) from the cloned tree. Let's call this tree as "inner tree". Inner tree consists of only semitop, mid level nodes and semibottom nodes. Then you can find the semitop by collapsing each level from leaf nodes of inner tree. Now validate for semitop, the furthest directly reachable leaf node from semitop, and the closest directly reachable leaf node from semitop. It is guaranteed that the top node is one of those two leaves. If any valid vertex found, print it. Otherwise print $-1$. This is the inner tree of original tree. You can find the semitop easier than before since top is removed in inner tree. This is the inner tree of original tree. You can find the semitop easier than before since top is removed in inner tree. Time complexity is $O(n)$.
|
[
"constructive algorithms",
"dfs and similar",
"dp",
"hashing",
"implementation",
"trees"
] | 2,400
|
#include <stdio.h>
#include <vector>
#include <set>
#include <utility>
#include <algorithm>
// Graph attributes
typedef std::vector<std::set<int>> EDGE;
int v;
std::vector<bool> isInner;
EDGE edges, inneredges;
// Validation
bool validate(int root){
//printf("Validating for %d\n", root);
std::vector<bool> visited(v+1, false);
std::vector<int> nowlook = {root};
while(!nowlook.empty()){
std::set<int> degrees;
std::vector<int> nextlook;
for(auto now: nowlook) visited[now] = true;
for(auto now: nowlook){
for(auto next: edges[now]){
if(!visited[next]){
nextlook.push_back(next);
degrees.insert(edges[next].size());
if(degrees.size() >= 2) return false;
}
}
} nowlook = nextlook;
} return true;
}
// Calculate distances for directly reachable nodes. -1 for not set.
void directDistanceCalculation(int now, std::vector<int> &distance){
for(auto next: edges[now]){
if(distance[next] == -1 && edges[next].size() <= 2){
distance[next] = distance[now]+1;
directDistanceCalculation(next, distance);
}
}
}
int main(void){
// Get input and construct tree
scanf("%d", &v);
edges.resize(v+1);
isInner.resize(v+1, true);
for(int i=1; i<v; i++){
int u1, u2; scanf("%d %d", &u1, &u2);
edges[u1].insert(u2);
edges[u2].insert(u1);
} inneredges = edges;
// Construct inner tree
//printf("Constructing inner tree:\n");
for(int start=1; start<=v; start++){
if(edges[start].size() == 1 && inneredges[start].size() == 1){
int now = start;
while(edges[now].size() <= 2 && inneredges[now].size() == 1){
//printf("Removing %d\n", now);
int next = *(inneredges[now].begin());
inneredges[now].clear();
inneredges[next].erase(now);
isInner[now] = false;
now = next;
}
}
}
// Corner case: No inner tree => See leaf
//printf("Let's see if this is corner case\n");
int innervertices = 0;
std::vector<int> leaves;
for(int u=1; u<=v; u++){
if(isInner[u]) innervertices++;
if(edges[u].size() == 1) leaves.push_back(u);
}
if(innervertices == 0){
//printf("ok no inner\n");
for(auto leaf: leaves){
if(validate(leaf)){
printf("%d\n", leaf);
return 0;
}
}
throw "???";
}
// Collapse inner tree
//printf("Let's collapse inner tree\n");
std::vector<bool> collapseVisited(v+1, false);
std::vector<int> nowlook;
for(int u=1; u<=v; u++) if(isInner[u] && inneredges[u].size() <= 1) nowlook.push_back(u);
while(nowlook.size() >= 2){
std::set<int> nextlook;
for(auto now: nowlook) collapseVisited[now] = true;
for(auto now: nowlook) for(auto next: inneredges[now]) if(!collapseVisited[next]) nextlook.insert(next);
nowlook.clear();
for(auto next: nextlook) nowlook.push_back(next);
}
// Corner case 2: No semitop
if(nowlook.empty()){
printf("-1\n");
return 0;
}
// Semitop validation
int semitop = nowlook[0];
//printf("Ok semitop is %d\n", semitop);
if(validate(semitop)){
printf("%d\n", semitop);
return 0;
}
// Calculate distances for directly reachable leaves
std::vector<int> dirDist(v+1, -1);
dirDist[semitop] = 0;
directDistanceCalculation(semitop, dirDist);
std::vector<std::pair<int, int>> directLeaves;
for(int u=1; u<=v; u++){
if(edges[u].size() == 1 && dirDist[u] != -1)
directLeaves.push_back({dirDist[u], u});
} std::sort(directLeaves.begin(), directLeaves.end());
// Validate for the furthest leaf and the closest leaf
if(!directLeaves.empty()){
int closestLeaf = directLeaves.front().second;
int furthestLeaf = directLeaves.back().second;
if(validate(closestLeaf)){
printf("%d\n", closestLeaf);
return 0;
}
else if(validate(furthestLeaf)){
printf("%d\n", furthestLeaf);
return 0;
}
}
printf("-1\n");
return 0;
}
|
1182
|
E
|
Product Oriented Recurrence
|
Let $f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3}$ for $x \ge 4$.
You have given integers $n$, $f_{1}$, $f_{2}$, $f_{3}$, and $c$. Find $f_{n} \bmod (10^{9}+7)$.
|
You can form the expression into this; $c^{x} f_{x} = c^{x-1} f_{x-1} \cdot c^{x-2} f_{x-2} \cdot c^{x-3} f_{x-3}$ Let $g(x, p) = c^{x} f_{x}$'s $p$-occurrence for prime number $p$. For example, $40 = 2^{3} \times 5$ so $40$'s $2$-occurrence is $3$. Then we can set the formula $g(x, p) = g(x-1, p) + g(x-2, p) + g(x-3, p)$ and calculate $g(n, p)$ using matrix exponentiation. Since all different prime numbers $p$ share same matrix, we can calculate matrix only once. And we have less or equal than 36 distinct prime numbers targeted because you cannot get more than $9$ distinct prime numbers by prime decomposition from numbers in range $[1, 10^9]$. With $g(x, p)$ we can calculate $c^{n} f_{n}$, and we can calculate $f_{n}$ using modulo inverse. Time complexity is $O(\text{log } n + \text{ sqrt}(\text{max}(f_{1}, f_{2}, f_{3}, c)))$.
|
[
"dp",
"math",
"matrices",
"number theory"
] | 2,300
|
#include <stdio.h>
#include <vector>
#include <set>
#include <map>
// Constants
typedef long long int lld;
const lld R = 1000 * 1000 * 1000 + 7; // a^(R-1) = 1 (mod R)
const lld matrixRemainder = R-1;
// Matrix class
class matrix{
public:
// Attributes
int row, col;
std::vector<std::vector<lld>> num;
// Constructor
matrix(int row, int col, int defaultValue = 0){
this->num = std::vector<std::vector<lld>>(row, std::vector<lld>(col, defaultValue));
this->row = row, this->col = col;
}
matrix(std::vector<std::vector<lld>> num){
this->num = num;
this->row = this->num.size();
this->col = this->num[0].size();
}
// Operator
matrix operator *(matrix &another){
if(this->col != another.row){
printf("Wrong size: %d*%d X %d*%d\n", this->row, this->col, another.row, another.col);
throw "Wrong size";
}
matrix newone(this->row, another.col);
for(int r=0; r<newone.row; r++) for(int c=0; c<newone.col; c++){
for(int k=0; k<this->col; k++){
newone.num[r][c] += this->num[r][k] * another.num[k][c];
newone.num[r][c] %= matrixRemainder;
}
} return newone;
}
// Power
matrix operator ^(lld x){
if(x==0){
printf("Not implemented yet.\n");
throw "Not implemented";
}
else if(x==1) return *this;
else{
matrix halfpower = (*this) ^ (x/2);
if(x%2 == 0) return halfpower * halfpower;
else return halfpower * halfpower * (*this);
}
}
};
// Prime related
const int limit = 1<<20;
bool isPrime[limit] = {false, };
std::vector<lld> primes;
// Decomposite given value to primes
std::vector<lld> primeDecomposition(lld x){
std::vector<lld> answer;
for(lld p: primes){
if(x <= 1) break;
else if(x%p == 0){
answer.push_back(p);
while(x%p == 0) x /= p;
}
else if(p*p > x){
answer.push_back(x);
break;
}
} return answer;
}
// Return a^x % R
lld power(lld a, lld x){
if(x==0) return 1;
lld half = power(a, x/2);
if(x%2 == 0) return half*half%R;
else return half*half%R*a%R;
}
// Main function
int main(void){
// Matrix functionality testing
//matrix a1({{1, 2}, {0, 1}}), a2({{3, 2}, {-1, 0}});
//matrix b = a1*a2;
//printf("a1*a2 = \n %lld %lld\n %lld %lld\n", b.num[0][0], b.num[0][1], b.num[1][0], b.num[1][1]);
// Calculate primes
for(int i=2; i<limit; i++) isPrime[i] = true;
for(int i=2; i<limit; i++) if(isPrime[i]){
primes.push_back((lld)i);
for(int j=2*i; j<limit; j+=i) isPrime[j] = false;
}
// Get input
lld n, f[4], c; scanf("%lld %lld %lld %lld %lld", &n, &f[1], &f[2], &f[3], &c);
matrix baseLogPropagate({{1, 1, 1}, {1, 0, 0}, {0, 1, 0}});
matrix totalLogPropagate = baseLogPropagate ^ (n-3);
// Calculate target primes
std::set<lld> knownprimes;
for(int i=1; i<=3; i++) for(lld p: primeDecomposition(f[i])) knownprimes.insert(p);
for(lld p: primeDecomposition(c)) knownprimes.insert(p);
//printf("Known primes: "); for(lld knownprime: knownprimes) printf("%lld, ", knownprime); printf("\n");
// Calculate c^n * f[n]'s prime count: initPrimeCount[x]: f[3-x]'s p-occurrence
std::map<lld, lld> fnPrimeCount;
for(lld p: knownprimes){
matrix initPrimeCount(3, 1);
for(int i=1; i<=3; i++){
for(lld num = f[i]; num%p == 0; num /= p) initPrimeCount.num[3-i][0]++; // f[n]
for(lld num = c; num%p == 0; num /= p) initPrimeCount.num[3-i][0] += i; // c^n
}
matrix lastPrimeCount = totalLogPropagate * initPrimeCount;
fnPrimeCount[p] = lastPrimeCount.num[0][0];
}
// Calculate answer = product(p^fnPrimeCount[p]) * c^(-n)
lld answer = 1;
for(auto pinfo: fnPrimeCount){
//printf("%lld-occurrence = %lld\n", pinfo.first, pinfo.second);
answer *= power(pinfo.first, pinfo.second);
answer %= R;
}
answer *= power(power(c, R-2), n); answer %= R;
printf("%lld\n", answer);
return 0;
}
|
1182
|
F
|
Maximum Sine
|
You have given integers $a$, $b$, $p$, and $q$. Let $f(x) = \text{abs}(\text{sin}(\frac{p}{q} \pi x))$.
Find minimum possible integer $x$ that maximizes $f(x)$ where $a \le x \le b$.
|
Lemma: For all $x$, $y$ $\in [0, \pi]$, if $|\text{sin}(x)| > |\text{sin}(y)|$ then $x$ is more closer to the $\frac{\pi}{2}$ than $y$. With this lemma, we can avoid the calculation of floating precision numbers. Let's reform the problem; Find minimum possible integer $x$ that $\frac{p}{q}x \pi \bmod \pi$ is the closest to $\frac{\pi}{2}$. This is equivalent to find minimum possible integer $x$ that $2px \bmod 2q$ is the closest to $q$. Let $g(x) = 2px \bmod 2q$. Now set the interval with length $t = \text{sqrt}(b-a+1)$ and construct the list like this - $[(g(a), a), (g(a+1), a+1), \ldots (g(a+t-1), a+t-1)]$. Then remove the big number $x$s with duplicated $g(x)$ values from the list and sort the list. Now we can find any $x$ that $g(x)$ is the closest to any integer $y$ in $O(\text{log}(n))$. We will search all numbers in range $[a, b]$ without modifying the list we created. How is this possible? Because $g(x) + g(y) \equiv g(x+y) \pmod{2q}$ for all integers $x$, $y$. So in every $\text{sqrt}(b-a+1)$ iterations, we can set the target and just find. More precisely, our target value is $q - 2 \times i \cdot t \cdot p \bmod 2q$ for $i$-th iteration. With this search, we can find such minimum possible integer $x$. Oh, don't forget to do bruteforce in remaining range! The time complexity is $O(\text{sqrt } n \text{ log } n)$.
|
[
"binary search",
"data structures",
"number theory"
] | 2,700
|
#include <stdio.h>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
typedef long long int lld;
const lld infL = 1LL << 60;
// Find x that abs(sin(p/q pi x)) is the largest in [start, end).
int solve(lld start, lld end, lld p, lld q){
// Construct base intervals
lld interval = 1;
while(interval * interval < end - start) interval++;
// Period is q/p. x should be the closest to the middle of period(q/2p).
// x % (2q/2p) should be the closest to q/2p => 2px % 2q should be the closest to q.
// Construct remainders
std::vector<std::pair<lld, lld>> remainders, remainders_copy;
for(lld i=start; i<start+interval; i++){
lld key = 2*p*i % (2*q);
remainders.push_back({key, i});
}
std::sort(remainders.begin(), remainders.end());
remainders_copy = remainders; remainders.clear();
remainders.push_back(remainders_copy[0]);
for(int i=1; i<remainders_copy.size(); i++){
if(remainders_copy[i].first != remainders_copy[i-1].first)
remainders.push_back(remainders_copy[i]);
} remainders_copy.clear();
// Look in [start + i*interval, start + (i+1)*interval), start + (i+1)*interval <= end.
// x + i*interval ~= q/2p => x ~= q/2p - i*interval.
//printf("base interval = %lld\n", interval);
lld answervalue = -1, answerdistance = infL, iteration = 0;
for(iteration = 0; start + (iteration+1)*interval <= end; iteration++){
lld look = q - iteration * interval * 2 * p; // iteration * interval <= interval^2 <= end - start <= 10^8
look %= (2*q); if(look < 0) look += 2*q;
//printf("Looking %lld in [%lld, %lld)\n", look, start + iteration*interval, start + (iteration+1)*interval);
lld baseindex = std::lower_bound(remainders.begin(), remainders.end(), std::make_pair(look, -infL)) - remainders.begin();
for(int j=0; j>=-1; j--){
lld thisindex = (baseindex+j) % remainders.size(); if(thisindex < 0) thisindex += remainders.size();
lld thisvalue = remainders[thisindex].second + iteration * interval;
lld thisdistance = look - remainders[thisindex].first;
if(thisdistance < 0) thisdistance *= -1;
if(thisdistance > q) thisdistance = 2*q - thisdistance;
//printf(" Looking baseindex = %lld, thisindex = %lld, thisfirst = %lld, thisvalue = %lld (distance %lld)\n",
// baseindex, thisindex, thisvalue, remainders[thisindex].first, thisdistance);
if(std::make_pair(thisdistance, thisvalue) < std::make_pair(answerdistance, answervalue)){
answervalue = thisvalue;
answerdistance = thisdistance;
//printf(" Answer changed to %lld (distance %lld)\n", answervalue, answerdistance);
}
}
}
// Brute force for remaining ranges
for(lld v = start + iteration * interval; v < end; v++){
//printf("Looking %lld\n", v);
lld thisdistance = (2*p*v) % (2*q) - q; if(thisdistance < 0) thisdistance *= -1;
if(std::make_pair(thisdistance, v) < std::make_pair(answerdistance, answervalue)){
answerdistance = thisdistance;
answervalue = v;
//printf(" Answer changed to %lld (distance %lld)\n", answervalue, answerdistance);
}
}
return answervalue;
}
int main(void){
int testcases; scanf("%d", &testcases);
for(int t=0; t<testcases; t++){
lld a, b, p, q; scanf("%lld %lld %lld %lld", &a, &b, &p, &q);
//printf("Case #%d: ", t+1);
printf("%d\n", solve(a, b+1, p, q));
}
return 0;
}
|
1183
|
A
|
Nearest Interesting Number
|
Polycarp knows that if the sum of the digits of a number is divisible by $3$, then the number itself is divisible by $3$. He assumes that the numbers, the sum of the digits of which is divisible by $4$, are also somewhat interesting. Thus, he considers a positive integer $n$ interesting if its sum of digits is divisible by $4$.
Help Polycarp find the nearest larger or equal interesting number for the given number $a$. That is, find the interesting number $n$ such that $n \ge a$ and $n$ is minimal.
|
Even if we will iterate over all possible numbers starting from $a$ and check if sum of digits of the current number is divisible by $4$, we will find the answer very fast. The maximum possible number of iterations is no more than $5$.
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int sum(int a) {
int result = 0;
while (a > 0) {
result += a % 10;
a /= 10;
}
return result;
}
int main() {
int a;
cin >> a;
while (sum(a) % 4 != 0) {
a++;
}
cout << a << endl;
}
|
1183
|
B
|
Equalize Prices
|
There are $n$ products in the shop. The price of the $i$-th product is $a_i$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.
In fact, the owner of the shop can change the price of some product $i$ in such a way that the difference between the old price of this product $a_i$ and the new price $b_i$ is at most $k$. In other words, the condition $|a_i - b_i| \le k$ should be satisfied ($|x|$ is the absolute value of $x$).
He can change the price for each product \textbf{not more than once}. Note that he can leave the old prices for some products. The new price $b_i$ of each product $i$ should be positive (i.e. $b_i > 0$ should be satisfied for all $i$ from $1$ to $n$).
Your task is to find out the \textbf{maximum} possible \textbf{equal} price $B$ of \textbf{all} productts with the restriction that for all products the condiion $|a_i - B| \le k$ should be satisfied (where $a_i$ is the old price of the product and $B$ is the same new price of all products) or report that it is impossible to find such price $B$.
\textbf{Note that the chosen price $B$ should be integer}.
You should answer $q$ independent queries.
|
It is very intuitive that the maximum price we can obtain is $min + k$ where $min$ is the minimum value in the array. For this price we should check that we can change prices of all products to it. It can be done very easily: we can just check if each segment $[a_i - k; a_i + k]$ covers the point $min + k$. But this is not necessary because if we can change the price of the maximum to this value ($min + k$) then we can change each price in the segment $[min; max]$ to this value. So we just need to check that $min + k \ge max - k$ and if it is then print $min + k$ otherwise print -1.
|
[
"math"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int j = 0; j < n; ++j) {
cin >> a[j];
}
int mn = *min_element(a.begin(), a.end());
int mx = *max_element(a.begin(), a.end());
if (mx - mn > 2 * k) cout << -1 << endl;
else cout << mn + k << endl;
}
return 0;
}
|
1183
|
C
|
Computer Game
|
Vova is playing a computer game. There are in total $n$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $k$.
During each turn Vova can choose what to do:
- If the current charge of his laptop battery is strictly greater than $a$, Vova can just play, and then the charge of his laptop battery will decrease by $a$;
- if the current charge of his laptop battery is strictly greater than $b$ ($b<a$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $b$;
- if the current charge of his laptop battery is less than or equal to $a$ and $b$ at the same time then Vova cannot do anything and loses the game.
\textbf{Regardless of Vova's turns the charge of the laptop battery is always decreases}.
Vova wants to complete the game (Vova can complete the game if after each of $n$ turns the charge of the laptop battery is \textbf{strictly greater than $0$}). Vova has to play \textbf{exactly $n$ turns}. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (\textbf{first type turn}) is the \textbf{maximum} possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the \textbf{maximum} possible number of turns Vova can just play (make the \textbf{first type turn}) or report that Vova cannot complete the game.
You have to answer $q$ independent queries.
|
Firstly, about the problem description. Vova really needs to complete the game i. e. play all $n$ turns. Exactly $n$ turns. Among all possible ways to do it he need choose one where the number of turns when he just plays (this is the first type turn!) is maximum possible. Suppose the answer is $n$. Then the charge of the battery after $n$ turns will be $c = k - na$. If this value is greater than $0$ then the answer is $n$. Otherwise we need to replace some turns when Vova just plays with turns when Vova plays and charges. The charge of the battery will increase by $diff = a - b$ avfter one replacement. We have to obtain $c > 0$ with some replacements. The number of turns to do it is equals to $turns = \lceil\frac{-c + 1}{diff}\rceil$, where $\lceil\frac{x}{y}\rceil$ is $x$ divided by $y$ rounded up. If $turns > n$ then the answer is -1. Otherwise the answer is $n - turns$.
|
[
"binary search",
"math"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
long long k, n, a, b;
cin >> k >> n >> a >> b;
k -= n * a;
if (k > 0) {
cout << n << endl;
} else {
k = -k;
++k;
long long diff = a - b;
long long turns = (k + diff - 1) / diff;
if (turns > n) {
cout << -1 << '\n';
} else {
cout << n - turns << '\n';
}
}
}
return 0;
}
|
1183
|
D
|
Candy Box (easy version)
|
\textbf{This problem is actually a subproblem of problem G from the same contest.}
There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad).
\textbf{It is possible that multiple types of candies are completely absent from the gift}. It is also possible that \textbf{not all candies} of some types will be taken to a gift.
Your task is to find out the \textbf{maximum} possible size of the single gift you can prepare using the candies you have.
You have to answer $q$ independent queries.
\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}
|
Let's calculate the array $cnt$ where $cnt_i$ is the number of candies of the $i$-th type. Let's sort it in non-ascending order. Obviously, now we can take $cnt_1$ because this is the maximum number of candies of some type in the array. Let $lst$ be the last number of candies we take. Initially it equals $cnt_1$ (and the answer $ans$ is initially the same number). Then let's iterate over all values of $cnt$ in order from left to right. If the current number $cnt_i$ is greater than or equal to the last taken number of candies $lst$ then we cannot take more candies than $lst - 1$ (because we iterating over values of $cnt$ in non-ascending order), so let's increase answer by $lst - 1$ and set $lst := lst - 1$. Otherwise $cnt_i < lst$ and we can take all candies of this type, increase the answer by $cnt_i$ and set $lst := cnt_i$.
|
[
"greedy",
"sortings"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int t = 0; t < q; ++t) {
int n;
cin >> n;
vector<int> cnt(n + 1);
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
++cnt[x];
}
sort(cnt.rbegin(), cnt.rend());
int ans = cnt[0];
int lst = cnt[0];
for (int i = 1; i <= n; ++i) {
if (lst == 0) break;
if (cnt[i] >= lst) {
ans += lst - 1;
lst -= 1;
} else {
ans += cnt[i];
lst = cnt[i];
}
}
cout << ans << endl;
}
return 0;
}
|
1183
|
E
|
Subsequences (easy version)
|
\textbf{The only difference between the easy and the hard versions is constraints}.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string $s$ consisting of $n$ lowercase Latin letters.
In one move you can take \textbf{any} subsequence $t$ of the given string and add it to the set $S$. The set $S$ can't contain duplicates. This move costs $n - |t|$, where $|t|$ is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set $S$ of size $k$ or report that it is impossible to do so.
|
The topic of this problem is BFS. Let strings be the vertices of the graph and there is a directed edge from string $s$ to string $t$ if and only if we can obtain $t$ from $s$ by removing exactly one character. In this interpretation we have to find first $k$ visited vertices if we start our BFS from the initial string. And then the answer will be just $nk$ minus the sum of length of visited strings. The last thing to mention: instead of standard queue of integers we need to maintain the queue of strings and instead of array of visited vertices we have to maintain the set of visited strings. Don't forget to stop BFS when you obtain exactly $k$ strings. If the number of distinct subsequences is less than $k$ then the answer is -1.
|
[
"dp",
"graphs",
"implementation",
"shortest paths"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
string s;
cin >> s;
int ans = 0;
queue<string> q;
set<string> st;
q.push(s);
st.insert(s);
while (!q.empty() && int(st.size()) < k) {
string v = q.front();
q.pop();
for (int i = 0; i < int(v.size()); ++i) {
string nv = v;
nv.erase(i, 1);
if (!st.count(nv) && int(st.size()) + 1 <= k) {
q.push(nv);
st.insert(nv);
ans += n - nv.size();
}
}
}
if (int(st.size()) < k) cout << -1 << endl;
else cout << ans << endl;
return 0;
}
|
1183
|
F
|
Topforces Strikes Back
|
One important contest will take place on the most famous programming platform (Topforces) very soon!
The authors have a pool of $n$ problems and should choose \textbf{at most three} of them into this contest. The prettiness of the $i$-th problem is $a_i$. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be \textbf{maximum possible}).
But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are $x, y, z$, then $x$ should be divisible by neither $y$, nor $z$, $y$ should be divisible by neither $x$, nor $z$ and $z$ should be divisible by neither $x$, nor $y$. If the prettinesses of chosen problems are $x$ and $y$ then neither $x$ should be divisible by $y$ nor $y$ should be divisible by $x$. Any contest composed from one problem is considered good.
Your task is to find out the maximum possible total prettiness of the contest composed of \textbf{at most three} problems from the given pool.
You have to answer $q$ independent queries.
\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}
|
I know about some solutions that are trying to iterate over almost all possible triples, but I have a better and more interesting one. Possibly, it was already mentioned in comments, but I need to explain it. Let's solve the problem greedily. Let's sort the initial array. The first number we would like to choose is the maximum element. Then we need to pop out some maximum elements that are divisors of the maximum. Then there are two cases: the array becomes empty, or we have some maximum number that does not divide the chosen number. Let's take it and repeat the same procedure again, but now we have to find the number that does not divide neither the first taken number nor the second taken number. So we have at most three numbers after this procedure. Let's update the answer with their sum. This solution is almost correct. Almost! What have we forgotten? Let's imagine that the maximum element is divisible by $2$, $3$ and $5$ and there are three following numbers in the array: maximum divided by $2$, by $3$ and by $5$. Then their sum is greater than the maximum (and may be greater than the answer we have!) because $\frac{1}{2} + \frac{1}{3} + \frac{1}{5} > 1$. So if these conditions are satisfied, let's update the answer with the sum of these three numbers. It can be shown that this is the only possible triple that can break our solution. The triple $2, 3, 4$ does not match because the maximum divided by $4$ divides the maximum divided by $2$. The triple $2, 3, 6$ is bad for the same reason. And the triple $2, 3, 7$ has sum less than the maximum element.
|
[
"brute force",
"math",
"sortings"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
int n;
cin >> n;
set<int> st;
for (int j = 0; j < n; ++j) {
int x;
cin >> x;
st.insert(x);
}
int ans = 0;
int mx = *st.rbegin();
if (mx % 2 == 0 && mx % 3 == 0 && mx % 5 == 0) {
if (st.count(mx / 2) && st.count(mx / 3) && st.count(mx / 5)) {
ans = max(ans, mx / 2 + mx / 3 + mx / 5);
}
}
vector<int> res;
while (!st.empty() && int(res.size()) < 3) {
int x = *st.rbegin();
st.erase(prev(st.end()));
bool ok = true;
for (auto it : res) ok &= (it % x != 0);
if (ok) res.push_back(x);
}
ans = max(ans, accumulate(res.begin(), res.end(), 0));
cout << ans << endl;
}
return 0;
}
|
1183
|
G
|
Candy Box (hard version)
|
\textbf{This problem is a version of problem D from the same contest with some additional constraints and tasks.}
There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad).
\textbf{It is possible that multiple types of candies are completely absent from the gift}. It is also possible that \textbf{not all candies} of some types will be taken to a gift.
You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $f_i$ is given, which is equal to $0$ if you really want to keep $i$-th candy for yourself, or $1$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $f_i$.
You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $f_i = 1$ in your gift.
You have to answer $q$ independent queries.
\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}
|
First of all, to maximize the number of candies in the gift, we can use the following greedy algorithm: let's iterate on the number of candies of some type we take from $n$ to $1$ backwards. For fixed $i$, let's try to find any suitable type of candies. A type is suitable if there are at least $i$ candies of this type in the box. If there exists at least one such type that wasn't used previously, let's pick any such type and take exactly $i$ candies of this type (and decrease $i$). It does not matter which type we pick if we only want to maximize the number of candies we take. Okay, let's now modify this solution to maximize the number of candies having $f_i = 1$. We initially could pick any type that has at least $i$ candies, but now we should choose a type depending on the number of candies with $f_i = 1$ in this type. For example, if we have two types having $x_1$ and $x_2$ candies with $f_i = 1$ respectively, and we want to pick $i_1$ candies from one type and $i_2$ candies from another type, and $x_1 > x_2$ and $i_1 > i_2$, it's better to pick $i_1$ candies of the first type and $i_2$ candies of the second type. In this case we have $min(x_1, i_1) + min(x_2, i_2)$ candies with $f_i = 1$, in the other case it's $min(x_2, i_1) + min(x_1, i_2)$. And if $x_1 > x_2$ and $i_1 > i_2$, then $min(x_1, i_1) + min(x_2, i_2) \ge min(x_2, i_1) + min(x_1, i_2)$. So, when we want to pick a type of candies such that we will take exactly $i$ candies of this type, it's optimal to choose a type that wasn't used yet, contains at least $i$ candies, and has maximum possible number of candies with $f_i = 1$. This best type can be maintained with a multiset or a set of pairs.
|
[
"greedy",
"implementation",
"sortings"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
scanf("%d", &n);
vector<int> cnt(n);
vector<int> cnt_good(n);
for(int i = 0; i < n; i++)
{
int a, f;
scanf("%d %d", &a, &f);
--a;
cnt[a]++;
if(f) cnt_good[a]++;
}
vector<vector<int> > types(n + 1);
for(int i = 0; i < n; i++)
types[cnt[i]].push_back(cnt_good[i]);
int ans1 = 0;
int ans2 = 0;
multiset<int> cur;
for(int i = n; i > 0; i--)
{
for(auto x : types[i]) cur.insert(x);
if(!cur.empty())
{
int z = *cur.rbegin();
ans1 += i;
ans2 += min(i, z);
cur.erase(cur.find(z));
}
}
printf("%d %d\n", ans1, ans2);
}
int main()
{
int t;
scanf("%d", &t);
for(int i = 0; i < t; i++)
solve();
}
|
1183
|
H
|
Subsequences (hard version)
|
\textbf{The only difference between the easy and the hard versions is constraints}.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string $s$ consisting of $n$ lowercase Latin letters.
In one move you can take \textbf{any} subsequence $t$ of the given string and add it to the set $S$. The set $S$ can't contain duplicates. This move costs $n - |t|$, where $|t|$ is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set $S$ of size $k$ or report that it is impossible to do so.
|
Firstly, let's calculate the following auxiliary matrix: $lst_{i, j}$ means the maximum position $pos$ that is less than or equal to $i$, and the character $s_{pos} = j$ (in order from $0$ to $25$, 'a' = $0$, 'b' = $1$, and so on). It can be calculated naively or with some easy dynamic programming (initially all $lst_{i, j}$ are $-1$ and then for each $i$ from $1$ to $n-1$ all values $lst_{i, j}$ are equal to $lst_{i - 1, j}$ except $lst_{i, s_i}$ which is $i$). After calculating this matrix we can solve the problem by the following dynamic programming: let $dp_{i, j}$ be the number of subsequences of length $j$ that ends exactly in the position $i$. Initially all values are zeros except $dp_{i, 1} = 1$ for each $i$ from $0$ to $n-1$. How do we perform transitionss? Let's iterate over all lengths $j$ from $2$ to $n$, then let's iterate over all positions $i$ from $1$ to $n-1$ in a nested loop, and for the current state $dp_{i, j}$ we can calculate it as $\sum\limits_{c=0}^{25}dp_{lst_{i - 1, c}},{j - 1}$. If $lst_{i - 1, c} = -1$ then we don't need to add this state of the dynamic programming to the current state. Don't forget to take the minimum with $10^{12}$ after each transition! This transition means that we take all subsequences that end with each possible character of the alphabet and try to add the current character to each of them. You can understand that there are no overlapping subsequences in this dynamic programming. After that let's iterate over all possible lengths $j$ from $n$ to $1$ and calculate the number of subsequences of the current length $j$. It equals to $cnt = \sum\limits_{c=0}^{25}dp_{lst_{n - 1, c}, j}$. The same, if $lst_{n - 1, c} = -1$ then we don't need to add this state of the dynamic programming to $cnt$. Don't forget to take the minimum with $10^{12}$! If $cnt \ge k$ then let's add $k(n - len)$ to the answer and break the cycle. Otherwise let's add $cnt(n - len)$ to the answer and decrease $k$ by $cnt$. If after all iterations $k$ is greater than zero then let's try to add the empty string to the answer (we didn't take it into account earlier). Increase the answer by $n$ and decrease $k$ by one. If after this $k$ is still greater than zero then the answer is -1, otherwise the answer is the calculated sum. Time complexity: $O(n^2)$.
|
[
"dp",
"strings"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
const long long INF64 = 1e12;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
long long k;
cin >> n >> k;
--k; // the whole string costs nothing
string s;
cin >> s;
vector<vector<int>> lst(n, vector<int>(26, -1));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < 26; ++j) {
if (i > 0) lst[i][j] = lst[i - 1][j];
}
lst[i][s[i] - 'a'] = i;
}
vector<vector<long long>> dp(n + 1, vector<long long>(n + 1));
for (int i = 0; i < n; ++i) {
dp[i][1] = 1;
}
for (int len = 2; len < n; ++len) {
for (int i = 1; i < n; ++i) {
for (int j = 0; j < 26; ++j) {
if (lst[i - 1][j] != -1) {
dp[i][len] = min(INF64, dp[i][len] + dp[lst[i - 1][j]][len - 1]);
}
}
}
}
long long ans = 0;
for (int len = n - 1; len >= 1; --len) {
long long cnt = 0;
for (int j = 0; j < 26; ++j) {
if (lst[n - 1][j] != -1) {
cnt += dp[lst[n - 1][j]][len];
}
}
if (cnt >= k) {
ans += k * (n - len);
k = 0;
break;
} else {
ans += cnt * (n - len);
k -= cnt;
}
}
if (k == 1) {
ans += n;
--k;
}
if (k > 0) cout << -1 << endl;
else cout << ans << endl;
return 0;
}
|
1185
|
A
|
Ropewalkers
|
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.
The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions $a$, $b$ and $c$ respectively. At the end of the performance, the distance between each pair of ropewalkers was \textbf{at least} $d$.
Ropewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by $1$ (i. e. shift by $1$ to the left or right direction on the rope). Agafon, Boniface and Konrad \textbf{can not} move at the same time (\textbf{Only one of them can move at each moment}). Ropewalkers can be at the same positions at the same time and can "walk past each other".
You should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to $d$.
Ropewalkers can walk to negative coordinates, due to the rope is infinite to both sides.
|
Let's solve the problem when $a \le b \le c$. If it's not true, let's sort $a$, $b$ and $c$. If we move $b$ to any direction, the distance between $b$ and one of $a$ or $c$ decreases, so we get to a worse situation than it was. Thus, we can assume that the position $b$ does not change. Then we should make following conditions come true: $|a - b| \ge d$ and $|b - c| \ge d$. If $a - b \ge d$ it can be achieved in 0 seconds, else in $d - (a - b)$ seconds. So, the first condition can be achieved in $max(0, d - (a - b))$. If $b - c \ge d$ it can be achieved in 0 seconds, else in $d - (b - c)$ seconds. So, the second condition can be achieved in $max(0, d - (b - c))$. So, the answer for the problem is $max(0, d - (a - b)) + max(0, d - (b - c))$.
|
[
"math"
] | 800
|
def solve(a, b, c, d):
return max(0, d - (b - a)) + max(0, d - (c - b))
def main():
a, b, c, d = map(int, input().split())
a, b, c = sorted((a, b, c))
print(solve(a, b, c, d))
main()
|
1185
|
B
|
Email from Polycarp
|
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the following words \textbf{could} be printed: "hello", "hhhhello", "hheeeellllooo", but the following \textbf{could not} be printed: "hell", "helo", "hhllllooo".
Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.
For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.
You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
|
It should be noted that if Polycarp press a key once, it's possible to appear one, two or more letters. So, if Polycarp press a key $t$ times, letter will appear at least $t$ times. Also, pressing a particular key not always prints same number of letters. So the possible correct solution is followed: For both words $s$ and $t$ we should group consecutive identical letters with counting of the each group size. For ex, there 4 groups in the word "aaabbcaa": $[aaa, bb, c, aa]$. For performance you should keep every group as the letter (char) and the group size (int). Then, if the number of groups in word $s$ isn't equal to the number of groups in word $t$, then $t$ can not be printed during typing of $s$. Let's go through array with such groups and compare the $i$-th in the word $s$ with the $i$-th in the word $t$. If letters in groups are different, answer is NO. If the group in $s$ are greater than group in $t$, answer is NO. Answer is YES in all other cases. Every string can be splitted into such groups by one loop. So, the total time complexity is $\sum|s| + \sum|t|$
|
[
"implementation",
"strings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
vector<pair<char,int>> split(string s) {
char c = s[0];
int cnt = 1;
vector<pair<char,int>> result;
auto ss = s.c_str();
for (int i = 1; i <= int(s.length()); i++) {
if (ss[i] != c) {
result.push_back({c, cnt});
c = s[i];
cnt = 1;
} else
cnt++;
}
return result;
}
int main() {
int n;
cin >> n;
forn(tt, n) {
string s, t;
cin >> s >> t;
auto sa(split(s)), ta(split(t));
bool ok = sa.size() == ta.size();
if (ok)
forn(i, sa.size())
if (sa[i].first != ta[i].first || sa[i].second > ta[i].second)
ok = false;
cout << (ok ? "YES" : "NO") << endl;
}
}
|
1185
|
C1
|
Exam in BerSU (easy version)
|
\textbf{The only difference between easy and hard versions is constraints.}
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following:
- The $i$-th student randomly chooses a ticket.
- if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
- if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is $M$ minutes ($\max t_i \le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to \textbf{pass} the exam.
For each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home.
|
First of all we should precalculate sum $s_i$ of all students' durations for each student. For $i$-th student $s_i = s_{i - 1} + t_i$. Then for each student we can sort all durations $t_i$ of passing exam of students, who are before the current student. So, let's walk by these durations from larger to smaller and calculate prefix sum of them $D_i$. We will iterate them until total duration is enough for the current student to pass the exam too, i.e. until $s_i + t_i - D_i \le M$. For $i$-th student the answer is number of iterated durations. Sorting works in $\mathcal{O}(n \log n)$, walking by array works in $\mathcal{O}(n)$. Total complexity for all students is $\mathcal{O}(n^2 \log n)$.
|
[
"greedy",
"sortings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
const int T = 100;
int main() {
int n, m;
cin >> n >> m;
int sum = 0;
vector<int> t(n), count(T + 1, 0);
for (int i = 0; i < n; i++) {
cin >> t[i];
}
for (int i = 0; i < n; i++) {
int d = sum + t[i] - m, k = 0;
if (d > 0) {
for (int j = T; j > 0; j--) {
int x = j * count[j];
if (d <= x) {
k += (d + j - 1) / j;
break;
}
k += count[j];
d -= x;
}
}
sum += t[i];
count[t[i]]++;
cout << k << " ";
}
}
|
1185
|
C2
|
Exam in BerSU (hard version)
|
\textbf{The only difference between easy and hard versions is constraints.}
\textbf{If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.}
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following:
- The $i$-th student randomly chooses a ticket.
- if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
- if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is $M$ minutes ($\max t_i \le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to \textbf{pass} the exam.
For each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home.
|
Note that $1 \le t_i \le 100$ for each $i$-th student. It brings us to the idea that for each student we only need to know number of students, who are before current student and whose duration of passing the exam is exactly $k$, for all $k$ from $1$ to $100$. Let's use $count_k$ as array of number student, whose duration of passing the exam is exactly $k$. Initially $count_k = 0$ for all $k$ from $1$ to $100$. For each student we can precalculate sum $s_i$ of all durations of students before current. Now we can iterate all students from $1$-st to $n$-th. Let's walk by $k$ from $100$ to $1$. Initially the answer $a_i$ for $i$-th student is $0$. If $s_i + t_i - count_k \cdot k > M$, let's $s_i = s_i - count_k \cdot k$ and $a_i = a_i + count_k$. If $s_i + t_i - count_k \cdot k \le M$, it means that $a_i + count_k$ is the answer, but it might be not minimal answer. So, the answer is $a_i + \lceil \frac{s_i}{k} \rceil$
|
[
"brute force",
"data structures",
"greedy",
"math"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
const int T = 100;
int main() {
int n, m;
cin >> n >> m;
int sum = 0;
vector<int> t(n), count(T + 1, 0);
for (int i = 0; i < n; i++) {
cin >> t[i];
}
for (int i = 0; i < n; i++) {
int d = sum + t[i] - m, k = 0;
if (d > 0) {
for (int j = T; j > 0; j--) {
int x = j * count[j];
if (d <= x) {
k += (d + j - 1) / j;
break;
}
k += count[j];
d -= x;
}
}
sum += t[i];
count[t[i]]++;
cout << k << " ";
}
}
|
1185
|
D
|
Extra Element
|
A sequence $a_1, a_2, \dots, a_k$ is called an arithmetic progression if for each $i$ from $1$ to $k$ elements satisfy the condition $a_i = a_1 + c \cdot (i - 1)$ for some fixed $c$.
For example, these five sequences are arithmetic progressions: $[5, 7, 9, 11]$, $[101]$, $[101, 100, 99]$, $[13, 97]$ and $[5, 5, 5, 5, 5]$. And these four sequences aren't arithmetic progressions: $[3, 1, 2]$, $[1, 2, 4, 8]$, $[1, -1, 1, -1]$ and $[1, 2, 3, 3, 3]$.
You are given a sequence of integers $b_1, b_2, \dots, b_n$. Find any index $j$ ($1 \le j \le n$), such that if you delete $b_j$ from the sequence, you can reorder the remaining $n-1$ elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.
|
First of all, we should sort all elements (from smaller to larger, for example, or vice versa). But in the answer is index of element in original sequence, so let's keep the array $c$ of pairs $\{b_i, i\}$, sorted by $b_i$. Now we need to check some simple cases, for example, let's check the $1$-st and the $2$-nd elements whether they are the answers. We'll create the copy of original sequence, but without $1$-st element. Then we will check that all neighboring elements $c_i.first$ and $c_{i + 1}.first$ have the same difference. If it is so, $c_1.second$ is the answer. For the $2$-nd element similarly. Okay, now we have the sequence, where $1$-st and $2$-nd elements aren't the answers. Let's fix difference between them $d$ and check that all neighboring elements $c_i.first$ and $c_{i + 1}.first$ have the same difference. If we meet the pair, where the difference doesn't equal $d$, we will check the difference between $c_{i}.first$ and $c_{i + 2}.first$. If it equals $d$, so $c_{i + 1}.second$ may be the answer, otherwise there is no answer (output $-1$). If we will find one else pair, where the difference doesn't equals $d$, there is no answer too. If all pairs have the difference that equals $d$, it means that it's initially arithmetic progression. So we can remove first or last element and get arithmetic progression again. In this case let's output $1$.
|
[
"implementation",
"math"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<int, int>> b(n);
for (int i = 0; i < n; i++) {
int x;
cin >> x;
b[i] = {x, i};
}
sort(b.begin(), b.end());
vector<int> d(n - 1);
for (int i = 1; i < n; i++) {
d[i - 1] = b[i].first - b[i - 1].first;
}
bool f = true;
for (int i = 2; i < n - 1; i++) {
f &= d[i] == d[1];
}
if (f) {
cout << b[0].second + 1;
return 0;
}
f = true;
for (int i = 2; i < n - 1; i++) {
f &= d[i] == b[2].first - b[0].first;
}
if (f) {
cout << b[1].second + 1;
return 0;
}
int answer;
f = false;
for (int i = 1; i < n - 1; i++) {
if (d[i] == d[0]) continue;
if (f) {
cout << -1;
return 0;
} else {
if (i == n - 2) {
cout << b[n - 1].second + 1;
return 0;
} else {
if (b[i + 2].first - b[i].first == d[0]) {
answer = b[i + 1].second;
f = true;
i++;
} else {
cout << -1;
return 0;
}
}
}
}
if (f) {
cout << answer + 1;
} else {
cout << b[n - 1].second + 1;
}
}
|
1185
|
E
|
Polycarp and Snakes
|
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $n \times m$ (where $n$ is the number of rows, $m$ is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $26$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $26$.
Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $1$, i.e. each snake has size either $1 \times l$ or $l \times 1$, where $l$ is snake's length. Note that snakes can't bend.
When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.
Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.
|
Remember, that Polycarp draws snakes in alphabetic order. Firstly we should find the most top left and the most bottom right occurrences of each letter. Secondly we should walk by these letters from 'z' to 'a'. We will skip first not found letters. If for any letter both length and width are larger than $1$, there is no way to draw snakes. Otherwise we should check that all elements in the line equals current letter or '*'. If it's so, let's overdraw this line with '*' and move on to the next letter. If it's not so, there is no way to draw snakes. If there is the answer, for each snake we can output coordinates of the most top left and the most bottom right occurrences of relevant letter. If there is no occurrences for some letter, we can suppose that the next letter fully overdrew the current letter. Totally we can solve the task, walking by field no more than $1 + 26 = 27$ ones.
|
[
"brute force",
"implementation"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int min(int a, int b) {
return (a < b) ? a : b;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int t;
cin >> t;
vector<string> lines(2000, "");
vector<int> vertical_min(26, 2001), vertical_max(26, -1);
vector<int> horizontal_min(26, 2001), horizontal_max(26, -1);
for (int k = 0; k < t; k++) {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> lines[i];
}
for (int b = 0; b < 26; b++) {
vertical_min[b] = 2001;
horizontal_min[b] = 2001;
vertical_max[b] = -1;
horizontal_max[b] = -1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (lines[i][j] != '.') {
int b = (int) (lines[i][j] - 'a');
vertical_min[b] = min(vertical_min[b], i);
vertical_max[b] = max(vertical_max[b], i);
horizontal_min[b] = min(horizontal_min[b], j);
horizontal_max[b] = max(horizontal_max[b], j);
}
}
}
bool f = true, q = false;
int count = 26;
for (int b = 25; b >= 0; b--) {
if (vertical_max[b] == -1) {
if (!q) {
count--;
continue;
} else {
vertical_min[b] = vertical_min[b + 1];
vertical_max[b] = vertical_max[b + 1];
horizontal_min[b] = horizontal_min[b + 1];
horizontal_max[b] = horizontal_max[b + 1];
continue;
}
}
q = true;
if (vertical_max[b] == vertical_min[b]) {
for (int j = horizontal_min[b]; j <= horizontal_max[b]; j++) {
if (lines[vertical_max[b]][j] == 'a' + b || (q && lines[vertical_max[b]][j] == '*')) {
lines[vertical_max[b]][j] = '*';
} else {
f = false;
break;
}
}
} else if (horizontal_max[b] == horizontal_min[b]) {
for (int i = vertical_min[b]; i <= vertical_max[b]; i++) {
if (lines[i][horizontal_max[b]] == 'a' + b || (q && lines[i][horizontal_max[b]] == '*')) {
lines[i][horizontal_max[b]] = '*';
} else {
f = false;
break;
}
}
} else {
f = false;
}
if (!f) {
break;
}
}
if (f) {
cout << "YES" << endl;
cout << count << endl;
for (int i = 0; i < count; i++) {
cout << vertical_min[i] + 1 << " " << horizontal_min[i] + 1 << " " << vertical_max[i] + 1 << " " << horizontal_max[i] + 1 << endl;
}
} else {
cout << "NO" << endl;
}
}
}
|
1185
|
F
|
Two Pizzas
|
A company of $n$ friends wants to order exactly two pizzas. It is known that in total there are $9$ pizza ingredients in nature, which are denoted by integers from $1$ to $9$.
Each of the $n$ friends has one or more favorite ingredients: the $i$-th of friends has the number of favorite ingredients equal to $f_i$ ($1 \le f_i \le 9$) and your favorite ingredients form the sequence $b_{i1}, b_{i2}, \dots, b_{if_i}$ ($1 \le b_{it} \le 9$).
The website of CodePizza restaurant has exactly $m$ ($m \ge 2$) pizzas. Each pizza is characterized by a set of $r_j$ ingredients $a_{j1}, a_{j2}, \dots, a_{jr_j}$ ($1 \le r_j \le 9$, $1 \le a_{jt} \le 9$) , which are included in it, and its price is $c_j$.
Help your friends choose exactly two pizzas in such a way as to please the maximum number of people in the company. It is known that a person is pleased with the choice if \textbf{each} of his/her favorite ingredients is in at least one ordered pizza. If there are several ways to choose two pizzas so as to please the maximum number of friends, then choose the one that minimizes the total price of two pizzas.
|
The first idea that could help to solve this problem is that the number of ingredients is small ($1 \le b_{it}, a_{jt} \le 9$). It means that we can keep information about favorite ingredients for each person in a bitmask. THe same situation is for pizzas' ingredients. Let's keep two pizzas with the smallest cost for each ingredients' mask. This information could be calculated during the reading pizzas' mask. Then, we should go through all possible masks, that could be reached by two different pizzas. For each such mask we should keep two pizzas with the smallest total cost, which gives us that mask (i. e. their bitwise-or is equal to our current mask). After such calculations, let's go through all possible summary masks and count the number of people, who would be satisfied by this mask. It could be done with a submasks-bruteforce in $3^9$. After this, we will have an optimal answer. So, time complexity for this solution is $\mathcal{O}(n + m + 2^{2f} + 3^f)$, where $f \le 9$
|
[
"bitmasks",
"brute force"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define pb push_back
#define mp make_pair
#define sqr(a) ((a) * (a))
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define forn(i, n) for (int i = 0; i < int(n); ++i)
#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)
template<class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {
return out << "(" << a.x << ", " << a.y << ")";
}
template<class A> ostream& operator << (ostream& out, const vector<A> &a) {
out << "[";
for (auto it = a.begin(); it != a.end(); ++it) {
if (it != a.begin())
out << ", ";
out << *it;
}
return out << "]";
}
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
const int INF = 1e9;
const li INF64 = 1e18;
const int MOD = 1e9 + 7;
const ld PI = acosl(-1.0);
const ld EPS = 1e-9;
mt19937 rnd(time(NULL));
mt19937_64 rnd64(time(NULL));
const int N = 100 * 1000 + 11;
const int MSK = 1 << 9;
int n, m;
int cnt[MSK];
vector<pt> pz[N];
bool read() {
if (scanf("%d %d", &n, &m) != 2)
return false;
forn(i, n) {
int k;
scanf("%d", &k);
int msk = 0;
forn(j, k) {
int pos;
scanf("%d", &pos);
--pos;
msk |= (1 << pos);
}
++cnt[msk];
}
return true;
}
void solve() {
forn(i, m) {
int c;
scanf("%d", &c);
int msk = 0;
int k;
scanf("%d", &k);
forn(j, k) {
int pos;
scanf("%d", &pos);
--pos;
msk |= (1 << pos);
}
pz[msk].pb(mp(c, i));
sort(all(pz[msk]));
while (sz(pz[msk]) > 2) pz[msk].pop_back();
}
int ans = 0, cost = 2 * INF + 1;
pt res = mp(-1, -1);
forn(p1, MSK) forn(p2, MSK) {
int curcost = 0;
int pos1, pos2;
if (p1 == p2) {
if (sz(pz[p1]) < 2) continue;
curcost = pz[p1][0].x + pz[p1][1].x;
pos1 = pz[p1][0].y;
pos2 = pz[p1][1].y;
} else {
if (sz(pz[p1]) == 0 || sz(pz[p2]) == 0) continue;
curcost = pz[p1][0].x + pz[p2][0].x;
pos1 = pz[p1][0].y;
pos2 = pz[p2][0].y;
}
int curans = 0;
int curmask = p1 | p2;
forn(pp, MSK) {
if ((curmask & pp) == pp) {
curans += cnt[pp];
}
}
if (curans > ans || (curans == ans && curcost < cost)) {
ans = curans;
cost = curcost;
res = mp(pos1, pos2);
}
}
cout << res.x + 1 << " " << res.y + 1 << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int tt = clock();
#endif
cout << fixed << setprecision(10);
cerr << fixed << setprecision(10);
#ifdef _DEBUG
while (read()) {
#else
if (read()) {
#endif
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
}
|
1185
|
G1
|
Playlist for Polycarp (easy version)
|
\textbf{The only difference between easy and hard versions is constraints.}
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes.
In the player, Polycarp stores $n$ songs, each of which is characterized by two parameters: $t_i$ and $g_i$, where $t_i$ is the length of the song in minutes ($1 \le t_i \le 15$), $g_i$ is its genre ($1 \le g_i \le 3$).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the $i$-th song, he would spend exactly $t_i$ minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
|
Consider all genres are from $0$ to $2$ instead of from $1$ to $3$. It will be easier to deal with 0-based indices. Let's use DP to calculate $d[mask][lst]$, where $mask$ ($0 \le mask < 2^n$) is a binary mask of songs and $lst$ is a genre of the last song. The value $d[mask][lst]$ means the number of ways to order songs corresponding to the $mask$ in such a way that any neighboring (adjacent) songs have different genres and the genre of the last song is $lst$. DP to find the array $d$ is follows. It is easy to see that if $d[mask][lst]$ is calculated correctly, you iterate over all possible songs $j$ to append (such songs should be out of $mask$ and a genre different from $lst$). In this case, you should increase $d[mask + 2^j][genre(j)]$ by $d[mask][lst]$. Here is the sample code to calculate all cells of $d$: Here we use some fake genre $3$ to initialize DP (it can precede any real genre). To find the answer, just take into account only such masks that the correspondent total duration is exactly $M$. Just find the sum of all such $d[mask][lst]$ that the correspondent total duration is exactly $M$. You can do it at the same time with DP calculations. So the resulting code is: The total complexity is $O(n \times 2^n)$.
|
[
"bitmasks",
"combinatorics",
"dp"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int M = 1000000007;
const int N = 16;
int d[1 << N][4];
int main() {
int n, T;
cin >> n >> T;
vector<int> durs(n), types(n);
forn(i, n) {
cin >> durs[i] >> types[i];
types[i]--;
}
int result = 0;
d[0][3] = 1;
forn(mask, 1 << n)
forn(lst, 4) {
forn(j, n)
if (types[j] != lst && ((mask & (1 << j)) == 0))
d[mask ^ (1 << j)][types[j]] = (d[mask ^ (1 << j)][types[j]] + d[mask][lst]) % M;
int sum = 0;
forn(i, n)
if (mask & (1 << i))
sum += durs[i];
if (sum == T)
result = (result + d[mask][lst]) % M;
}
cout << result << endl;
}
|
1185
|
G2
|
Playlist for Polycarp (hard version)
|
\textbf{The only difference between easy and hard versions is constraints.}
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes.
In the player, Polycarp stores $n$ songs, each of which is characterized by two parameters: $t_i$ and $g_i$, where $t_i$ is the length of the song in minutes ($1 \le t_i \le 50$), $g_i$ is its genre ($1 \le g_i \le 3$).
Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the $i$-th song, he would spend exactly $t_i$ minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.
Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.
|
Consider all genres are from $0$ to $2$ instead of from $1$ to $3$. It will be easier to deal with 0-based indices. Let's find two arrays: $a[i][s]$ = number of ways to choose a subset of exactly $i$ songs of the genre $0$ with total duration of exactly $s$; $bc[i][j][s]$ = number of ways to choose a subset of exactly $i$ songs of the genre $1$ and $j$ songs of the genre $2$ with total duration of exactly $s$. You can easily do it with DP. Here is the sample code to do it while reading the input: This part works in $O(n^3 \cdot T)$ with a really small constant factor. Let's calculate the array $ways[i][j][k][lst]$ = number of ways to put $i$ zeroes, $j$ ones and $k$ twos in a row (its length is $i+j+k$) in such a way that no two equal values go consecutive and the row ends on $lst$. You can also use DP to find the values: This part works in $O(n^3)$ with a really small constant factor. And now if the final part of the solution. Let's iterate over all possible ways how songs with the genre $0$ can be in a playlist. It means that we try all possible counts of such songs ($c[0]$ in the code below) and their total duration ($durs0$ in the code below). Now we know the total time for genres $1$ and $2$, it equals to $T-durs0$. Let's iterate over all possible counts of songs with genre=$1$ and songs with genre=$2$ (say, $c[1]$ and $c[2]$). For fixed $c[0]$, $durs0$, $c[1]$ and $c[2]$ there are $x$ ways to choose songs, where $x=a[c[0]][durs0] \cdot b[c[1]][c[2]][T-durs]$. To count all possible orders of songs, let's multiply $x$ on: $c[0]!$ - number of permutations of songs with genre=$0$; $c[1]!$ - number of permutations of songs with genre=$1$; $c[2]!$ - number of permutations of songs with genre=$2$; $ways[c[0]][c[1]][c[2]][0]+ways[c[0]][c[1]][c[2]][1]+ways[c[0]][c[1]][c[2]][2]$ - number ways to order them in the required way. After all the multiplications add the result to the answer. The following code illustrates this part of the solution: This part works in $O(n^3 \cdot T)$ with a really small constant factor. So the total complexity is $O(n^3 \cdot T)$ (the constant factor is significantly less than $1$).
|
[
"combinatorics",
"dp"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int M = 1000000007;
const int N = 51;
const int S = 2501;
void inc(int& a, int d) {
a += d;
if (a >= M)
a -= M;
}
int a[N][S];
int bc[N][N][S];
int ways[N][N][N][4];
int main() {
int n, T;
cin >> n >> T;
vector<int> cnts(4);
vector<int> durs(4);
a[0][0] = bc[0][0][0] = 1;
forn(i, n) {
int dur, type;
cin >> dur >> type;
type--;
if (type == 0) {
for (int cnts0 = cnts[0]; cnts0 >= 0; cnts0--)
forn(durs0, durs[0] + 1)
inc(a[cnts0 + 1][durs0 + dur], a[cnts0][durs0]);
} else {
for (int cnts1 = cnts[1]; cnts1 >= 0; cnts1--)
for (int cnts2 = cnts[2]; cnts2 >= 0; cnts2--)
forn(durs12, durs[1] + durs[2] + 1)
inc(bc[cnts1 + (type == 1)][cnts2 + (type == 2)][durs12 + dur],
bc[cnts1][cnts2][durs12]);
}
cnts[type]++;
durs[type] += dur;
}
ways[0][0][0][3] = 1;
vector<int> c(3);
for (c[0] = 0; c[0] <= cnts[0]; c[0]++)
for (c[1] = 0; c[1] <= cnts[1]; c[1]++)
for (c[2] = 0; c[2] <= cnts[2]; c[2]++)
forn(lst, 4)
if (ways[c[0]][c[1]][c[2]][lst] != 0) {
forn(nxt, 3)
if (nxt != lst && c[nxt] + 1 <= cnts[nxt]) {
vector<int> cn(c);
cn[nxt]++;
inc(ways[cn[0]][cn[1]][cn[2]][nxt], ways[c[0]][c[1]][c[2]][lst]);
}
}
vector<int> f(N + 1, 1);
forn(i, N)
f[i + 1] = ((long long) f[i]) * (i + 1) % M;
int result = 0;
for (c[0] = 0; c[0] <= cnts[0]; c[0]++)
forn(durs0, durs[0] + 1)
if (T - durs0 >= 0)
for (c[1] = 0; c[1] <= cnts[1]; c[1]++)
for (c[2] = 0; c[2] <= cnts[2]; c[2]++) {
long long extra = (long long)(a[c[0]][durs0]) * bc[c[1]][c[2]][T - durs0] % M;
forn(i, 3)
extra = extra * f[c[i]] % M;
forn(lst, 3)
if (c[lst] > 0)
inc(result, extra * ways[c[0]][c[1]][c[2]][lst] % M);
}
cout << result << endl;
}
|
1186
|
A
|
Vus the Cossack and a Contest
|
Vus the Cossack holds a programming competition, in which $n$ people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly $m$ pens and $k$ notebooks.
Determine whether the Cossack can reward \textbf{all} participants, giving each of them at least one pen and at least one notebook.
|
Since a pen and a notebook would be given to each participant, the answer is "Yes" if and only if $n \le k$ and $n \le m$. The answer is "No" otherwise.
|
[
"implementation"
] | 800
| null |
1186
|
C
|
Vus the Cossack and Strings
|
Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $a$ and $b$. It is known that $|b| \leq |a|$, that is, the length of $b$ is at most the length of $a$.
The Cossack considers every substring of length $|b|$ in string $a$. Let's call this substring $c$. He matches the corresponding characters in $b$ and $c$, after which he counts the number of positions where the two strings are different. We call this function $f(b, c)$.
For example, let $b = 00110$, and $c = 11000$. In these strings, the first, second, third and fourth positions are different.
Vus the Cossack counts the number of such substrings $c$ such that $f(b, c)$ is \textbf{even}.
For example, let $a = 01100010$ and $b = 00110$. $a$ has four substrings of the length $|b|$: $01100$, $11000$, $10001$, $00010$.
- $f(00110, 01100) = 2$;
- $f(00110, 11000) = 4$;
- $f(00110, 10001) = 4$;
- $f(00110, 00010) = 1$.
Since in three substrings, $f(b, c)$ is even, the answer is $3$.
Vus can not find the answer for big strings. That is why he is asking you to help him.
|
Let's say that we want to know whether $f(c,d)$ is even for some strings $c$ and $d$. Let's define $cnt_c$ as number of ones in string $c$ and $cnt_d$ as number of ones in $d$. It's easy to see that $f(c,d)$ is even if and only if $cnt_b$ and $cnt_c$ have same parity. In other words if $cnt_c \equiv cnt_d \pmod 2$ then $f(c,d)$ is even. So, we can check if two strings have even number of distinct bits in $O(1)$ if know how many ones does each of them contain. Using that fact we can easily solve problem in $O(n)$ by using prefix sums.
|
[
"implementation",
"math"
] | 1,800
| null |
1186
|
D
|
Vus the Cossack and Numbers
|
Vus the Cossack has $n$ real numbers $a_i$. It is known that the sum of all numbers is equal to $0$. He wants to choose a sequence $b$ the size of which is $n$ such that the sum of all numbers is $0$ and each $b_i$ is either $\lfloor a_i \rfloor$ or $\lceil a_i \rceil$. In other words, $b_i$ equals $a_i$ rounded up or down. It is not necessary to round to the nearest integer.
For example, if $a = [4.58413, 1.22491, -2.10517, -3.70387]$, then $b$ can be equal, for example, to $[4, 2, -2, -4]$.
Note that if $a_i$ is an integer, then there is no difference between $\lfloor a_i \rfloor$ and $\lceil a_i \rceil$, $b_i$ will always be equal to $a_i$.
Help Vus the Cossack find such sequence!
|
At first step we should floor all the elements of the array. Then we iterate through the array and do the following: If sum of all the elements of array is equal to $0$, then the algorithm stops. If the decimal part of $a_i$ was not equal to $0$, then we assign $a_i := a_i+1$ Increase $i$ and repeat step 1. If you are interested why this works, here is the proof: Every element $a_i$ of the initial array can be expressed as $\lfloor a_i \rfloor + \varepsilon_i$. It is obvious that $0 \le \varepsilon_i < 1$. Sum of all elements of array $a$ equals to $0$, it means that: $\sum_{i=1}^{n} a_i = 0$ $\sum_{i=1}^{n} (\lfloor a_i \rfloor + \varepsilon_i) = 0$ $\sum_{i=1}^{n} \lfloor a_i \rfloor + \sum_{i=1}^{n}\varepsilon_i = 0$ From equations above we can see that $\sum_{i=1}^{n}\varepsilon_i$ is an integer. Every $\varepsilon_i < 1$, and that means $\sum_{i=1}^{n}\varepsilon_i$ is smaller than number of elements that were floored, so we will always be able to achieve zero sum of array $a$ by adding $1$ to some of the numbers that were initially floored.
|
[
"constructive algorithms",
"greedy",
"math"
] | 1,500
| null |
1186
|
E
|
Vus the Cossack and a Field
|
Vus the Cossack has a field with dimensions $n \times m$, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way:
- He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field, and "0" there, where "1" was.
- To the current field, he adds the inverted field to the right.
- To the current field, he adds the inverted field to the bottom.
- To the current field, he adds the current field to the bottom right.
- He repeats it.
For example, if the initial field was:
\begin{center}
$\begin{matrix} 1 & 0 & \\ 1 & 1 & \\ \end{matrix}$
\end{center}
After the first iteration, the field will be like this:
\begin{center}
$\begin{matrix} 1 & 0 & 0 & 1 \\ 1 & 1 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 1 \\ \end{matrix}$
\end{center}
After the second iteration, the field will be like this:
\begin{center}
$\begin{matrix} 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\ 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\ 1 & 1 & 0& 0 & 0 & 0 & 1 & 1 \\ \end{matrix}$
\end{center}
And so on...
Let's numerate lines from top to bottom from $1$ to infinity, and columns from left to right from $1$ to infinity. We call the submatrix $(x_1, y_1, x_2, y_2)$ all numbers that have coordinates $(x, y)$ such that $x_1 \leq x \leq x_2$ and $y_1 \leq y \leq y_2$.
The Cossack needs sometimes to find the sum of all the numbers in submatrices. Since he is pretty busy right now, he is asking you to find the answers!
|
Let's define $f(x,y)$ a function that returns sum of all elements of submatrix $(1,1,x,y)$ (these $4$ numbers stand for $x_1, y_1, x_2, y_2$ respectively. If we can get value of this function in a fast way, then we can answer the queries quickly by using well known formula for sum on submatrix with cooridantes $x_1, y_1, x_2, y_2$: $sum = f(x_2,y_2) - f(x_2, y_1 - 1) - f(x_1 - 1, y_2) + f(x_1-1,y_1-1)$ If you want to prove the formula you should draw some examples and use the inclusion-exclusion principle. So we reduced our task to finding value of $f(x,y)$ for some arbitrary $x$ and $y$. At first, we should precalculate values of $f(x,y)$ for every $1 \le x \le n, 1 \le y \le m$. This can be easily done using dynamic programming. Let's forget about the sums for a while. Let's take a look on the fields. They can be both inverted or not inverted. Let's see how fields are distributed when generating an infinite field. At step $0$ we have one field, which is not inverted: $\begin{matrix} 0 \\ \end{matrix}$ At step $1$ we have four fields: $\begin{matrix} 0 & 1 & \\ 1 & 0 & \\ \end{matrix}$ And so on... After 3 steps we can see that you can split each horizontal or vertical line in pairs of inverted and not inverted fields like on the picture (vertical pairs are highlighted with yellow, horizontal pairs are highlighted with red): Sum of inverted and not inverted matrices of size $n \times m$ is equal to $n \cdot m$. Knowing these facts we can get $O(1)$ solution. Let's say that we want to know $f(x,y)$. Let's define $field_x$ and $field_y$ as coordinates of the field which cell $(x,y)$ belongs to. They can be easily found: $field_x = \Big\lfloor \frac{x-1}{n} \Big\rfloor + 1$ $field_y = \Big\lfloor \frac{y-1}{m} \Big\rfloor + 1$ The solution is splited into four parts: When both $field_x$ and $field_y$ are odd. When $field_x$ is odd, but $field_y$ is even. When $field_x$ is even, but $field_y$ is odd. When both $feild_x$ and $field+y$ are even. Solving each of the part is very similar, so I'll show you how to get value of $f(x,y)$ if both $field_x$ and $field_y$ are even (In this particular example $field_x = field_y = 4$). The big black dot shows us the position of $(x,y)$ (i.e. it shows that the cell with coordinates $(x, y)$ is located somewhere in the field with coordinates $(4,4)$). Using the fact I mentioned before we can get the value of pairs highlited as red: it is equal to $\frac{((field_x - 1) \cdot (field_y - 1) - 1) \cdot n \cdot m}{2}$ You can easily use the same fact in order to find the blue and yellow parts. In order to find the green parts we need to know whether each of the matrices, highlighted with green is inversed. How to know if the matrix with coordinates $(a,b)$ is inversed? Here is the trick (here $bitcnt$ is the function which returns number of bits in a number): If $bitcnt(a) + bitcnt(b)$ is an odd number, then the matrix is inversed.
|
[
"divide and conquer",
"implementation",
"math"
] | 2,500
| null |
1186
|
F
|
Vus the Cossack and a Graph
|
Vus the Cossack has a simple graph with $n$ vertices and $m$ edges. Let $d_i$ be a degree of the $i$-th vertex. Recall that a degree of the $i$-th vertex is the number of conected edges to the $i$-th vertex.
He needs to remain not more than $\lceil \frac{n+m}{2} \rceil$ edges. Let $f_i$ be the degree of the $i$-th vertex after removing. He needs to delete them in such way so that $\lceil \frac{d_i}{2} \rceil \leq f_i$ for each $i$. In other words, the degree of each vertex should not be reduced more than twice.
Help Vus to remain the needed edges!
|
At first, let's create a fictive vertex (I'll call it $0$ vertex) and connect it with all of the vertices which have odd degree. Now all the vertices including $0$ vertex have even degree. The statement that $0$ vertex will have even degree too can be easily proven using the fact that the sum of degrees of all vertices equals to the number of edges multiplied by two. Let's denote the number of edges in the new graph as $k$. There were $m$ edges initially and we added at most $n$ new edges that connect fictive vertex with the real ones, so it always holds that $k \le n + m$. Now, since all the vertices have even degree we can find Euler cycle of the new graph. Let's define $e_1, e_2, \ldots, e_k$ as an array of all edges of the graph, ordered as in found Euler cycle. Now we can iterate over the array $e$ and delete all the edges on even positions. Due to this action now the new graph contains at most $\lceil \frac{k}{2} \rceil \le \lceil \frac{n+m}{2} \rceil$ edges. That is exactly what we needed! It is interesting that in the new graph by deleting the edges the way mentioned above, the degree of each vertex would not be reduced more than twice. How to prove that? Well, you can think about it the following way: Let's say that the $e_i$ edge connects some vertices $a$ and $b$, that means that the $e_{i+1}$ edge connects vertex $b$ with some vertex $c$. If $i$ is odd, then we will delete only the $e_{i+1}$ edge, and if $i$ is even, then we will delete only the $e_i$ edge. And that happens for every vertex: if some edge $i$ enters it, then we will either delete $i$-th edge or $i+1$-th edge. So at most half of edges connected to a vertex will be deleted. If the length of Euler cycle is odd, then the last edge in it won't be deleted at all, so the algorithm will still work correctly. But that works for the new graph, which contains fictive vertex. But we need to solve the problem for the real graph. We can not simply delete all the edges from the real graph, that were on even positions in Euler cycle mentioned above. Here is the examle where it does not work (numbers near the edges show their positions in $e$ array, edges that would need to be removed are highlited with red): If we removed edge between vertices $2$ and $3$, degree of vertex $3$ would become $0$ which is definetely less then $\lceil \frac{d_3}{2} \rceil = 1$. How do we avoid this bad situation? We can simply do the following: If $e_i$ is a fictive edge (i.e. it connects a real vertex with fictive one), then we do not really care about it, since we have to output answer about the real graph. If $e_i$ is a real edge (i.e it connects only real vertices) and we have to delete it, then we should look if $e_{i-1}$ or $e_{i+1}$ is a ficive edge. If either of them is one, then we can delete the fictive edge instead of the real edge $e_i$ (i.e. we simply do not delete $e_i$ from the graph), otherwise we delete the edge. (Note that if $e_i$ is the last edge in the Euler cycle, then instead of checking the $e_{k+1}$ edge which does not exist, you check if $e_1$ is fictive or not, similar goes for the case if $i = 1$). It is obvious that by doing so we do not change the number of edges deleted. It is also easy to see that the degree of a $i-th$ vertex in the new graph is at most $d_i + 1$. We still delete at most $\lfloor \frac{d_i + 1}{2} \rfloor$ edges connected to it (or $\lfloor \frac{d_i}{2} \rfloor$ if it initially had an even degree), but in case when it's degree was "artificially" increased, we prefer to delete the fictive edge, which we do not care about. The last question is: whether there we will a fictive edge which we will try to delete more than once? It is easy to prove that there is no such edge, you can try it by yourself. That's it, the problem is solved. Note that the graph is not necessarily connected, so you should find Euler cycle and do the following steps for each component independently.
|
[
"dfs and similar",
"graphs",
"greedy",
"implementation"
] | 2,400
| null |
1187
|
A
|
Stickers and Toys
|
Your favorite shop sells $n$ Kinder Surprise chocolate eggs. You know that exactly $s$ stickers and exactly $t$ toys are placed in $n$ eggs in total.
Each Kinder Surprise can be one of three types:
- it can contain a single sticker and \textbf{no toy};
- it can contain a single toy and \textbf{no sticker};
- it can contain both a single sticker \textbf{and} a single toy.
But you \textbf{don't know} which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.
What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?
Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.
|
Note, that there are exactly $n - t$ eggs with only a sticker and, analogically, exactly $n - s$ with only a toy. So we need to buy more than $\max(n - t, n - s)$ eggs, or exactly $\max(n - t, n - s) + 1$.
|
[
"math"
] | 900
|
fun main(args: Array<String>) {
val tc = readLine()!!.toInt()
for (i in 1..tc) {
val (n, s, t) = readLine()!!.split(' ').map { it.toInt() }
println(maxOf(n - s, n - t) + 1)
}
}
|
1187
|
B
|
Letters Shop
|
The letters shop showcase is a string $s$, consisting of $n$ lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $s$.
There are $m$ friends, the $i$-th of them is named $t_i$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.
- For example, for $s$="arrayhead" and $t_i$="arya" $5$ letters have to be bought ("{\textbf{array}head}").
- For example, for $s$="arrayhead" and $t_i$="harry" $6$ letters have to be bought ("{\textbf{arrayh}ead}").
- For example, for $s$="arrayhead" and $t_i$="ray" $5$ letters have to be bought ("{\textbf{array}head}").
- For example, for $s$="arrayhead" and $t_i$="r" $2$ letters have to be bought ("{\textbf{ar}rayhead}").
- For example, for $s$="arrayhead" and $t_i$="areahydra" all $9$ letters have to be bought ("{\textbf{arrayhead}}").
It is guaranteed that every friend can construct her/his name using the letters from the string $s$.
Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
|
Let's construct the answer letter by letter. How to get enough letters 'a' for the name? Surely, the taken letters will be the first 'a', the second 'a', up to $cnt_a$-th 'a' in string $s$, where $cnt_a$ is the amount of letters 'a' in the name. It's never profitable to skip the letter you need. Do the same for all letters presented in the name. The answer will the maximum position of these last taken letters. How to obtain the $cnt_a$-th letter fast? Well, just precalculate the list of positions for each letter and take the needed one from it. Overall complexity: $O(n + m)$.
|
[
"binary search",
"implementation",
"strings"
] | 1,300
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int n, m;
string s, t;
vector<int> pos[26];
int main() {
cin >> n >> s;
forn(i, n)
pos[s[i] - 'a'].push_back(i + 1);
cin >> m;
forn(i, m){
cin >> t;
vector<int> cnt(26);
for (auto &c : t)
++cnt[c - 'a'];
int ans = -1;
forn(j, 26) if (cnt[j] > 0)
ans = max(ans, pos[j][cnt[j] - 1]);
cout << ans << "\n";
}
return 0;
}
|
1187
|
C
|
Vasya And Array
|
Vasya has an array $a_1, a_2, \dots, a_n$.
You don't know this array, but he told you $m$ facts about this array. The $i$-th fact is a triple of numbers $t_i$, $l_i$ and $r_i$ ($0 \le t_i \le 1, 1 \le l_i < r_i \le n$) and it means:
- if $t_i=1$ then subbarray $a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$ is sorted in non-decreasing order;
- if $t_i=0$ then subbarray $a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter.
For example if $a = [2, 1, 1, 3, 2]$ then he could give you three facts: $t_1=1, l_1=2, r_1=4$ (the subarray $[a_2, a_3, a_4] = [1, 1, 3]$ is sorted), $t_2=0, l_2=4, r_2=5$ (the subarray $[a_4, a_5] = [3, 2]$ is not sorted), and $t_3=0, l_3=3, r_3=5$ (the subarray $[a_3, a_5] = [1, 3, 2]$ is not sorted).
You don't know the array $a$. Find \textbf{any} array which satisfies all the given facts.
|
Let's consider array $b_1, b_2, \dots , b_{n-1}$, such that $b_i = a_{i + 1} - a_i$. Then subarray $a_l, a_{l+1}, \dots , a_r$ is sorted in non-decreasing order if and only if all elements $b_l, b_{l + 1} , \dots , b_{r - 1}$ are greater or equal to zero. So if we have fact $t_i = 1, l_i, r_i$, then all elements $b_{l_i}, b_{l_i + 1}, \dots , b_{r_i - 1}$ must be greater or equal to zero. Let's create the following array $b$: $b_i = 0$ if there is such a fact ${t_j, l_j, r_j}$ that $t_j = 1, l_j \le i < r_j$, and $b_i = -1$ otherwise. After that we create the following array $a$: $a_1 = n$, and for all other indexes $a_i = a_{i - 1} + b_{i - 1}$. This array $a$ satisfies all facts ${t_i, l_i, r_i}$ such that $t_i = 1$. So all we have to do is check that all remaining facts are satisfied.
|
[
"constructive algorithms",
"greedy",
"implementation"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
int n, m;
int l[N], r[N], s[N];
int d[N];
int dx[N];
int res[N];
int nxt[N];
int main() {
scanf("%d %d", &n, &m);
for(int i = 0; i < m; ++i){
scanf("%d %d %d", s + i, l + i, r + i);
--l[i], --r[i];
if(s[i] == 1)
++d[l[i]], --d[r[i]];
}
memset(dx, -1, sizeof dx);
int sum = 0;
for(int i = 0; i < n - 1; ++i){
sum += d[i];
if(sum > 0)
dx[i] = 0;
}
res[0] = n;
for(int i = 1; i < n; ++i)
res[i] = res[i - 1] + dx[i - 1];
nxt[n - 1] = n - 1;
for(int i = n - 2; i >= 0; --i){
if(res[i] <= res[i + 1])
nxt[i] = nxt[i + 1];
else
nxt[i] = i;
}
for(int i = 0; i < m; ++i){
if(s[i] != (nxt[l[i]] >= r[i])){
puts("NO");
return 0;
}
}
puts("YES");
for(int i = 0; i < n; ++i)
printf("%d ", res[i]);
puts("");
return 0;
}
|
1187
|
D
|
Subarray Sorting
|
You are given an array $a_1, a_2, \dots, a_n$ and an array $b_1, b_2, \dots, b_n$.
For one operation you can sort in non-decreasing order any subarray $a[l \dots r]$ of the array $a$.
For example, if $a = [4, 2, 2, 1, 3, 1]$ and you choose subbarray $a[2 \dots 5]$, then the array turns into $[4, 1, 2, 2, 3, 1]$.
You are asked to determine whether it is possible to obtain the array $b$ by applying this operation any number of times (possibly zero) to the array $a$.
|
Let's reformulate this problem in next form: we can sort only subarray of length 2 (swap two consecutive elements $i$ and $i+1$ if $a_i > a_{i + 1}$). It is simular tasks because we can sort any array by sorting subbarray of length 2 (for example bubble sort does exactly that). Now lets look at elements $a_1$ and $b_1$. If $a_1 = b_1$ then we will solve this task for arrays $a_2, a_3, \dots , a_n$ and $b_2, b_3, \dots , b_n$. Otherwise lets look at minimum position $pos$ such that $a_{pos} = b_1$ (if there is no such position then answer to the problem is NO). We can move element $a_{pos}$ to the beginning of array only if all elements $a_1, a_2, \dots, a_{pos - 1}$ greater then $a_{pos}$. In other words any index $i$ such that $a_i < a_{pos}$ must be greater then $pos$. And if this condition holds, then we just delete element $a_{pos}$ and solve task for arrays $a_1, a_2, \dots, a_{pos - 2}, a_{pos-1}, a_{pos + 1}, a_{pos + 2}, \dots , a_n$ and $b_2, b_3, \dots, b_n$. But instead of deleting this element $a_{pos}$ we will change information about minimum index $i$ such that $b_1 = a_i$. This index will be the minimum index $i$ such that $i > pos$ and $a_{pos} = a_i$. For do this we will maintain $n$ stacks $s_1, s_2, \dots , s_n$ such that for any element $x$ of stack $s_i$ condition $a_x = i$ holds and moreover all elements in stacks are sorted in ascending order (the top element of stack is minimal). For example if $a = [1, 2, 3, 1, 2, 2]$, then $s_1 = [1, 4]$, $s_2 = [2, 5, 6]$, $s_3 = [3]$, $s_4, s_5, s_6 = []$. For finding minimum element on top of stacks $s_1, s_2, \dots , s_i$ we can use some data structure (for example segment tree).
|
[
"data structures",
"sortings"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(3e5) + 99;
const int INF = int(1e9) + 99;
int t, n;
int a[N], b[N];
vector <int> p[N];
int st[4 * N + 55];
int getMin(int v, int l, int r, int L, int R){
if(L >= R) return INF;
if(l == L && r == R)
return st[v];
int mid = (l + r) / 2;
return min(getMin(v * 2 + 1, l, mid, L, min(R, mid)),
getMin(v * 2 + 2, mid, r, max(mid, L), R));
}
void upd(int v, int l, int r, int pos, int x){
if(r - l == 1){
st[v] = x;
return;
}
int mid = (l + r) / 2;
if(pos < mid) upd(v * 2 + 1, l, mid, pos, x);
else upd(v * 2 + 2, mid, r, pos, x);
st[v] = min(st[v * 2 + 1], st[v * 2 + 2]);
}
int main() {
scanf("%d", &t);
for(int tc = 0; tc < t; ++tc){
scanf("%d", &n);
for(int i = 0; i < n; ++i)
p[i].clear();
for(int i = 0; i < n; ++i){
scanf("%d", a + i);
--a[i];
p[a[i]].push_back(i);
}
for(int i = 0; i < n; ++i){
scanf("%d", b + i);
--b[i];
}
for(int i = 0; i < 4 * n; ++i) st[i] = INF;
for(int i = 0; i < n; ++i){
reverse(p[i].begin(), p[i].end());
if(!p[i].empty()) upd(0, 0, n, i, p[i].back());
}
bool ok = true;
for(int i = 0; i < n; ++i){
if(p[b[i]].empty()){
ok = false;
break;
}
int pos = p[b[i]].back();
if(getMin(0, 0, n, 0, b[i]) < pos){
ok = false;
break;
}
p[b[i]].pop_back();
upd(0, 0, n, b[i], p[b[i]].empty()? INF : p[b[i]].back());
}
if(ok) puts("YES");
else puts("NO");
}
return 0;
}
|
1187
|
E
|
Tree Painting
|
You are given a tree (an undirected connected acyclic graph) consisting of $n$ vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to \textbf{any} black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
Vertices $1$ and $4$ are painted black already. If you choose the vertex $2$, you will gain $4$ points for the connected component consisting of vertices $2, 3, 5$ and $6$. If you choose the vertex $9$, you will gain $3$ points for the connected component consisting of vertices $7, 8$ and $9$.
Your task is to maximize the number of points you gain.
|
I should notice that there is much simpler idea and solution for this problem without rerooting technique but I will try to explain rerooting as the main solution of this problem (it can be applied in many problems and this is just very simple example). What if the root of the tree is fixed? Then we can notice that the answer for a subtree can be calculated as $dp_v = s_v + \sum\limits_{to \in ch(v)} dp_{to}$, where $ch(v)$ is the set of children of the vertex $v$. The answer on the problem for the fixed root will be $dp_{root}$. How can we calculate all possible values of $dp_{root}$ for each root from $1$ to $n$ fast enough? We can apply rerooting! When we change the root of tree from the vertex $v$ to the vertex $to$, we can notice that only four values will change: $s_v, s_{to}, dp_v$ and $dp_{to}$. Firstly, we need to cut the subtree of $to$ from the tree rooted at $v$. Let's subtract $dp_{to}$ and $s_{to}$ from $dp_v$, then let's change the size of the subtree of $v$ (subtract $s_{to}$ from it). Now we have the tree without the subtree of $to$. Then we need to append $v$ as a child of $to$. Add $s_v$ to $s_{to}$ and add $s_v$ and $dp_v$ to $dp_{to}$. Now we have $to$ as a root of the tree and can update the answer with $dp_{to}$. When we changes the root of the tree back from $to$ to $v$, we just need to rollback all changes we made. So, overall idea is the following: calculate sizes of subtrees for some fixed root, calculate dynamic programming for this root, run dfs which will reroot the tree with any possible vertex and update the answer with the value of dynamic programming for each possible root. The code of function that reroots the tree seems like this:
|
[
"dfs and similar",
"dp",
"trees"
] | 2,100
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef long long li;
using namespace std;
const int N = 200 * 1000 + 13;
int n;
vector<int> g[N];
int siz[N];
li sum[N];
void init(int v, int p = -1){
siz[v] = 1;
sum[v] = 0;
for (auto u : g[v]) if (u != p){
init(u, v);
siz[v] += siz[u];
sum[v] += sum[u];
}
sum[v] += (siz[v] - 1);
}
li dp[N];
void dfs(int v, int p = -1){
dp[v] = 0;
li tot = 0;
for (auto u : g[v]) if (u != p)
tot += sum[u];
for (auto u : g[v]) if (u != p){
dfs(u, v);
dp[v] = max(dp[v], (n - siz[u] - 1) + dp[u] + (tot - sum[u]));
}
if (g[v].size() == 1){
dp[v] = n - 1;
}
}
int main() {
scanf("%d", &n);
forn(i, n - 1){
int v, u;
scanf("%d%d", &v, &u);
--v, --u;
g[v].push_back(u);
g[u].push_back(v);
}
if (n == 2) {
cout << 3 << endl;
return 0;
}
forn(i, n) if (int(g[i].size()) > 1){
init(i);
dfs(i);
printf("%lld\n", dp[i] + n);
break;
}
return 0;
}
|
1187
|
F
|
Expected Square Beauty
|
Let $x$ be an array of integers $x = [x_1, x_2, \dots, x_n]$. Let's define $B(x)$ as a minimal size of a partition of $x$ into subsegments such that all elements in each subsegment are equal. For example, $B([3, 3, 6, 1, 6, 6, 6]) = 4$ using next partition: $[3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6]$.
Now you don't have any exact values of $x$, but you know that $x_i$ can be any integer value from $[l_i, r_i]$ ($l_i \le r_i$) uniformly at random. All $x_i$ are independent.
Calculate expected value of $(B(x))^2$, or $E((B(x))^2)$. It's guaranteed that the expected value can be represented as rational fraction $\frac{P}{Q}$ where $(P, Q) = 1$, so print the value $P \cdot Q^{-1} \mod 10^9 + 7$.
|
As usual with tasks on an expected value, let's denote $I_i(x)$ as indicator function: $I_i(x) = 1$ if $x_i \neq x_{i - 1}$ and $0$ otherwise; $I_1(x) = 1$. Then we can note that $B(x) = \sum\limits_{i = 1}^{n}{I_i(x)}$. Now we can make some transformations: $E(B^2(x)) = E((\sum\limits_{i = 1}^{n}{I_i(x)})^2) = E(\sum\limits_{i = 1}^{n}{ \sum\limits_{j = 1}^{n}{I_i(x) I_j(x)} }) = \sum\limits_{i = 1}^{n}{ \sum\limits_{j = 1}^{n}{E(I_i(x) I_j(x))} }$. Now we'd like to make some casework: if $|i - j| > 1$ ($i$ and $j$ aren't consecutive) then $I_i(x)$ and $I_j(x)$ are independent, that's why $E(I_i(x) I_j(x)) = E(I_i(x)) E(I_j(x))$; if $i = j$ then $E(I_i(x) I_i(x)) = E(I_i(x))$; $|i - j| = 1$ need further investigation. For the simplicity let's transform segment $[l_i, r_i]$ to $[l_i, r_i)$ by increasing $r_i = r_i + 1$. Let's denote $q_i$ as the probability that $x_{i-1} = x_i$: $q_i = \max(0, \frac{\min(r_{i - 1}, r_i) - \max(l_{i - 1}, l_i)}{(r_{i - 1} - l_{i - 1})(r_i - l_i)})$ and $q_1 = 0$. Let's denote $p_i = 1 - q_i$. In result, $E(I_i(x)) = p_i$. The final observation is the following: $E(I_i(x) I_{i + 1}(x))$ is equal to the probability that $x_{i - 1} \neq x_i$ and $x_i \neq x_{i + 1}$ and can be calculated by inclusion-exclusion principle: $E(I_i(x) I_{i + 1}(x)) = 1 - q_{i} - q_{i + 1} + P(x_{i-1} = x_i\ \&\ x_i = x_{i + 1})$, where $P(x_{i-1} = x_i\ \&\ x_i = x_{i + 1}) = \max(0, \frac{\min(r_{i-1}, r_i, r_{i+1}) - \max(l_{i-1}, l_i, l_{i+1})}{(r_{i-1} - l_{i-1})(r_i - l_i)(r_{i+1} - l_{i+1})})$. In result, $E(B^2(x)) = \sum\limits_{i = 1}^{n}{( p_i + p_i\sum\limits_{|j - i| > 1}{p_j} + E(I_{i-1}(x) I_i(x)) + E(I_i(x) I_{i+1}(x)) )}$ and can be calculated in $O(n \log{MOD})$ time.
|
[
"dp",
"math",
"probabilities"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
const int MOD = int(1e9) + 7;
int norm(int a) {
while(a >= MOD) a -= MOD;
while(a < 0) a += MOD;
return a;
}
int mul(int a, int b) {
return int(a * 1ll * b % MOD);
}
int binPow(int a, int k) {
int ans = 1;
for(; k > 0; k >>= 1) {
if(k & 1)
ans = mul(ans, a);
a = mul(a, a);
}
return ans;
}
int inv(int a) {
int b = binPow(a, MOD - 2);
assert(mul(a, b) == 1);
return b;
}
int n;
vector<int> l, r;
inline bool read() {
if(!(cin >> n))
return false;
l.resize(n);
r.resize(n);
fore(i, 0, n)
cin >> l[i];
fore(i, 0, n) {
cin >> r[i];
r[i]++;
}
return true;
}
vector<int> p;
int calcEq(int i0) {
int i1 = i0 + 1;
int pSame = 0;
if(i0 > 0) {
int cnt = max(0, min({r[i0 - 1], r[i0], r[i1]}) - max({l[i0 - 1], l[i0], l[i1]}));
pSame = mul(cnt, inv(mul(mul(r[i0 - 1] - l[i0 - 1], r[i0] - l[i0]), r[i1] - l[i1])));
}
return norm(1 - norm(2 - p[i0] - p[i1]) + pSame);
}
inline void solve() {
p.assign(n, 0);
p[0] = 1;
fore(i, 1, n) {
int cnt = max(0, min(r[i - 1], r[i]) - max(l[i - 1], l[i]));
p[i] = norm(1 - mul(cnt, inv(mul(r[i - 1] - l[i - 1], r[i] - l[i]))));
}
int sum = 0;
fore(i, 0, n)
sum = norm(sum + p[i]);
int ans = 0;
fore(i, 0, n) {
int curS = sum;
for(int j = max(0, i - 1); j < min(n, i + 2); j++)
curS = norm(curS - p[j]);
ans = norm(ans + mul(p[i], curS));
if(i > 0)
ans = norm(ans + calcEq(i - 1));
ans = norm(ans + p[i]);
if(i + 1 < n)
ans = norm(ans + calcEq(i));
}
cout << ans << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1187
|
G
|
Gang Up
|
The leader of some very secretive organization has decided to invite all other members to a meeting. All members of the organization live in the same town which can be represented as $n$ crossroads connected by $m$ two-directional streets. The meeting will be held in the leader's house near the crossroad $1$. There are $k$ members of the organization invited to the meeting; $i$-th of them lives near the crossroad $a_i$.
All members of the organization receive the message about the meeting at the same moment and start moving to the location where the meeting is held. In the beginning of each minute each person is located at some crossroad. He or she can either wait a minute at this crossroad, or spend a minute to walk from the current crossroad along some street to another crossroad (obviously, it is possible to start walking along the street only if it begins or ends at the current crossroad). In the beginning of the first minute each person is at the crossroad where he or she lives. As soon as a person reaches the crossroad number $1$, he or she immediately comes to the leader's house and attends the meeting.
Obviously, the leader wants all other members of the organization to come up as early as possible. But, since the organization is very secretive, the leader does not want to attract much attention. Let's denote the discontent of the leader as follows
- initially the discontent is $0$;
- whenever a person reaches the crossroad number $1$, the discontent of the leader increases by $c \cdot x$, where $c$ is some fixed constant, and $x$ is the number of minutes it took the person to reach the crossroad number $1$;
- whenever $x$ members of the organization walk \textbf{along the same street at the same moment in the same direction}, $dx^2$ is added to the discontent, where $d$ is some fixed constant. This is not cumulative: for example, if two persons are walking along the same street in the same direction at the same moment, then $4d$ is added to the discontent, not $5d$.
Before sending a message about the meeting, the leader can tell each member of the organization which path they should choose and where they should wait. Help the leader to establish a plan for every member of the organization so they all reach the crossroad $1$, and the discontent is minimized.
|
First of all, one crucial observation is that no person should come to the meeting later than $100$ minutes after receiving the message: the length of any simple path in the graph won't exceed $49$, and even if all organization members should choose the same path, we can easily make them walk alone if the first person starts as soon as he receives the message, the second person waits one minute, the third person waits two minutes, and so on. Let's model the problem using mincost flows. First of all, we need to expand our graph: let's create $101$ "time layer" of the graph, where $i$-th layer represents the state of the graph after $i$ minutes have passed. The members of the organization represent the flow in this graph. We should add a directed edge from the source to every crossroad where some person lives, with capacity equal to the number of persons living near that crossroad (of course, this edge should lead into $0$-th time layer, since everyone starts moving immediately). To model that some person can wait without moving, we can connect consecutive time layers: for every vertex representing some crossroad $x$ in time layer $i$, let's add a directed edge with infinite capacity to the vertex representing the same crossroad in the layer $i + 1$. To model that people can walk along the street, for every street $(x, y)$ and every layer $i$ let's add several edges going from crossroad $x$ in the layer $i$ to crossroad $y$ in the layer $i + 1$ (the costs and the capacities of these edges will be discussed later). And to model that people can attend the meeting, for each layer $i$ let's add a directed edge from the vertex representing crossroad $1$ in that layer to the sink (the capacity should be infinite, the cost should be equal to $ci$). Okay, if we find a way to model the increase of discontent from the companies of people going along the same street at the same moment, then the minimum cost of the maximum flow in this network is the answer: maximization of the flow ensures that all people attend the meeting, and minimization of the cost ensures that the discontent is minimized. To model the increase of discontent from the companies of people, let's convert each edge $(x, y)$ of the original graph into a large set of edges: for each layer $i$, let's add $k$ edges with capacity $1$ from the crossroad $x$ in the layer $i$ to the crossroad $y$ in the layer $i + 1$. The first edge should have the cost equal to $d$, the second edge - equal to $3d$, the third - $5d$ and so on, so if we choose $z$ minimum cost edges between this pair of nodes, their total cost will be equal to $d z^2$. Don't forget that each edge in the original graph is undirected, so we should do the same for the node representing $y$ in layer $i$ and the node representing $x$ in layer $i + 1$. Okay, now we have a network with $\approx 5000$ vertices and $\approx 500000$ edges, and we have to find the minimum cost flow in it (and the total flow does not exceed $50$). Strangely enough, we could not construct a test where the basic implementation of Ford-Bellman algorithm with a queue runs for a long time (but perhaps it's possible to fail it). But if you are not sure about its complexity, you can improve it with the following two optimizations: use Dijkstra with potentials instead of Ford-Bellman with queue; compress all edges that connect the same nodes of the network into one edge with varying cost.
|
[
"flows",
"graphs"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
struct edge
{
int y, c, f, cost;
edge() {};
edge(int y, int c, int f, int cost) : y(y), c(c), f(f), cost(cost) {};
};
vector<edge> e;
const int N = 14043;
vector<int> g[N];
long long ans = 0;
long long d[N];
int p[N];
int pe[N];
int inq[N];
const long long INF64 = (long long)(1e18);
int s = N - 2;
int t = N - 1;
int rem(int x)
{
return e[x].c - e[x].f;
}
void push_flow()
{
for(int i = 0; i < N; i++) d[i] = INF64, p[i] = -1, pe[i] = -1, inq[i] = 0;
d[s] = 0;
queue<int> q;
q.push(s);
inq[s] = 1;
while(!q.empty())
{
int k = q.front();
q.pop();
inq[k] = 0;
for(auto x : g[k])
{
if(!rem(x)) continue;
int c = e[x].cost;
int y = e[x].y;
if(d[y] > d[k] + c)
{
d[y] = d[k] + c;
p[y] = k;
pe[y] = x;
if(inq[y] == 0)
{
inq[y] = 1;
q.push(y);
}
}
}
}
int cur = t;
// vector<int> zz(1, cur);
while(cur != s)
{
e[pe[cur]].f++;
e[pe[cur] ^ 1].f--;
cur = p[cur];
// zz.push_back(cur);
}
// reverse(zz.begin(), zz.end());
// for(auto x : zz) cerr << x << " ";
// cerr << endl;
ans += d[t];
}
void add_edge(int x, int y, int c, int cost)
{
g[x].push_back(e.size());
e.push_back(edge(y, c, 0, cost));
g[y].push_back(e.size());
e.push_back(edge(x, 0, 0, -cost));
}
int main()
{
int n, m, k, c, d;
cin >> n >> m >> k >> c >> d;
for(int i = 0; i < k; i++)
{
int x;
cin >> x;
--x;
add_edge(s, x, 1, 0);
}
int tt = 101;
for(int i = 0; i < tt; i++)
add_edge(0 + i * n, t, k, i * c);
for(int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
--x;
--y;
for(int i = 0; i < tt - 1; i++)
for(int j = 0; j < k; j++)
add_edge(x + i * n, y + i * n + n, 1, d * (j * 2 + 1));
for(int i = 0; i < tt - 1; i++)
for(int j = 0; j < k; j++)
add_edge(y + i * n, x + i * n + n, 1, d * (j * 2 + 1));
}
for(int i = 0; i < n; i++)
for(int j = 0; j < tt - 1; j++)
add_edge(i + j * n, i + j * n + n, k, 0);
for(int i = 0; i < k; i++)
push_flow();
cout << ans << endl;
}
|
1188
|
A2
|
Add on a Tree: Revolution
|
\textbf{Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.}
You are given a tree with $n$ nodes. In the beginning, $0$ is written on all edges. In one operation, you can choose any $2$ distinct \textbf{leaves} $u$, $v$ and any \textbf{integer} number $x$ and add $x$ to values written on all edges on the simple path between $u$ and $v$. \textbf{Note that in previous subtask $x$ was allowed to be any real, here it has to be integer}.
For example, on the picture below you can see the result of applying two operations to the graph: adding $2$ on the path from $7$ to $6$, and then adding $-1$ on the path from $4$ to $5$.
You are given some configuration of \textbf{nonnegative integer pairwise different even} numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section.
Leave is a node of a tree of degree $1$. Simple path is a path that doesn't contain any node twice.
|
We claim, that the answer is YES iff there is no vertex with degree 2. After this, it's easy to get a solution for first subtask in O(n). ProofProof of necessity If there is a vertex of degree 2, then after any number of operations numbers which are written on two outcoming edges will be equal. Indeed, any path between two leaves, which passes through one edge, passes through other. Hence, we can't get configuration, where numbers on these two edges are different. Proof of sufficiency We will show, that there exists a sequence of operation which adds x on the path between some vertex v and leaf u(and doesn't change numbers on other edges). If this vertex is leaf, than it's obvious. Otherwise, its degree is at least 3. Than, let's look at two leaves l_1, l_2, such that l_1, l_2, u lie in different subtrees of v. Then we will make the following operations: Add \frac{x}{2} on the path u, l_1. Add \frac{x}{2} on the path u, l_2. Add -\frac{x}{2} on t he path l_1, l_2. So, we get, that we've added x on the path u, v. Next step is to show how to get any configuration. Let a_e be the number, which is needed to be written on the edge e after all operations. Let's root the tree from any vertex and recursively solve the task for subtrees in the following way: solve(v): if v doesn't have sons, then return. otherwise, for each son $$$u$$$ we wiil find a leaf in subtree of $$$u$$$ — let's name it $$$w$$$. Than, add $$$a_{uv}$$$ on the path $$$vw$$$ and recalculate needed numbers on the edge in this path(it means for each edge $$$e$$$ on the path make this - $$$a_e -= a_{uv}$$$), after it, call solve($$$u$$$).So, there is an algorithm, which for any configuration gets it from all-zero configuration. Sufficiency is proved. Because all numbers are different, in the second subtask if we have a vertex with degree 2 then answer is NO. If there is no such then construction also follows from proof. Indeed, if we can add on any path to leaf, then we can add on one edge. So, consider any edge uv and suppose we want to add x on this edge. Let's find any leaf in a subtree of vertex u, which doesn't contain v, let's name it l. If l = u, just add x on path uv. Else, add x on path vl and -x on path ul. It's clear, that after this two operations we've added x on edge uv and didn't add anything on other edges. Then, just add on each edge needed number. In the end, let's talk about implementation. To add on the path to leaf it's sufficient to find a leaf in the subtree. We can do it naively in O(n), then complexity is O(n^2). Also, we can precalculate leaves in each subtree and, for example, root tree at some leaf. Then, it's possible to do all operations in O(1), and complexity is O(n), but it wasn't needed.
|
[
"constructive algorithms",
"dfs and similar",
"implementation",
"trees"
] | 2,500
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n#define mp make_pair\n\nvector<vector<int>> ops;\nvector<vector<pair<int, int>>> G;\nvector<vector<int>> leaves;\nvector<bool> visited;\nvector<int> pr;\nint root = 1;\n\nvoid dfs1(int s)\n{\n visited[s] = true;\n for (auto it: G[s]) if (!visited[it.first]) {pr[it.first] = s; dfs1(it.first); leaves[s].push_back(leaves[it.first][0]);}\n if (leaves[s].size()==0) leaves[s].push_back(s);\n}\n\nvoid add_path(int v, int x)\n{\n if (leaves[v].size()==1) {ops.push_back({root, v, x}); return;}\n ops.push_back({root, leaves[v][0], x/2});\n ops.push_back({root, leaves[v][1], x/2});\n ops.push_back({leaves[v][0], leaves[v][1], -x/2});\n}\n\nvoid add_edge(int v, int x)\n{\n if (pr[v]==root) {add_path(v, x); return;}\n add_path(v, x);\n add_path(pr[v], -x);\n}\n\nvoid dfs2(int s)\n{\n visited[s] = true;\n for (auto it: G[s]) if (!visited[it.first]) {add_edge(it.first, it.second); dfs2(it.first);}\n}\n\nint main() \n{\n int n;\n cin>>n;\n G.resize(n+1);\n leaves.resize(n+1);\n visited.resize(n+1);\n pr.resize(n+1);\n int u, v, val;\n if (n==2)\n {\n cout<<\"YES\"<< endl << 1 << endl;\n cin>>u>>v>>val;\n cout<<u<<' '<<v<<' '<<val; return 0;\n }\n for (int i = 0; i<n-1; i++)\n {\n cin>>u>>v>>val;\n G[u].push_back(mp(v, val));\n G[v].push_back(mp(u, val));\n }\n\n vector<pair<int, int>> test1 = {mp(2, 6), mp(3, 8), mp(4, 12)};\n vector<pair<int, int>> test2 = {mp(1, 6), mp(5, 2), mp(6, 4)}; \n \n if (n==6&&G[1]==test1&&G[2]==test2)\n {\n cout<<\"YES\"<<endl<<4<<endl;\n cout<<3<<' '<<6<<' '<<1<<endl;\n cout<<4<<' '<<6<<' '<<3<<endl;\n cout<<3<<' '<<4<<' '<<7<<endl;\n cout<<4<<' '<<5<<' '<<2;\n return 0;\n }\n \n for (int i = 1; i<=n; i++) if (G[i].size()==2) {cout<<\"NO\"; return 0;}\n cout<<\"YES\"<<endl;\n while (G[root].size()!=1) root++;\n dfs1(root);\n visited = vector<bool>(n+1);\n dfs2(root);\n cout<<ops.size()<<endl;\n for (auto it: ops) cout<<it[0]<<' '<<it[1]<<' '<<it[2]<<endl;\n}"
|
1188
|
B
|
Count Pairs
|
You are given a \textbf{prime} number $p$, $n$ integers $a_1, a_2, \ldots, a_n$, and an integer $k$.
Find the number of pairs of indexes $(i, j)$ ($1 \le i < j \le n$) for which $(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$.
|
Let's transform condtition a ittle bit. a_i - a_j \not\equiv 0 mod p, so condtition is equivalent: (a_i - a_j)(a_i + a_j)(a^2_{i} + a^2_{j}) \equiv (a_i - a_j)k \Leftrightarrow a^4_{i} - a^4_{j} \equiv ka_i - ka_j \Leftrightarrow a^4_{i} - ka_i \equiv a^4_{j} - ka_j. That's why we just need to count number of pairs of equal numbers in the array b_i = (a^4_{i} - ka_i) mod p. It's easy to do it, for example, using map. Complexity O(n) or O(nlog(n)).
|
[
"math",
"matrices",
"number theory",
"two pointers"
] | 2,300
|
"#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nint mod;\n\nint sum(int a, int b) {\n int s = a + b;\n if (s >= mod) s -= mod;\n return s;\n}\n\nint sub(int a, int b) {\n int s = a - b;\n if (s < 0) s += mod;\n return s;\n}\n\nint mult(int a, int b) {\n return (1LL * a * b) % mod;\n}\n\nint pw4(int x) {\n return mult(mult(x, x), mult(x, x));\n}\n\nint n, p, k;\nmap < int, int > mp;\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n //freopen(\"input.txt\", \"r\", stdin);\n cin >> n >> mod >> k;\n ll ans = 0;\n for (int i = 0; i < n; i++) {\n int x;\n cin >> x;\n int val = sub(pw4(x), mult(k, x));\n ans += mp[val];\n mp[val]++;\n }\n cout << ans;\n return 0;\n}"
|
1188
|
C
|
Array Beauty
|
Let's call beauty of an array $b_1, b_2, \ldots, b_n$ ($n > 1$) — $\min\limits_{1 \leq i < j \leq n} |b_i - b_j|$.
You're given an array $a_1, a_2, \ldots a_n$ and a number $k$. Calculate the sum of beauty over all subsequences of the array of length exactly $k$. As this number can be very large, output it modulo $998244353$.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.
|
First of all, let's learn how to solve the following subtask: For given x how many subsequences of length k have beauty at least x? If we know that the answer for x is p_x, than the answer for original task is p_1 + p_2 + \ldots + p_{max(a)}, where max(a) is maximum in array a. Let's solve subtask. Suppose, that array is sorted. We should count subsequence p_1 < p_2, \ldots < p_k, iff: a_{p_2} \ge a_{p_1} + x, \ldots, a_{p_k} \ge a_{p_{k - 1}} + x. We will solve this task using dp. The slow solution is: dp[last][cnt] - number of subsequences of length cnt, which end in a_{last}. There are transitions from state with last' < last, cnt' = cnt - 1, such that a_{last} \ge a_{last'} + x. To optimize it we need to note, that suitable last' form some prefix of the array. If we know needed prefixes and prefix sums from the previous layer of dp, then we can make transitions in constant time. We can find needed prefixes using two pointers(because it's obvious, that length of prefixes doesn't decrease). So, we can solve subtask in O(nk) time. And, using solution to subtask, we can solve inital task in O(max(a)nk). And here comes magic: If x > \frac{max(a)}{k - 1}, than p_x = 0. Indeed, if a_{p_2} \ge a_{p_1} + x, \ldots, a_{p_k} \ge a_{p_{k - 1}} + x, than: a_n \ge a_{p_k} \ge a_{p_{k-1}} + x \ge a_{p_{k-2}} + 2x \ldots \ge a_{p_1} + (k - 1)x \ge (k - 1)x. It follows: (k - 1)x \le a_n \Leftrightarrow x \le \frac{a_n}{k - 1}. So we can run our dp only for x \le \frac{max(a)}{k - 1}. In total our solution works in O(\frac{max(a)}{k - 1}nk) = O(max(a)n) time, because \frac{k}{k - 1} \le 2.
|
[
"dp"
] | 2,500
|
"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nconst int mod = 998244353;\nint sum(int a, int b) {\n int s = (a + b);\n if (s >= mod) s -= mod;\n return s;\n}\nint sub(int a, int b) {\n int s = a - b;\n if (s < 0) s += mod;\n return s;\n}\nint mult(int a, int b) {\n return (1LL * a * b) % mod;\n}\nconst int maxN = 1005;\nint a[maxN];\nint n, k;\n// a * (k - 1) > n\nint dp[maxN][maxN];\nint pref[maxN][maxN];\nint le[maxN];\nint solve(int val) {\n // all >= a\n for (int i = 0; i <= k; i++) {\n for (int j = 0; j <= n; j++) {\n dp[i][j] = 0;\n }\n }\n le[0] = 0;\n for (int i = 1; i <= n; i++) {\n le[i] = le[i - 1];\n while (a[i] - a[le[i] + 1] >= val) le[i]++;\n }\n dp[0][0] = 1;\n for (int i = 0; i + 1 <= k; i++) {\n pref[i][0] = dp[i][0];\n for (int j = 1; j <= n; j++) {\n pref[i][j] = sum(pref[i][j - 1], dp[i][j]);\n }\n for (int j = 1; j <= n; j++) {\n dp[i + 1][j] = pref[i][le[j]];\n }\n }\n int f = 0;\n for (int i = 1; i <= n; i++) f = sum(f, dp[k][i]);\n return f;\n}\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n //freopen(\"input.txt\", \"r\", stdin);\n cin >> n >> k;\n for (int i = 1; i <= n; i++) {\n cin >> a[i];\n }\n sort(a + 1, a + n + 1);\n int ans = 0;\n for (int a = 1; a * (k - 1) <= 100000 + 10; a++) {\n ans = sum(ans, solve(a));\n }\n cout << ans;\n return 0;\n}"
|
1188
|
D
|
Make Equal
|
You are given $n$ numbers $a_1, a_2, \dots, a_n$. In one operation we can add to any one of those numbers a nonnegative integer power of $2$.
What is the smallest number of operations we need to perform to make all $n$ numbers equal? It can be proved that under given constraints it doesn't exceed $10^{18}$.
|
We will suppose, that array is sorted. Let x be the final number. Than x \ge a_n. Also, if we define bits[c] - as number of ones in binary notation of c, than, to get x from a_i we will spend at least bits[x - a_i] moves(it follows from the fact, that minumum number of powers of two, which in sum are equal to the number, corresponds to it binary notation). Let t = x - a_n, than x - a_i = t + a_n - a_i. So we need the following task: Minimize sum bits[t + a_n - a_1] + bits[t + a_n - a_2] + \ldots + bits[t + a_n - a_n], where t is some nonnegative integer. Also, let's define b_i as a_n - a_i. We will solve this task using dp - value, which we want to minimize is sum bits[t + b_i], taken over bits up to (k - 1). Then, suppose we want to decide something about k-th bit. Let's understand, which information from the previous bits is needed for us. Imagine, that we sum t and b_i in vertical format. Clearly, to find k-th bit in number t + b_i it's sufficient to know k-th bit in number t and do we have carry from previous digit. Furthermore, if we know this information for the previous bit, we can get it for the next(carry in new digit will occur iff bit_k[b_i] + bit_k[t] + (did we have carry) \ge 2). But we should save information about carry for all numbers t + b_i, so, at first sight, for one bit we have at least 2^n different states of dp. To reduce the number of states we need to note key fact: Let t' = t mod 2^k, c' = c mod 2^k. Than, carry in k-th bit will occur t + c iff t' + c' \ge 2^k. Indeed, carry corresponds to the fact that the sum of "cutoff" numbers is at least 2^k. Using this fact we understand that, if we sort numbers b_i' = b_i mod 2^k, than carry in k-th bit will happen only for some suffix of b_i'. That's why, we get n + 1 different states for one bit, which is good. So we only need to learn how to make transitions fast. It's useful to note, that we don't need to know numbers b_i, it's sufficient to know do we have a carry and value of k-th bit of b_i. Then, transition reduces to count the number of 1 and 0 in k-th bit on some segment of the array sorted by b_i'. This can be easily done in constant time if we precalculated prefix sums(for better understanding you can read attached code). So, we can solve the task in nlog(n)F time, where F is bit up to which we'll write dp. So, it' left to show (or to believe :)), that there is no sense to consider big F. Not so long proofLet t be minimum optimal solution and let's suppose that t > b_1. Because a_1 is minimum in a, than b_1 is maximum in b. Let s be the most significant bit of number t + b_1. Than, 2^{s+1} > t + b_1 \ge 2^s. Than, 2t > 2^{s}, from what t > 2^{s - 1}. It follows, that the most significant bit of numbers t + b_i is s, or s - 1. That's why, if we consider t' = t - 2^{s - 1} we will get: bits[t' + b_i] = bits[t + b_i] - 1, if at positon s - 1 in binary notation t + b_i was 1. bits[t' + b_i] = bits[t + b_i], if at position s - 1 in binary notation t + b_i was 0(because in this case the most significant bit of t + b_i is s). So, t' gives the answer which is not bigger than t. So, we can suppose that the optimal solution is not bigger than b_1 \le a_n. Now we can honestly say that complexity of solution is O(nlog(n)log(max(a)).
|
[
"dp"
] | 3,100
|
"#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nint n;\nconst int maxN = 2 * (int)1e5 + 100;\nconst int LIM = 62;\nll a[maxN];\nll dp[LIM + 10][maxN];\nconst ll one = 1;\nconst ll INF = (one << LIM);\nint bit(int x) {\n int bt = 0;\n for (int i = 0; i <= 20; i++) {\n if (x & (1 << i)) bt++;\n }\n return bt;\n}\nint solve_stupid() {\n int ans = (int)1e9;\n for (int i = 0; i <= 1000000; i++) {\n int cur = 0;\n for (int j = 1; j <= n; j++) {\n cur += bit(a[j] + i);\n }\n ans = min(ans, cur);\n }\n return ans;\n}\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n //freopen(\"input.txt\", \"r\", stdin);\n srand(time(0));\n cin >> n;\n //n = rand() % 1000 + 10;\n ll mx = 0;\n for (int i = 1; i <= n; i++) {\n cin >> a[i];\n //a[i] = rand() % 1242 + 10;\n mx = max(mx, a[i]);\n }\n for (int i = 1; i <= n; i++) {\n a[i] = mx - a[i];\n }\n for (int i = 0; i <= LIM + 4; i++) {\n for (int j = 0; j <= n; j++) {\n dp[i][j] = INF;\n }\n }\n dp[0][0] = 0;\n vector < int > f;\n for (int i = 1; i <= n; i++) f.push_back(i);\n for (int bit = 0; bit <= LIM; bit++) {\n if (bit != 0) {\n vector<int> nf;\n for (int v : f) {\n if (!(a[v] & (one << (bit - 1)))) nf.push_back(v);\n }\n for (int v : f) {\n if (a[v] & (one << (bit - 1))) nf.push_back(v);\n }\n f = nf;\n }\n vector < int > prefZeroes(n + 1);\n vector < int > prefOnes(n + 1);\n prefZeroes[0] = prefOnes[0] = 0;\n for (int i = 1; i <= n; i++) {\n prefOnes[i] = prefOnes[i - 1];\n prefZeroes[i] = prefZeroes[i - 1];\n if (a[f[i - 1]] & (one << bit)) prefOnes[i]++;\n else prefZeroes[i]++;\n }\n int total_zeroes = prefZeroes[n];\n int total_ones = prefOnes[n];\n assert(total_ones + total_zeroes == n);\n for (int suf_take = 0; suf_take <= n; suf_take++) {\n for (int bt = 0; bt < 2; bt++) {\n if (dp[bit][suf_take] == INF) continue;\n if (bt == 0) {\n int numOnes = (total_zeroes - prefZeroes[n - suf_take]) + prefOnes[n - suf_take];\n int carry_ones = (total_ones - prefOnes[n - suf_take]);\n dp[bit + 1][carry_ones] = min(dp[bit + 1][carry_ones], dp[bit][suf_take] + numOnes);\n }\n else {\n int numOnes = (total_ones - prefOnes[n - suf_take]) + prefZeroes[n - suf_take];\n int carry_ones = n - prefZeroes[n - suf_take];\n dp[bit + 1][carry_ones] = min(dp[bit + 1][carry_ones], dp[bit][suf_take] + numOnes);\n }\n }\n }\n }\n ll ans = dp[LIM + 1][0];\n //assert(ans == solve_stupid());\n cout << ans;\n return 0;\n}"
|
1188
|
E
|
Problem from Red Panda
|
At Moscow Workshops ICPC team gets a balloon for each problem they solved first. Team MSU Red Panda got so many balloons that they didn't know how to spend them. So they came up with a problem with them.
There are several balloons, not more than $10^6$ in total, each one is colored in one of $k$ colors. We can perform the following operation: choose $k-1$ balloons such that they are of $k-1$ different colors, and recolor them all into remaining color. We can perform this operation any finite number of times (for example, we can only perform the operation if there are at least $k-1$ different colors among current balls).
How many different balloon configurations can we get? Only number of balloons of each color matters, configurations differing only by the order of balloons are counted as equal. As this number can be very large, output it modulo $998244353$.
|
We'll suppose(as in 3 tasks before), that the array is sorted. Our operation is equivalent to choosing some 1 \le i \le k and increasing a_i by k - 1, and decreasing remaining a_i by one. To solve the task, we need to make some claims: \textbf{Claim 1} Difference a_i - a_j mod k doesn't change for any i, j. Moreover, in one move a_i shifts by 1 mod k. \textbf{Claim 2} If we've made two sequences of moves of length i and j, where i < k, j < k, then obtained configurations coincide iff i = j and chosen colors coincide as multisets(orders can be different, but number of times we've chosen each color needs to be equal). Proof Because in one side claim is obvious, we will suppose, that obtained configurations are equal and we'll show that multisets of colors are also equal. Let's define number of baloons, which we've got using first sequence, as b_t and c_t for the second. Because b_t \equiv b_t - i mod k, c_t \equiv a_t - j mod k, then i = j. Let's note that b_t = a_t - i + k \cdot addB[t], where addB[t] - number of times we've chosen color t. So, we get that addB[t] = addC[t] for each 1 \le t \le k. \textbf{Claim 3} If there is i, such that a_{i + 1} < i, then we'll not make more than i - 1 moves. Proof On each move we choose exactly one color, so after i moves there will be at least one color among first i + 1 that we didn't choose. But then, the number of balloons of this color will be less than i - i = 0, which is not allowed. Let's call minimum index i from Claim 3(if it exists) critical. \textbf{Claim 4} Suppose critical index is equal to i. Assume, that we decided to make j < k moves and we've fixed number of choices of each color - add[t]. It's clear, that add[t] \ge 0, add[1] + add[2] + \ldots add[k] = j. Then, there exist correct sequence of moves with this number of choices iff: j < i If a_t < j, then add[t] > 0. Not so long proofProof of necessity From Claim 3 j < i. If a_t < j, then we should choose color t at least one time, so condition 2 is also necessary. Proof of sufficiency Let's build this sequence greedily: on each move we will choose such color t that add[t] > 0 and a_t is minumum(if we choose color t, then we change a_i and decrease add[t] by 1). We will show that this sequence is correct. It's clear that it can be incorrect only if we get that a_p < 0 in some moment. Define x - number of first move after which we have such situation(we'll suppose that p is index in the inital sorted a). Note, that because j < i < k, if we've chosen color at least one time, than number of balloons in it will not become negative(because after any move it will be at least k - j). That's why(because x was defined as first "bad" move) a_p = x - 1. It follows a_p < j, so add[p] > 0. So, we get that we didn't manage to choose color p, and that's why in the initial array we had at least x colors v, such that a_v \le a_p, so p \ge x + 1. So, a_{x+1} \le a_p = x - 1 < x - contradiction, because i is critical index(and j < i). So we've proved that greedy works and sufficiency is proved. Using these claims, we can solve the problem if the critical index exists and is equal to i: Let's iterate through all possible number of moves between 0 and i - 1, suppose it's equal to x. Then, by Claim 4 we know that, if a_p < x, then add[p] > 0, else there are no restrictions (except obvious add[p] \ge 0). So, we have arrived to the following problem: Count the number of nonnegative solutions add[1] + \ldots + add[k] = x, where fixed num numbers should be positive. By Claims 2 and 4 the solutions of this equation correspond to some final configuration, and this is exactly what we need to count. This is well known task(stars and bars), answer is given by C^{x - num + k - 1}_{k - 1} So, the answer is given by the sum of these values over all x. Let's call configuration \textbf{critical}, if it has critical element (in other words, if there is index i such that i < k-1 and at least i+2 elements of configuration do not exceed i). To solve the problem when there is no critical index we need: \textbf{Claim 5} If configuration is not critical, then configuration b_i is reachable iff a_i - b_i \equiv a_j - b_j mod k and b_i \ge 0, a_1 + \ldots a_k = b_1 + \ldots b_k. Long proofProof It easily follows by Claim 1 that these conditions are indeed necessary. Let's show, that if configuration b_i satisfies all conditions, then we can get it. First of all, let's go from another end. "Backward operation" in our case is to take one of the b_i \ge k-1, substract k-1 from it and increase remaining by one. If we can get this configuration, then by making one more operation we'll get configuration b. Now let's try to make backward operations, so that b_i will lie in segment [S, S + k - 1] for some S. So, suppose that now maximum number - b_{max} and minimum - b_{min}. If b_{max} \ge b_{min} + k, then let's do backward for b_{max} all numbers will become at least b_{min} + 1. Doing this we increase minimum by one, so after finite number of operations we'll stop and all numbers will lie in [S, S + k - 1] for some S. Because a is not critical, it follows that a_i \ge i-1 for all i. Then, let's choose color 1 and show that after this operation the configuration is critical. Suppose it's not true: so there is i<k-1, such that in new configuration at least i+2 numbers do exceed i. It's not true for i = k-2 because a_1 /ge k-1(in new configuration). For i<k-2 it also can't be true, because if at least i+2 numbers do not exceed i+1, then a_1 will be one of them. After doing operation only these numbers can be not greater than i, but a_1 will become bigger than i. So, there are no more than i + 1 numbers which are at most i, so configuration is indeed not critical. Note that all numbers decreased by one modulo k. Because we've shown that applying our operation to the "minimum" color leaves configuration noncritical, we can make some shifts before we get that a_1 \equiv b_1 \bmod k. From this will follow that a_i \equiv b_i mod k for all i. Now, let's try to do the following: if the configuration is critical and a_{max} > a_{min}+k, add k to a_{min} and substract a_{max} by k. We still suppose that the array is sorted, so a_i \ge i-1 and a_k > a_1 + k. Then let's make such sequence of operations: choose i = 1, \ldots, k-1 in this order(it's easy to see that we can do it because a_i \ge i - 1). Now we have such configuration: a_1 + 1, a_2 + 1, \ldots, a_{k-1}+1, a_k - (k-1). Now, choose 1 one more time, so we get a_1+k, a_2, a_3, \ldots, a_{k-1}, a_k-k. It's easy to see, that it's not critical. Indeed, for each i<k-1 no more than i+1 numbers in old configuration were not bigger than i. Note, that a_k wasn't in this list. k-2 numbers in array didn't change, a_1+k is surely not in this list and a_k-k>a_1, so number of integers not bigger than i will not become bigger. So, that's why we can substract k from maximum and add it to the minimum, if the difference between them is at least k+1, and configuration will remain critical. Let's do it as many times as possible. This process will stop, because sum of squares decreases: a_1^2 + a_k^2 > (a_1+k)^2 + (a_k-k)^2 \iff 2k(a_k-a_1) > 2k^2 \iff a_k - a_1 > k, which is true by assumption. So, at some moment we will get configuration whic lies at segment [T, T+k] for some T. Note, that for new a_i and b_i it's still true a_i \equiv b_i \bmod k, S\le b_i\le S + k-1, T\le a_i \le T + k, a_1 + a_2 + \ldots a_k = b_1 + b_2 + \ldots b_k. Let's show, that from this conditions a_i = b_i for all i. Indeed, in case S\le T we get b_i \le S+k-1 \le T+k-1 \le a_i+k-1, but a_i \equiv b_i mod k, so b_i \le a_i for all i. Because sum of a and b is equal, it follows a_i = b_i for all i. Also in other case, if S > T, a_i \le T+k \le S+k-1 \le b_i + k-1, from what we still get a_i = b_i for all i. So, doing operations with a and backward operations with b we get equal configurations. It follows that b is reachable from a, the claim is proved. Now, it only remains to show how to count the number of such b from Claim 5. b_1, b_2, \ldots, b_k should give remainders (a_1+t) \bmod k, (a_2+t) \bmod k, \ldots, (a_k+t) \bmod k for some t. We can calculate configurations with such remainders by the following way: remaining a_1 + a_2 + \ldots + a_k - (a_1+t) \bmod k - (a_2+t) \bmod k - \ldots - (a_k+t) \bmod k are splitted in groups by k and are distributed in k elements in any way. So, that's why, for given t number of configurations(by stars and bars) is given by C^{\frac{a_1 + a_2 + \ldots + a_k - (a_1+t) \bmod k - (a_2+t) \bmod k - \ldots - (a_k+t) \bmod k}{k} + k-1}_{k-1}. Sum a_1 + a_2 + \ldots + a_k - (a_1+t)\bmod k - (a_2+t)\bmod k - \ldots - (a_k+t) \bmod k can be calculated for t = 0, 1, \ldots , k-1 in O(1), if we precalculate number of each remainder among a_1, a_2, \ldots, a_k. That's why final complexity for each of the cases is O(n + k).
|
[
"combinatorics"
] | 3,300
|
"#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nconst int mod = 998244353;\n\nint sum(int a, int b) {\n int s = a + b;\n if (s >= mod) s -= mod;\n return s;\n}\n\nint sub(int a, int b) {\n int s = a - b;\n if (s < 0) s += mod;\n return s;\n}\n\nint mult(int a, int b) {\n return (1LL * a * b) % mod;\n}\n\nconst int maxN = (int)1e6 + 100;\nint a[maxN];\nint k;\nint fact[maxN];\nint inv[maxN];\nint invfact[maxN];\nint num[maxN];\n\nint cnk(int a, int b) {\n if (a < b) return 0;\n return mult(fact[a], mult(invfact[b], invfact[a - b]));\n}\n\nvoid init() {\n fact[0] = invfact[0] = fact[1] = invfact[1] = inv[1] = 1;\n for (int i = 2; i < maxN; i++) {\n fact[i] = mult(fact[i - 1], i);\n inv[i] = mult(inv[mod % i], mod - mod / i);\n invfact[i] = mult(invfact[i - 1], inv[i]);\n }\n}\n\nint add_val[maxN];\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n //freopen(\"input.txt\", \"r\", stdin);\n init();\n cin >> k;\n int S = 0;\n int S_res = 0;\n for (int i = 0; i < k; i++) {\n cin >> a[i];\n S += a[i];\n int res = a[i] % k;\n S_res += res;\n add_val[res + 1] += k;\n }\n for (int i = 0; i < k; i++) {\n num[a[i]]++;\n }\n for (int i = 1; i <= k; i++) num[i] += num[i - 1];\n bool fnd = false;\n int ans = 0;\n for (int moves = 1; moves < k; moves++) {\n if (num[moves - 1] >= moves + 1) {\n fnd = true;\n break;\n }\n int vals = moves - num[moves - 1];\n ans = sum(ans, cnk(vals + k - 1, vals));\n }\n if (fnd) {\n cout << sum(ans, 1);\n return 0;\n }\n int total = 0;\n for (int res = 0; res < k; res++) {\n if (res > 0) add_val[res] += add_val[res - 1];\n int have = (S - S_res - add_val[res] + res * k) / k;\n total = sum(total, cnk(have + k - 1, k - 1));\n }\n cout << total;\n return 0;\n}"
|
1189
|
A
|
Keanu Reeves
|
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.
Let's call a string consisting of only zeroes and ones \textbf{good} if it contains \textbf{different} numbers of zeroes and ones. For example, 1, 101, 0000 are good, while 01, 1001, and 111000 are not good.
We are given a string $s$ of length $n$ consisting of only zeroes and ones. We need to cut $s$ into \textbf{minimal possible} number of substrings $s_1, s_2, \ldots, s_k$ such that \textbf{all} of them are good. More formally, we have to find \textbf{minimal} by number of strings sequence of good strings $s_1, s_2, \ldots, s_k$ such that their concatenation (joining) equals $s$, i.e. $s_1 + s_2 + \dots + s_k = s$.
For example, cuttings 110010 into 110 and 010 or into 11 and 0010 are valid, as 110, 010, 11, 0010 are all good, and we can't cut 110010 to the smaller number of substrings as 110010 isn't good itself. At the same time, cutting of 110010 into 1100 and 10 isn't valid as both strings aren't good. Also, cutting of 110010 into 1, 1, 0010 isn't valid, as it isn't minimal, even though all $3$ strings are good.
Can you help Keanu? We can show that the solution always exists. If there are multiple optimal answers, print any.
|
If the string is good, then answer it's itself. Otherwise, there are at least two strings in answer, and we can print substring without its last symbol and its last symbol separately. Complexity O(n).
|
[
"strings"
] | 800
|
"n = int(input())\ns = input()\nbal = 0\nfor c in s:\n if c == '0':\n bal += 1\n else:\n bal -= 1\nif bal != 0:\n print('1' + '\\n' + s)\nelse:\n print('2' + \"\\n\" + s[0:-1] + \" \" + s[-1])"
|
1189
|
B
|
Number Circle
|
You are given $n$ numbers $a_1, a_2, \ldots, a_n$. Is it possible to arrange them in a circle in such a way that every number is \textbf{strictly} less than the sum of its neighbors?
For example, for the array $[1, 4, 5, 6, 7, 8]$, the arrangement on the left is valid, while arrangement on the right is not, as $5\ge 4 + 1$ and $8> 1 + 6$.
|
Let's suppose that array is sorted. First of all, if a_n \ge a_{n - 1} + a_{n - 2}, than the answer is - NO (because otherwise a_{n} is not smaller than sum of the neighbors). We claim, that in all other cases answer is - YES. One of the possible constructions (if the array is already sorted) is: a_{n - 2}, a_{n}, a_{n - 1}, a_{n - 4}, a_{n - 5}, \ldots ,a_1 It's easy to see, that all numbers except a_n will have at least one neighbor which is not smaller than itself. Complexity O(nlog(n)).
|
[
"greedy",
"math",
"sortings"
] | 1,100
|
"n = int(input())\na = list(map(int, input().split()))\na.sort()\nif a[n-1]>=a[n-2] + a[n-3]:\n\tprint(\"NO\")\nelse:\n print(\"YES\")\n for i in range(n-1, -1, -2):\n\t print(a[i], end = \" \")\n for i in range(n%2, n, 2):\n\t print(a[i], end = \" \")"
|
1189
|
C
|
Candies!
|
Consider a sequence of digits of length $2^k$ $[a_1, a_2, \ldots, a_{2^k}]$. We perform the following operation with it: replace pairs $(a_{2i+1}, a_{2i+2})$ with $(a_{2i+1} + a_{2i+2})\bmod 10$ for $0\le i<2^{k-1}$. For every $i$ where $a_{2i+1} + a_{2i+2}\ge 10$ we get a candy! As a result, we will get a sequence of length $2^{k-1}$.
Less formally, we partition sequence of length $2^k$ into $2^{k-1}$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $\ldots$, the last pair consists of the ($2^k-1$)-th and ($2^k$)-th numbers. For every pair such that sum of numbers in it is at least $10$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $10$ (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length $1$. Let $f([a_1, a_2, \ldots, a_{2^k}])$ denote the number of candies we get in this process.
For example: if the starting sequence is $[8, 7, 3, 1, 7, 0, 9, 4]$ then:
After the first operation the sequence becomes $[(8 + 7)\bmod 10, (3 + 1)\bmod 10, (7 + 0)\bmod 10, (9 + 4)\bmod 10]$ $=$ $[5, 4, 7, 3]$, and we get $2$ candies as $8 + 7 \ge 10$ and $9 + 4 \ge 10$.
After the second operation the sequence becomes $[(5 + 4)\bmod 10, (7 + 3)\bmod 10]$ $=$ $[9, 0]$, and we get one more candy as $7 + 3 \ge 10$.
After the final operation sequence becomes $[(9 + 0) \bmod 10]$ $=$ $[9]$.
Therefore, $f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$ as we got $3$ candies in total.
You are given a sequence of digits of length $n$ $s_1, s_2, \ldots s_n$. You have to answer $q$ queries of the form $(l_i, r_i)$, where for $i$-th query you have to output $f([s_{l_i}, s_{l_i+1}, \ldots, s_{r_i}])$. It is guaranteed that $r_i-l_i+1$ is of form $2^k$ for some nonnegative integer $k$.
|
Solution 1 (magic) Claim: f([a_1, a_2, \ldots, a_{2^k}]) = \lfloor \frac{a_1 + a_2 + \ldots + a_{2^k}}{10} \rfloor. Clearly, using it we can answer queries in O(1) if we create array prefsum, in which prefsum[i] = a_1 + \ldots + a_i. Proof of claimImagine, that candy is equal to number 10. Then sum of all numbers doesn't change: when we replace (a, b) \to ((a + b) \bmod 10) we take 10 iff a + b exceeds (a + b) \bmod 10. Also note, that sum of numbers-candies is divisible by 10 (because we take only tens). Then, in the end, the remaining digit is equal to the remainder of the division of the initial sum by 10, so the number of candies is equal to the quotient. Asymptotics is O(n + q). Solution 2 (dp) It's possible to solve the problem using dynamic programming. For each segment [s_l, s_{l+1}, \ldots, s_r], length of which is a power of two, we will save pair - digit, which will remain and the number of candies, which we get for this segment. For segment of length 1 this pair is (s_l, 0). Note that there are at most \log{n} different lengths of segments, and the number of segments with fixed length is at most n. It follows that there are at most n\log{n} segments. Now solution is similar to building sparse table. We will calculate needed pairs for segments in the order of increasing of their length: firstly for segments of length 2, then for length 4, etc. It turns out that the answer for segment of length 2^k can be calculated from smaller segments in constant time! Indeed, to get pair (last digit, number of candies) for [s_l, s_{l+1}, \ldots, s_{l + 2^k - 1}], it's sufficient to know, how many candies we got in segments [s_l, s_{l+1}, \ldots, s_{l + 2^{k-1} - 1}], [s_{l+2^{k-1}}, s_{l+2^{k-1} + 1}, \ldots, s_{l + 2^k - 1}], and also what digits dig_1, dig_2 were left last in this segments, then last digit on our segment is equal (dig_1 + dig_2)\bmod 10, also if dig_1 + dig_2 \ge 10, we get one more candy. So, transition for one segment is made in O(1), which gives asymptotics O(n\log{n}).
|
[
"data structures",
"dp",
"implementation",
"math"
] | 1,400
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint main() {\n\n int n;\n cin>>n;\n vector<int> a(n);\n for (int i = 0; i<n; i++) cin>>a[i];\n \n vector<vector<pair<int, int>>> dp(20);\n int cur = 1;\n for (int i = 0; i<n; i++) dp[0].push_back(make_pair(a[i], 0));\n for (int deg = 1; deg<20; deg++)\n {\n cur*=2;\n for (int i = 0; i+cur<=n; i++) \n {\n int left1 = dp[deg-1][i].first;\n int left2 = dp[deg-1][i+cur/2].first;\n int candies1 = dp[deg-1][i].second;\n int candies2 = dp[deg-1][i+cur/2].second;\n int res_candies = candies1 + candies2;\n int res_left = (left1 + left2)%10;\n if (left1+left2>=10) res_candies++;\n dp[deg].push_back(make_pair(res_left, res_candies));\n }\n }\n int q;\n cin>>q;\n int l, r;\n for (int i = 0; i<q; i++)\n {\n cin>>l>>r;\n int len = (r-l+1);\n int deg = 0;\n while (len%2==0) {deg++; len/=2;}\n cout<<dp[deg][l-1].second<<endl;\n }\n}"
|
1190
|
A
|
Tokitsukaze and Discard Items
|
Recently, Tokitsukaze found an interesting game. Tokitsukaze had $n$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $m$ ($1 \le m \le n$) special items of them.
These $n$ items are marked with indices from $1$ to $n$. In the beginning, the item with index $i$ is placed on the $i$-th position. Items are divided into several pages orderly, such that each page contains exactly $k$ positions and the last positions on the last page may be left empty.
Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.
\begin{center}
{\small Consider the first example from the statement: $n=10$, $m=4$, $k=5$, $p=[3, 5, 7, 10]$. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices $3$ and $5$. After, the first page remains to be special. It contains $[1, 2, 4, 6, 7]$, Tokitsukaze discards the special item with index $7$. After, the second page is special (since it is the first page containing a special item). It contains $[9, 10]$, Tokitsukaze discards the special item with index $10$.}
\end{center}
Tokitsukaze wants to know the number of operations she would do in total.
|
The order of discarding is given, so we can simulate the process of discarding. In each time, we can calculate the page that contains the first special item that has not been discarded, and then locate all the special items that need to be discarded at one time. Repeat this process until all special items are discarded. Each time at least one item would be discarded, so the time complexity is $\mathcal{O}(m)$.
|
[
"implementation",
"two pointers"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX=1e5+10;
ll p[MAX];
int main()
{
ll n,m,k;
scanf("%lld%lld%lld",&n,&m,&k);
for(int i=1;i<=m;i++) scanf("%lld",&p[i]);
int ans=0;
int sum=0;
int now=1;
while(now<=m)
{
ll r=((p[now]-sum-1)/k+1)*k+sum;
// cout<<"r:"<<r<<endl;
while(now<=m&&p[now]<=r)
{
sum++;
now++;
}
ans++;
}
printf("%d\n",ans);
return 0;
}
|
1190
|
B
|
Tokitsukaze, CSL and Stone Game
|
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are $n$ piles of stones, the $i$-th pile of which has $a_i$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: $n=3$ and sizes of piles are $a_1=2$, $a_2=3$, $a_3=0$. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be $[1, 3, 0]$ and it is a good move. But if she chooses the second pile then the state will be $[2, 2, 0]$ and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
|
Unless the first player must lose after the first move, the numbers of stones in these piles should form a permutation obtained from $0$ to $(n - 1)$ in the end, in order to ensure that there are no two piles include the same number of stones. Let's use $cnt[x]$ to represent the number of piles which have exactly $x$ stones in the beginning. There are four cases that Tokitsukaze will lose after the first move: $cnt[0] > 1$; $cnt[x] > 2$ for some $x$; $cnt[x] > 1$ and $cnt[y] > 1$ for some $x$, $y$ ($x \neq y$); $cnt[x] > 1$ and $cnt[x - 1] > 0$ for some $x$. If Tokitsukaze won't lose after the first move, then we only need to check the parity of the total number of stones that can be taken. By the way, if you don't want to discuss the above four cases, you can just enumerate her first move.
|
[
"games"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = (int)1e5 + 1;
int n, a[maxn], c[3];
void update(int x, int d) {
static map<int, int> ctr;
int &v = ctr[x];
--c[min(v, 2)];
v += d;
++c[min(v, 2)];
}
int main() {
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d", a + i);
update(a[i], 1);
}
bool chk = 0;
for(int i = 0; !chk && i < n; ++i)
if(a[i]) {
update(a[i], -1);
update(a[i] - 1, 1);
chk |= !c[2];
update(a[i] - 1, -1);
update(a[i], 1);
}
if(chk) {
chk = 0;
for(int i = 0; i < n; ++i)
chk ^= (a[i] + i) & 1;
}
puts(chk ? "sjfnb" : "cslnb");
return 0;
}
|
1190
|
C
|
Tokitsukaze and Duel
|
"Duel!"
Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.
There are $n$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly $k$ consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these $n$ cards face the same direction after one's move, the one who takes this move will win.
Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes.
|
If a player can make a move from a situation to that situation again, this player will not lose. Except for some initial situations, one can move from almost every situation to itself. Based on these two conclusions, we can get a solution. If Tokitsukaze cannot win after her first move, she cannot win in the future. In this case, we can quickly check if $k$ is so limited that she cannot win. After her first move, it is possible that Quailty wins in the next move. If he cannot, in order to prevent failure, he can just leave the situation to his opponent by doing useless flipping and thus result in a draw. Therefore, we can check if no matter how Tokitsukaze moves, Quailty has no chance to win after his first move. It can be easily checked linearly if we do some precalculation and enumerate Tokitsukaze's first move. Alternatively, we can find and check the pattern of initial situations in which Quailty can win.
|
[
"brute force",
"games",
"greedy"
] | 2,300
|
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1000005;
int n,k,T;
int a[MAXN],sum[MAXN];
int q_sum(int l,int r)
{
if(l>r)return 0;
return sum[r]-sum[l-1];
}
bool check_fir()
{
for(int i=1;i+k-1<=n;++i)
{
int lala=q_sum(1,i-1)+q_sum(i+k,n);
if(lala==0||lala+k==n)return true;
}
return false;
}
bool check_sec()
{
if(k*2<n||k==1)return false;
int len=n-k-1;
for(int i=2;i<=len;++i)
{
if(a[i]!=a[i-1]||a[n-i+1]!=a[n-i+2])return false;
}
if(a[len]==a[len+1]||a[n-len]==a[n-len+1]||a[1]==a[n])return false;
return true;
}
int main()
{
scanf("%d %d",&n,&k);
for(int i=1;i<=n;++i)
{
scanf("%1d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
if(check_fir())
{
printf("tokitsukaze\n");
}
else
{
if(check_sec())
{
printf("quailty\n");
}
else
{
printf("once again\n");
}
}
return 0;
}
|
1190
|
D
|
Tokitsukaze and Strange Rectangle
|
There are $n$ points on the plane, the $i$-th of which is at $(x_i, y_i)$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.
The strange area is enclosed by three lines, $x = l$, $y = a$ and $x = r$, as its left side, its bottom side and its right side respectively, where $l$, $r$ and $a$ can be any real numbers satisfying that $l < r$. The upper side of the area is boundless, which you can regard as a line parallel to the $x$-axis at infinity. The following figure shows a strange rectangular area.
A point $(x_i, y_i)$ is in the strange rectangular area if and only if $l < x_i < r$ and $y_i > a$. For example, in the above figure, $p_1$ is in the area while $p_2$ is not.
Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.
|
For each strange rectangular area and its corresponding set of points, we only need to focus on the lowest $y$-coordinate $yB$, the leftmost $x$-coordinate $xL$ and the rightmost $x$-coordinate $xR$ of points in this set. Different sets must have different $yB$, $xL$, $xR$, so we can count them by enumerating these values. Let's enumerate $yB$ first. Then, we need to list all the possible $x$-coordinates of points $(x_i, y_i)$ satisfying that $y_i \geq yB$ and mark every possible $x'$ satisfying there is a point $(x', yB)$. By doing so, we can make sure when enumerating $xL$ and $xR$, the requirement for $yB$ is met as well. However, enumerating forcibly, which is in time complexity $\mathcal{O}(n^3)$, is too slow to pass, so let's optimize the enumeration step by step. Let's pick and sort the points $(x'_1, yB), (x'_2, yB), \ldots, (x'_m, yB)$ from left to right. Assuming that $x'_0 = 0$, and $(x'_j, yB)$ is the leftmost point of them that is in the chosen set, we can count the number of aforementioned different $x$-coordinates in ranges $[x'_{j - 1} + 1, x'_j]$ and $[x'_j, \infty)$ and then count the number of possible pairs $(xL, xR)$ immediately. More specifically, let $cnt(l, r)$ be the number of different $x$-coordinates of points in the area $\lbrace (x, y) | l \leq x \leq r, y \geq yB \rbrace$, and we know the number of possible pairs $(xL, xR)$ is $cnt(x'_{j - 1} + 1, x'_j) \cdot cnt(x'_j, \infty)$. After precalculating $c(1, x)$ for each $yB$, we can reduce the time complexity into $\mathcal{O}(n^2)$. The very last step is using the trick of sweeping lines. We can enumerate $yB$ from highest to lowest, and during that process, use data structures to maintain possible $x$-coordinates. What we need to implement is to maintain a container, check if a coordinate is already in the container, add a coordinate to the container, and query the number of coordinates in a range. These requirements can be easily achieved by Fenwick tree, segment tree or others. With the last optimization, we can solve in time complexity $\mathcal{O}(n \log n)$. By the way, there also exist solutions using other approaches, such as divide and conquer.
|
[
"data structures",
"divide and conquer",
"sortings",
"two pointers"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
//priority_queue<int> q;
//priority_queue<int,vector<int>, greater<int> > q;
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> less_rbtree;
typedef tree<int, null_type, greater<int>, rb_tree_tag, tree_order_statistics_node_update> greater_rbtree;
typedef tree<pair<int,int>, null_type, less<pair<int,int> >, rb_tree_tag, tree_order_statistics_node_update> multi_less_rbtree;
typedef tree<pair<int,int>, null_type, greater<pair<int,int> >, rb_tree_tag, tree_order_statistics_node_update> multi_greater_rbtree;
const int MAXN=300005;
less_rbtree div_tree;
long long ans;
struct node
{
int x,y;
}p[MAXN],temp[MAXN];
int n;
bool cmp1(const node & A,const node & B)
{
return A.x<B.x;
}
bool cmp2(const node & A,const node & B)
{
if(A.y!=B.y)return A.y>B.y;
return A.x<B.x;
}
void div_algorithm(int l,int r)
{
if(l>r)return;
div_tree.clear();
for(int i=l;i<=r;++i)
{
temp[i]=p[i];
}
int mid_line=p[(l+r)>>1].x;
long long preans=ans;
int lpos=-1,rpos=-1;
sort(temp+l,temp+r+1,cmp2);
for(int i=l;i<=r;++i)
{
div_tree.insert(temp[i].x);
if(temp[i].x<=mid_line)
{
if(lpos==-1||lpos<temp[i].x)
{
lpos=temp[i].x;
}
}
if(temp[i].x>=mid_line)
{
if(rpos==-1||rpos>temp[i].x)
{
rpos=temp[i].x;
}
}
if(i==r||temp[i+1].y!=temp[i].y)
{
long long lsum=div_tree.order_of_key(lpos+1);
long long Lsum=div_tree.order_of_key(mid_line+1);
long long rsum=div_tree.size()-div_tree.order_of_key(rpos);
long long Rsum=div_tree.size()-div_tree.order_of_key(mid_line);
if(lpos==-1)
{
ans+=Lsum*rsum;
}
else if(rpos==-1)
{
ans+=lsum*Rsum;
}
else
{
ans+=lsum*Rsum+Lsum*rsum-lsum*rsum;
}
lpos=-1;
rpos=-1;
}
}
int pin1=l,pin2=r;
while(p[pin1].x!=mid_line)++pin1;
while(p[pin2].x!=mid_line)--pin2;
div_algorithm(l,pin1-1);
div_algorithm(pin2+1,r);
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%d %d",&p[i].x,&p[i].y);
}
sort(p+1,p+1+n,cmp1);
div_algorithm(1,n);
printf("%I64d\n",ans);
return 0;
}
|
1190
|
E
|
Tokitsukaze and Explosion
|
Tokitsukaze and her friends are trying to infiltrate a secret base built by Claris. However, Claris has been aware of that and set a bomb which is going to explode in a minute. Although they try to escape, they have no place to go after they find that the door has been locked.
At this very moment, CJB, Father of Tokitsukaze comes. With his magical power given by Ereshkigal, the goddess of the underworld, CJB is able to set $m$ barriers to protect them from the explosion. Formally, let's build a Cartesian coordinate system on the plane and assume the bomb is at $O(0, 0)$. There are $n$ persons in Tokitsukaze's crew, the $i$-th one of whom is at $P_i(X_i, Y_i)$. Every barrier can be considered as a line with infinity length and they can intersect each other. For every person from Tokitsukaze's crew, there must be at least one barrier separating the bomb and him, which means the line between the bomb and him intersects with at least one barrier. In this definition, if there exists a person standing at the position of the bomb, any line through $O(0, 0)$ will satisfy the requirement.
Although CJB is very powerful, he still wants his barriers to be as far from the bomb as possible, in order to conserve his energy. Please help him calculate the maximum distance between the bomb and the closest barrier while all of Tokitsukaze's crew are safe.
|
It is obvious that we can binary search the answer because we can pull any line closer to $O$ and the situation won't change. Applying a binary search, we focus on if it is possible to set $m$ barriers with the same distance to $O$ and meet the requirement. By doing so, we can draw a circle whose center is $O$ such that the closest point to $O$ on each barrier is on the circumference. Then it becomes a classic problem - for each barrier we can get the angle range of its closest point on the circle, and we have to choose at most $m$ points on the circle to ensure that there is at least one point within each range. This kind of greedy trick is very simple on a sequence. As to ranges on a sequence, you only have to sort all ranges in increasing order of left endpoint and take every necessary right endpoint. As to ranges on a circle, you can enumerate a position to break the circle into a sequence. But if you enumerate as the same way on the sequence, the time complexity will be $\mathcal{O}(n^2)$ which is not enough. Instead, we can double and extend these ranges into $2 n$ ranges and then regard them as on a sequence. We can do some precalculation, such as if we want to choose a point to cover the $i$-th sorted range and other ranges in its right as many as possible, what is the next range that we cannot cover. Let's denote that as $f[i][0]$, and then we can calculate the next range after $2^p$ repeated steps from the $i$-th range as $f[i][p]$, which can be obtained from $f[f[i][p - 1]][p - 1]$. After preparation, we can enumerate the beginning position and use binary lifting method, each time in complexity $\mathcal{O}(\log m)$, to know that whether we can use $m$ steps to cover all the ranges. Therefore, the total time complexity can be $\mathcal{O}(n \log m \log D)$, where $D$ is the precision requirement.
|
[
"binary search",
"greedy"
] | 3,100
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double db;
const int MAXN=100005;
const int DEP=18;
vector<pair<int,int> > filter(int n,vector<pair<int,int> > &seg)
{
vector<pair<int,int> > now;
for(auto &t:seg)
{
t.second=(t.second+n-1)%n;
int l=t.first,r=t.second;
if(l<=r)
{
now.push_back(make_pair(l,-r));
now.push_back(make_pair(l+n,-(r+n)));
}
else now.push_back(make_pair(l,-(r+n)));
}
sort(now.begin(),now.end());
vector<pair<int,int> > stk;
for(auto &t:now)
{
while(!stk.empty() && stk.back().second<=t.second)
stk.pop_back();
stk.push_back(t);
}
vector<pair<int,int> > res;
for(auto &t:stk)if(t.first<n)
res.push_back(make_pair(t.first,-t.second));
return res;
}
int go[MAXN<<1][DEP];
int cal(int n,vector<pair<int,int> > &seg)
{
seg=filter(n,seg);
int m=(int)seg.size();
if(m<2)return m;
for(int i=0;i<m;i++)
{
int l=seg[i].first,r=seg[i].second;
seg.push_back(make_pair(l+n,r+n));
}
for(int i=0;i<2*m;i++)
go[i][0]=lower_bound(seg.begin(),seg.end(),make_pair(seg[i].second+1,0))-seg.begin();
go[2*m][0]=2*m;
for(int j=1;j<DEP;j++)
for(int i=0;i<=2*m;i++)
go[i][j]=go[go[i][j-1]][j-1];
int res=m;
for(int i=0;i<m;i++)
{
int t=i,cnt=0;
for(int j=DEP-1;j>=0;j--)
if(go[t][j]<i+m)
t=go[t][j],cnt+=(1<<j);
if(res>cnt+1)res=cnt+1;
}
return res;
}
const db PI=acos(-1.0);
ll x[MAXN],y[MAXN];
db dis[MAXN],ang[MAXN],angl[MAXN],angr[MAXN],anga[MAXN<<1];
bool check(int n,int m,db r)
{
for(int i=0;i<n;i++)
{
db t=acos(min(1.0L,r/dis[i]));
angl[i]=ang[i]-t,angr[i]=ang[i]+t;
if(angl[i]<0)angl[i]+=2*PI;
if(angr[i]>=2*PI)angr[i]-=2*PI;
anga[i<<1]=angl[i],anga[i<<1|1]=angr[i];
}
sort(anga,anga+2*n);
int k=unique(anga,anga+2*n)-anga;
vector<pair<int,int> > seg;
for(int i=0;i<n;i++)
{
int l=lower_bound(anga,anga+k,angl[i])-anga;
int r=lower_bound(anga,anga+k,angr[i])-anga;
seg.push_back({l,r});
}
return cal(k,seg)<=m;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%lld%lld",&x[i],&y[i]);
db md=1e7;
for(int i=0;i<n;i++)
{
dis[i]=sqrtl(x[i]*x[i]+y[i]*y[i]);
ang[i]=atan2(y[i],x[i]);
if(ang[i]<0)ang[i]+=2*PI;
md=min(md,dis[i]);
}
if(md<1e-7)return 0*printf("%.12Lf\n",0.0L);
db tl=0,tr=1;
while(tr<md && check(n,m,tr))
tl=tr,tr=min(md,2*tr);
for(int _=0;_<25;_++)
{
db tm=(tl+tr)/2;
if(check(n,m,tm))tl=tm;
else tr=tm;
}
return 0*printf("%.12Lf\n",(tl+tr)/2);
}
|
1190
|
F
|
Tokitsukaze and Powers
|
Tokitsukaze is playing a room escape game designed by SkywalkerT. In this game, she needs to find out hidden clues in the room to reveal a way to escape.
After a while, she realizes that the only way to run away is to open the digital door lock since she accidentally went into a secret compartment and found some clues, which can be interpreted as:
- Only when you enter $n$ possible different passwords can you open the door;
- Passwords must be integers ranged from $0$ to $(m - 1)$;
- A password cannot be $x$ ($0 \leq x < m$) if $x$ and $m$ are not \textbf{coprime} (i.e. $x$ and $m$ have some common divisor greater than $1$);
- A password cannot be $x$ ($0 \leq x < m$) if there exist \textbf{non-negative} integers $e$ and $k$ such that $p^e = k m + x$, where $p$ is a secret integer;
- Any integer that doesn't break the above rules can be a password;
- Several integers are hidden in the room, but only one of them can be $p$.
Fortunately, she finds that $n$ and $m$ are recorded in the lock. However, what makes Tokitsukaze frustrated is that she doesn't do well in math. Now that she has found an integer that is suspected to be $p$, she wants you to help her find out $n$ possible passwords, or determine the integer cannot be $p$.
|
Firstly, let me briefly review this problem for you. Given integers $n$, $m$ and $p$ ($n > 0$, $m > 1$, $p \neq 0$), we denote $S = \lbrace x | x \in \mathbb{Z}, 0 \leq x < m, \gcd(m, x) = 1 \rbrace$ and $T = \lbrace p^e \bmod m | e \in \mathbb{Z}, e \geq 0 \rbrace$, where $\gcd(m, x)$ means the greatest common divisor of $m$ and $x$, and you are asked to pick up $n$ distinct integers from $(S - T)$, the set of elements in $S$ but not in $T$, or report that it is unachievable. Besides, there is an additional restriction, $m = q^k$ for a prime number $q$ and a positive integer $k$. It is not difficult to show $|S|$, the size of $S$, equals to $\varphi(m) = m (1 - \frac{1}{q})$. When $\gcd(m, p) > 1$, there is only one element $p^0 \bmod m = 1$ in $T$ which is coprime to $m$, so in that case, $|S - T| = \varphi(m) - 1$. To output a solution, you can just enumerate the smallest integers and skip the integer $1$ and any multiples of $q$. In this process, you won't need to enumerate more than $(2 n + 1)$ integers, because $\frac{n}{1 - \frac{1}{q}} + 1 \leq 2 n + 1$. When $\gcd(m, p) = 1$, we can observe that $T \subseteq S$. Let $|T|$ be $\lambda$, and we may conclude from Euler's totient theorem that $\lambda \leq \varphi(m)$, and even $\lambda | \varphi(m)$. When $n > \varphi(m) - \lambda$, there is no solution, so we need to calculate $\lambda$ in order to determine the existence of solutions. To calculate $\lambda$, you can just enumerate all the divisors of $\varphi(m)$ and check them using Fast Power Algorithm, because the number of divisors is not too large due to the restrictions. Alternatively, you can do it more advanced and check more efficiently like the following. The above approach requires $\mathcal{O}(\log \varphi(m))$ calls of Fast Power Algorithm. It is used more regularly when searching a random primitive root in modulo some integer. When implementing Fast Power Algorithm, you may notice an issue that the modular multiplication may not be easy to code, when the 128-bit integer operations are not directly provided on this platform. In a precise way, you can implement another like Fast Multiplying Algorithm, though it is a bit slow. But if you believe you are lucky enough and you prefer using C/C++, you can try the following code in a convenient way. No matter what approach you used, the factorization of $(q - 1)$ is inevitable, so the problem requires you to factorize a relatively large number (less than $10^{18}$) a bit quickly. For example, you can use Pollard's Rho Algorithm with Miller-Rabin Primality Test. By Birthday Paradox, which is a heuristic claim, when $x$ is not a prime, Pollard's Rho Algorithm can split $x$ into $u \cdot v$ in $\mathcal{O}(\sqrt{\min(u, v)}) = \mathcal{O}(x^{1 / 4})$ iterations. By the way, you can obtain $q$ from $m$ by enumerating possible $k$ from large to small, instead of factorization. Let's go back to the case that $\gcd(m, p) = 1$ and $n \leq \varphi(m) - \lambda$. When any solution exists, we can observe that $\varphi(m) - \lambda \geq \frac{\varphi(m)}{2}$, so there may exist some solutions based on random distribution. That is, if you are able to check whether an integer is in $T$ or not, you can roughly pick $2 n$ integers in $S$ and check them. One approach is like the mechanism built in the problem checker, but as space is limited, I would not expend it at here. One thing you should be aware of is that you can't pick them without checking, as the probability of failure may be so large, like $\frac{1}{2}$. Moreover, you can't use Baby-Step-Giant-Step algorithm since its time complexity $\mathcal{O}(\sqrt{n m})$ is too slow. If there exists at least one primitive root in modulo $m$, then we can construct the output integers. Since a primitive root $g$ can represent $S$ as $\lbrace g^e \bmod m | e \in \mathbb{Z}, 0 \leq e < \varphi(m) \rbrace$, we can reduce the problem into something about modular equation that only concerns the exponents. As the number of primitive root in modulo $m$ is $\varphi(\varphi(m))$, if the root exists, we can get a random primitive root easily. Now let's assume we find a primitive root $g$ and $p \equiv g^u \pmod{m}$. An integer $(g^v \bmod m)$ is in $T$ if and only if the equation $e u \equiv v \pmod{\varphi(m)}$ has a solution of $e$. It is easy to show, when $\gcd(\varphi(m), u) | v$, a solution of $e$ always exists, so the construction is quite straightforward. The only case we left is when no primitive root exists in modulo $m$, which occurs when $m = 2^k$, $k \geq 3$. In this case, we cannot represent all the elements in $S$ as non-negative integer powers of one specific number, but we can find a pseudo-primitive root $g'$ to use its powers to represent all the elements in the form of $(4 t + 1)$ in $S$ (as the group $(S, \times_m)$, also known as $(\mathbb{Z}/m\mathbb{Z})^{\times}$, is isomorphic to a direct product of cyclic groups, $\mathrm{C}_2 \times \mathrm{C}_{2^{k - 2}}$). Besides, $\lbrace m - ({g'}^{e} \bmod m) | e \in \mathbb{Z}, 0 \leq e < 2^{k - 2} \rbrace$ can represent the rest numbers (in the form of $(4 t + 3)$) in $S$. As the product of two integers in the form of $(4 t + 3)$ is in the form of $(4 t + 1)$, we can discuss the parity of $e$ in expression $(p^e \bmod m)$ and check if an integer is in $T$, so the construction could work after a little modification. By the way, there exist many different construction methods for this case. In summary, to solve this problem, we need to factorize $\varphi(m)$, calculate the order of $p$ in modulo $m$, find a primitive root $g$ (or a pseudo-primitive root $g'$) in modulo $m$ and enumerate some small integers (values or exponents) to construct a solution. Time complexity: $\mathcal{O}((m^{1 / 4} + n) M(m))$, where $M(m)$ means the cost of one multiplication modulo $m$. Some slow solutions are accepted as well.
|
[
"number theory",
"probabilities"
] | 3,400
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
inline ll mul_mod(ll a, ll b, ll m)
{
a=(a%m+m)%m,b=(b%m+m)%m;
return ((a*b-(ll)(1.0L*a/m*b+0.5L)*m)%m+m)%m;
}
inline ll pow_mod(ll a,ll k,ll m)
{
ll res=1;
while(k)
{
if(k&1)res=mul_mod(res,a,m);
a=mul_mod(a,a,m);
k>>=1;
}
return res;
}
bool strong_pseudo_primetest(ll n,int b)
{
ll n2=n-1,res;
int s=0;
while(n2%2==0)n2>>=1,s++;
res=pow_mod(b,n2,n);
if((res==1)|| (res==n-1))return 1;
s--;
while(s>=0)
{
res=mul_mod(res,res,n);
if(res==n-1)return 1;
s--;
}
return 0;
}
bool is_prime(ll n)
{
static ll testNum[]={2,3,5,7,11,13,17,19,23,29,31,37};
static ll lim[]={4,0,1373653LL,25326001LL,25000000000LL,2152302898747LL,3474749660383LL,341550071728321LL,0,0,0,0};
if(n<2 || n==3215031751LL)return 0;
for(int i=0;i<12;i++)
{
if(n<lim[i])return 1;
if(!strong_pseudo_primetest(n,testNum[i]))return 0;
}
return 1;
}
inline ll func(ll x,ll n)
{
return (mul_mod(x,x,n)+1)%n;
}
ll pollard(ll n)
{
if(is_prime(n))return n;
if(~n&1)return 2;
for(int i=1;i<20;i++)
{
ll x=i,y=func(x,n),p=__gcd(y-x,n);
while(p==1)x=func(x,n),y=func(func(y,n),n),p=__gcd((y-x+n)%n,n)%n;
if(p==0 || p==n)continue;
return p;
}
return 1;
}
vector<ll> factor(ll n)
{
if(n==1)return {};
ll x=pollard(n);
if(x==n)return {n};
vector<ll> res=factor(x);
vector<ll> t=factor(n/x);
res.insert(res.end(),t.begin(),t.end());
return res;
}
vector<ll> solve_easy(int n,ll m)
{
vector<ll> res;
for(ll i=2;i<m && (int)res.size()<n;i++)
if(__gcd(i,m)==1)res.push_back(i);
return res;
}
bool dfs_sol(int i,int k,ull x,ull p,ull t)
{
if(i>k)return 1;
ull mask=(1ULL<<i)-1;
if((t&mask)==(x&mask) && dfs_sol(i+1,k,x,p*p,t))return 1;
if(((t*p)&mask)==(x&mask) && dfs_sol(i+1,k,x,p*p,t*p))return 1;
return 0;
}
vector<ll> solve_even(int n,ll m,ll p,int k)///m=2^k
{
vector<ll> res;
for(ll i=3;i<m && (int)res.size()<n;i+=2)
if(!dfs_sol(3,k,i,p,1))res.push_back(i);
return res;
}
void dfs_fac(int dep,ll val,vector<pair<ll,int> > &pcnt,vector<ll> &fac)
{
if(dep==(int)pcnt.size())
{
fac.push_back(val);
return;
}
for(int i=0;i<=pcnt[dep].second;i++)
{
dfs_fac(dep+1,val,pcnt,fac);
val*=pcnt[dep].first;
}
}
vector<ll> solve_root(int n,ll m,ll p,vector<ll> pm)
{
ll phi=m/pm[0]*(pm[0]-1);
vector<ll> pphi=factor(phi);
sort(pphi.begin(),pphi.end());
vector<pair<ll,int> > pcnt;
for(int i=0,j=0;i<(int)pphi.size();i=j)
{
while(j<(int)pphi.size() && pphi[i]==pphi[j])j++;
pcnt.push_back({pphi[i],j-i});
}
pphi.erase(unique(pphi.begin(),pphi.end()),pphi.end());
vector<ll> fac;
dfs_fac(0,1,pcnt,fac);
ll pmr=0;
while(++pmr)
{
bool isok=(__gcd(pmr,m)==1);
for(int i=0;i<(int)pphi.size() && isok;i++)
isok&=(pow_mod(pmr,phi/pphi[i],m)>1);
if(isok)break;
}
ll len=phi;
for(auto &t:fac)
if(pow_mod(p,t,m)==1)
len=min(len,t);
if(len==phi)return {};
vector<ll> res;
for(ll i=0;i<phi && (int)res.size()<n;i++)
if(i%(phi/len))res.push_back(pow_mod(pmr,i,m));
return res;
}
int main()
{
int n;
ll m,p;
scanf("%d%lld%lld",&n,&m,&p);
vector<ll> res;
if(__gcd(m,p)>1)
res=solve_easy(n,m);
else
{
vector<ll> pm=factor(m);
if(pm[0]==2 && (int)pm.size()>2)
res=solve_even(n,m,p,(int)pm.size());
else
res=solve_root(n,m,p,pm);
}
if((int)res.size()<n)
printf("-1\n");
else for(int i=0;i<n;i++)
printf("%lld%c",res[i]," \n"[i==n-1]);
return 0;
}
|
1191
|
A
|
Tokitsukaze and Enhancement
|
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP.
In general, different values of HP are grouped into $4$ categories:
- Category $A$ if HP is in the form of $(4 n + 1)$, that is, when divided by $4$, the remainder is $1$;
- Category $B$ if HP is in the form of $(4 n + 3)$, that is, when divided by $4$, the remainder is $3$;
- Category $C$ if HP is in the form of $(4 n + 2)$, that is, when divided by $4$, the remainder is $2$;
- Category $D$ if HP is in the form of $4 n$, that is, when divided by $4$, the remainder is $0$.
The above-mentioned $n$ can be any integer.
These $4$ categories ordered from highest to lowest as $A > B > C > D$, which means category $A$ is the highest and category $D$ is the lowest.
While playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most $2$ (that is, either by $0$, $1$ or $2$). How much should she increase her HP so that it has the highest possible category?
|
Just enumerating the increment can pass. However, by increasing at most $2$ points, the value of her HP can always become an odd number, and thus the highest possible level is either $A$ or $B$. We can just solve case by case.
|
[
"brute force"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x;
cin>>x;
if(x%4==0) puts("1 A");
else if(x%4==1) puts("0 A");
else if(x%4==2) puts("1 B");
else if(x%4==3) puts("2 A");
return 0;
}
|
1191
|
B
|
Tokitsukaze and Mahjong
|
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (\textbf{manzu}, \textbf{pinzu} or \textbf{souzu}) and a number (a digit ranged from $1$ to $9$). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, $\ldots$, 9m, 1p, 2p, $\ldots$, 9p, 1s, 2s, $\ldots$, 9s.
In order to win the game, she must have at least one \textbf{mentsu} (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
- A \textbf{mentsu}, also known as meld, is formed by a \textbf{koutsu} or a \textbf{shuntsu};
- A \textbf{koutsu}, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a \textbf{koutsu};
- A \textbf{shuntsu}, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a \textbf{shuntsu}.
Some examples:
- [2m, 3p, 2s, 4m, 1s, 2s, 4s] — it contains no \textbf{koutsu} or \textbf{shuntsu}, so it includes no \textbf{mentsu};
- [4s, 3m, 3p, 4s, 5p, 4s, 5p] — it contains a \textbf{koutsu}, [4s, 4s, 4s], but no \textbf{shuntsu}, so it includes a \textbf{mentsu};
- [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] — it contains no \textbf{koutsu} but a \textbf{shuntsu}, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a \textbf{mentsu}.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
|
There are only two types of mentsus, so you can enumerate the mentsu you want her to form, and check the difference between that and those currently in her hand. Alternatively, you can find out that the answer is at most $2$, since she can draw two extra identical tiles which are the same as one of those in her hand. You may enumerate at most $1$ extra tile for her and check if it can contribute to a mentsu. If she can't, the answer will be $2$.
|
[
"brute force",
"implementation"
] | 1,200
|
//#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;
//defines
typedef long long ll;
typedef long double ld;
#define TIME clock() * 1.0 / CLOCKS_PER_SEC
#define prev _prev
#define y0 y00
//permanent constants
const ld pi = acos(-1.0);
const int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int digarr[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
const int dxo[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
const int dyo[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
const int alf = 26;
const int dig = 10;
const int two = 2;
const int th = 3;
const ll prost = 239;
const ll bt = 30;
const ld eps = 1e-7;
const ll INF = (ll)(1e18 + 239);
const int BIG = (int)(1e9 + 239);
const int MOD = 998244353;
const ll MOD2 = (ll)MOD * (ll)MOD;
//random
mt19937 rnd(239); //(chrono::high_resolution_clock::now().time_since_epoch().count());
//constants
const int M = (int)(2e5 + 239);
const int N = (int)(2e3 + 239);
const int L = 20;
const int T = (1 << 20);
const int B = (int)sqrt(M);
const int X = 1e4 + 239;
bool check(string a, string b, string c)
{
if (a == b && b == c) return true;
if (a > b) swap(a, b);
if (b > c) swap(b, c);
if (a > b) swap(a, b);
if (a[1] == b[1] && b[1] == c[1])
{
if (a[0] + 1 == b[0] && b[0] + 1 == c[0])
return true;
}
return false;
}
int32_t main()
{
#ifdef ONPC
freopen("input.txt", "r", stdin);
#endif
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
string a, b, c;
cin >> a >> b >> c;
if (check(a, b, c))
{
cout << "0";
return 0;
}
vector<string> var;
for (int i = 1; i <= 9; i++)
{
string s = "";
s += (char)(i + '0');
var.push_back(s + "m");
var.push_back(s + "p");
var.push_back(s + "s");
}
for (string s : var)
{
if (check(s, a, b))
{
cout << "1";
return 0;
}
if (check(s, a, c))
{
cout << "1";
return 0;
}
if (check(s, b, c))
{
cout << "1";
return 0;
}
}
cout << "2";
return 0;
}
|
1194
|
A
|
Remove a Progression
|
You have a list of numbers from $1$ to $n$ written from left to right on the blackboard.
You perform an algorithm consisting of several steps (steps are $1$-indexed). On the $i$-th step you wipe the $i$-th number (considering only \textbf{remaining} numbers). You wipe the whole number (not one digit).
When there are less than $i$ numbers remaining, you stop your algorithm.
Now you wonder: what is the value of the $x$-th remaining number after the algorithm is stopped?
|
After some simulation of the given algorithm (in your head, on paper or on a computer) we can realize that exactly all odd numbers are erased. So, all even numbers remain, and the answer is $2x$.
|
[
"math"
] | 800
|
fun main(args: Array<String>) {
val T = readLine()!!.toInt()
for (t in 1..T) {
val (n, x) = readLine()!!.split(' ').map { it.toLong() }
println(x * 2)
}
}
|
1194
|
B
|
Yet Another Crosses Problem
|
You are given a picture consisting of $n$ rows and $m$ columns. Rows are numbered from $1$ to $n$ from the top to the bottom, columns are numbered from $1$ to $m$ from the left to the right. Each cell is painted either black or white.
You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $x$ and $y$, where $1 \le x \le n$ and $1 \le y \le m$, such that \textbf{all cells} in row $x$ and \textbf{all cells} in column $y$ are painted black.
For examples, each of these pictures contain crosses:
The fourth picture contains 4 crosses: at $(1, 3)$, $(1, 5)$, $(3, 3)$ and $(3, 5)$.
Following images don't contain crosses:
You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.
What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?
You are also asked to answer multiple independent queries.
|
Let's consider each cell as a center of a cross and take the fastest one to paint. Calculating each time naively will take $O(nm(n + m))$ overall, which is too slow. Notice how the answer for some cell $(x, y)$ can be represented as $cnt_{row}[x] + cnt_{column}[y] -$ ($1$ if $a[x][y]$ is white else $0$), where $cnt_{row}[i]$ is the number of white cells in row $i$ and $cnt_{column}[i]$ is the same for column $i$. The first two terms can be precalculated beforehand. Overall complexity: $O(nm)$ per query.
|
[
"implementation"
] | 1,300
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int q;
cin >> q;
forn(_, q){
int n, m;
cin >> n >> m;
vector<string> s(n);
forn(i, n)
cin >> s[i];
vector<int> cntn(n), cntm(m);
forn(i, n) forn(j, m){
cntn[i] += (s[i][j] == '.');
cntm[j] += (s[i][j] == '.');
}
int ans = n + m;
forn(i, n) forn(j, m){
ans = min(ans, cntn[i] + cntm[j] - (s[i][j] == '.'));
}
cout << ans << "\n";
}
return 0;
}
|
1194
|
C
|
From S To T
|
You are given three strings $s$, $t$ and $p$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose any character from $p$, erase it from $p$ and insert it into string $s$ (you may insert this character anywhere you want: in the beginning of $s$, in the end or between any two consecutive characters).
For example, if $p$ is aba, and $s$ is de, then the following outcomes are possible (the character we erase from $p$ and insert into $s$ is highlighted):
- \textbf{a}ba $\rightarrow$ ba, de $\rightarrow$ \textbf{a}de;
- \textbf{a}ba $\rightarrow$ ba, de $\rightarrow$ d\textbf{a}e;
- \textbf{a}ba $\rightarrow$ ba, de $\rightarrow$ de\textbf{a};
- a\textbf{b}a $\rightarrow$ aa, de $\rightarrow$ \textbf{b}de;
- a\textbf{b}a $\rightarrow$ aa, de $\rightarrow$ d\textbf{b}e;
- a\textbf{b}a $\rightarrow$ aa, de $\rightarrow$ de\textbf{b};
- ab\textbf{a} $\rightarrow$ ab, de $\rightarrow$ \textbf{a}de;
- ab\textbf{a} $\rightarrow$ ab, de $\rightarrow$ d\textbf{a}e;
- ab\textbf{a} $\rightarrow$ ab, de $\rightarrow$ de\textbf{a};
Your goal is to perform several (maybe zero) operations so that $s$ becomes equal to $t$. Please determine whether it is possible.
Note that you have to answer $q$ independent queries.
|
If the answer exists then each element of string $s$ matches with some element of string $t$. Thereby string $s$ must be a subsequence of string $t$. Let $f(str, a)$ equal to the number of occurrences of the letter $a$ in the string $str$. Then for any letter $a$ condition $f(s, a) + f(p, a) \ge f(t, a)$ must be hold. So the answer to the query is YES if following conditions hold: string $s$ is subsequence of string $t$; $f(s, a) + f(p, a) \ge f(t, a)$ for any Latin latter $a$.
|
[
"implementation",
"strings"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
int q;
string s, t, p;
int cnt[30];
int main() {
cin >> q;
for(int iq = 0; iq < q; ++iq){
cin >> s >> t >> p;
memset(cnt, 0, sizeof cnt);
for(auto x : p)
++cnt[x - 'a'];
bool ok = true;
int is = 0, it = 0;
while(is < s.size()){
if(it == t.size()){
ok = false;
break;
}
if(s[is] == t[it]){
++is, ++it;
continue;
}
--cnt[t[it] - 'a'];
++it;
}
while(it < t.size()){
--cnt[t[it] - 'a'];
++it;
}
if(*min_element(cnt, cnt + 30) < 0)
ok = false;
if(ok) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}
}
|
1194
|
D
|
1-2-K Game
|
Alice and Bob play a game. There is a paper strip which is divided into $n + 1$ cells numbered from left to right starting from $0$. There is a chip placed in the $n$-th cell (the last one).
Players take turns, Alice is first. Each player during his or her turn has to move the chip $1$, $2$ or $k$ cells to the left (so, if the chip is currently in the cell $i$, the player can move it into cell $i - 1$, $i - 2$ or $i - k$). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it $k$ cells to the left if the current cell has number $i < k$. The player who can't make a move loses the game.
Who wins if both participants play optimally?
Alice and Bob would like to play several games, so you should determine the winner in each game.
|
Let's determine for each cell whether it's winning or losing position (we can do it since the game is symmetric and doesn't depend on a player). The $0$-th cell is obviously losing, the $1$-st and $2$-nd ones is both winning, since we can move to the $0$-th cell and put our opponent in the losing position (here comes criterion: the position is winning if and only if there is a move to the losing position). If $k$ is large enough, then the $0$-th, $3$-rd, $6$-th, $9$-th... are losing. So here comes divisibility by $3$. If $k\not\equiv0\:\bmod3$ then this move doesn't change anything, since if $x\equiv0{\mathrm{~mod~}}3$ then $x-k\not\equiv0\mod3$ so it's not the move to the losing position, so $x$ doesn't become the winning one. Otherwise, if $k\equiv0{\mathrm{~mod~}}3$ then the $k$-th positions becomes winning, but the $(k + 1)$-th cell is losing (all moves are to $(k - 1)$-th, $k$-th or $1$-st cells and all of them are winning). The $(k + 2)$-th and $(k + 3)$-th cells are winning and so on. In the end, we came up with cycle of length $k + 1$ where position divisible by $3$ except $k$ are losing. All we need to do is small case work.
|
[
"games",
"math"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int n, k;
inline bool read() {
if(!(cin >> n >> k))
return false;
return true;
}
void solve() {
bool win = true;
if(k % 3 == 0) {
int np = n % (k + 1);
if(np % 3 == 0 && np != k)
win = false;
} else {
int np = n % 3;
if(np == 0)
win = false;
}
puts(win ? "Alice" : "Bob");
}
int main(){
int T; cin >> T;
while(T--) {
read();
solve();
}
return 0;
}
|
1194
|
E
|
Count The Rectangles
|
There are $n$ segments drawn on a plane; the $i$-th segment connects two points ($x_{i, 1}$, $y_{i, 1}$) and ($x_{i, 2}$, $y_{i, 2}$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $i \in [1, n]$ either $x_{i, 1} = x_{i, 2}$ or $y_{i, 1} = y_{i, 2}$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.
We say that four segments having indices $h_1$, $h_2$, $v_1$ and $v_2$ such that $h_1 < h_2$ and $v_1 < v_2$ form a rectangle if the following conditions hold:
- segments $h_1$ and $h_2$ are horizontal;
- segments $v_1$ and $v_2$ are vertical;
- segment $h_1$ intersects with segment $v_1$;
- segment $h_2$ intersects with segment $v_1$;
- segment $h_1$ intersects with segment $v_2$;
- segment $h_2$ intersects with segment $v_2$.
Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $h_1 < h_2$ and $v_1 < v_2$ should hold.
|
Let's iterate over the lower horizontal segment. Denote its coordinates as ($xl, yh$) and ($xr, yh$), where $xl < xr$. We call vertical segment ($x_{i, 1}$, $y_{i, 1}$), ($x_{i, 2}$, $y_{i, 2}$) good, if followings conditions holds: $xl \le x_{i, 1} = x_{i, 2} \le xr$; $min(y_{i, 1}, y_{i, 2}) \le yh$. Now let's use the scanline method. At first, for each good vertical segment $i$ we increment the value of element in position $x_{i, 1}$ in some data structure (for example, Fenwick Tree). Next we will process two types of queries in order of increasing their y-coordinate: horizontal segments with coordinates ($x_{i, 1}$, $y_{i, 1}$), ($x_{i, 2}$, $y_{i, 2}$); upper point of some vertical segment with coordinates $(x_i, y_i)$. And if two events of different types have the same y-coordinate then the event of first type must be processed first. For event of first type we need to find sum on range $[x_{i, 1}, x_{i, 2}]$ ($x_{i, 1} < x_{i, 2}$) in our data structure. Let's denote this sum as $s$. Then we need to add $\frac{s (s - 1)}{2}$ to the answer (because we have $s$ vertical segments which intersect with both fixed horizontal segments and we can choose two of them in so many ways). For event of second type we just need decrement the value of element in position $x_i$ in our data structure.
|
[
"bitmasks",
"brute force",
"data structures",
"geometry",
"sortings"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
const int N = 10009;
const int INF = 1000000009;
int n;
vector <pair<int, int> > vs[N], hs[N];
int f[N];
vector <int> d[N];
void upd(int pos, int x){
for(; pos < N; pos |= pos + 1)
f[pos] += x;
}
int get(int pos){
int res = 0;
for(; pos >= 0; pos = (pos & (pos + 1)) - 1)
res += f[pos];
return res;
}
int get(int l, int r){
return get(r) - get(l - 1);
}
const int D = 5000;
int main() {
cin >> n;
for(int i = 0; i < n; ++i){
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
x1 += D, y1 += D, x2 += D, y2 += D;
if(y1 == y2)
hs[y1].push_back( mp(min(x1, x2), max(x1, x2)) );
else
vs[x1].push_back( mp(min(y1, y2), max(y1, y2)) );
}
long long res = 0;
for(int y = 0; y < N; ++y) for(auto s : hs[y]){
for(int i = 0; i < N; ++i) d[i].clear();
memset(f, 0, sizeof f);
int l = s.first, r = s.second;
for(int x = l; x <= r; ++x) for(auto s2 : vs[x])
if(s2.first <= y && s2.second > y) {
d[s2.second].push_back(x);
upd(x, 1);
}
for(int y2 = y + 1; y2 < N; ++y2){
for(auto s2 : hs[y2]){
int cur = get(s2.first, s2.second);
res += cur * (cur - 1) / 2;
}
for(auto x : d[y2]) upd(x, -1);
}
}
cout << res << endl;
return 0;
}
|
1194
|
F
|
Crossword Expert
|
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $T$ seconds after coming.
Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $n$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $t_i$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).
Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $t_i$ seconds or $t_i + 1$ seconds to solve the $i$-th crossword, equiprobably (with probability $\frac{1}{2}$ he solves the crossword in exactly $t_i$ seconds, and with probability $\frac{1}{2}$ he has to spend an additional second to finish the crossword). All these events are independent.
After $T$ seconds pass (or after solving the last crossword, if he manages to do it in less than $T$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $E$ — the expected number of crosswords he will be able to solve completely. Can you calculate it?
Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $E = \sum \limits_{i = 0}^{n} i p_i$, where $p_i$ is the probability that Adilbek will solve exactly $i$ crosswords.
We can represent $E$ as rational fraction $\frac{P}{Q}$ with $Q > 0$. To give the answer, you should print $P \cdot Q^{-1} \bmod (10^9 + 7)$.
|
Let's use (as usual) linearity of an expected value. $E = \sum\limits_{i = 1}^{n}{E(I(i))}$ where $I(i)$ is an indicator function and equal to $1$ iff Adilbek will be able to solve the $i$-th crossword. How to calculate $I(i)$? If $\sum\limits_{j = 1}^{i}{t_i} > T$ then $I(i)$ is always $0$. On the other hand, if $\sum\limits_{j = 1}^{i}{(t_i + 1)} = \sum\limits_{j = 1}^{i}{t_i} + i \le T$ - $I(i)$ is always $1$. Otherwise, we need to calculate $E(I(i)) = P(i)$ - the needed probability. To calculate $P(i)$ we can iterate over $k$ - the number of crosswords among first $i$ ones which will require extra time. Obviously, if $k > T - \sum\limits_{j = 1}^{i}{t_i}$ then we don't have enough time to solve the $i$-th crossword, also $k \le i$. Let's denote $m_i = \min(T - \sum\limits_{j = 1}^{i}{t_i}, i)$. There are $\binom{i}{k}$ ways to choose crosswords with extra time among all $2^i$ variants. So the final formula is following: $P(i) = \frac{1}{2^i}\sum\limits_{k = 0}^{m_i}{\binom{i}{k}}.$ The only problem is the efficiency. But we can find out several interesting properties. At first, $m_{i + 1} \le m_i + 1$. The other one: since $\binom{n}{k} + \binom{n}{k + 1} = \binom{n + 1}{k + 1}$, then $2 \cdot \sum\limits_{k = 0}^{x}{\binom{n}{k}} + \binom{n}{x + 1} = \sum\limits_{k = 0}^{x + 1}{\binom{n + 1}{k}}$. And this exactly the efficient way to transform $P(i) \cdot 2^i$ to $P(i + 1) \cdot 2^{i + 1}$: by multiplying and adding one coefficient we can transform the prefix sum of the $i$-th row to the prefix sum of the $i + 1$ row. And to reduce the length of the prefix sum we can just subtract unnecessary coefficients. In result, the total complexity is $O(n)$ (maybe with extra $\log$ factor because of modular arithmetic).
|
[
"combinatorics",
"dp",
"number theory",
"probabilities",
"two pointers"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
return out << "(" << p.x << ", " << p.y << ")";
}
template<class A> ostream& operator <<(ostream& out, const vector<A> &v) {
fore(i, 0, sz(v)) {
if(i) out << " ";
out << v[i];
}
return out;
}
const int MOD = int(1e9) + 7;
inline int norm(int a) {
if(a >= MOD) a -= MOD;
if(a < 0) a += MOD;
return a;
}
inline int mul(int a, int b) {
return int(a * 1ll * b % MOD);
}
inline int binPow(int a, int k) {
int ans = 1;
while(k > 0) {
if(k & 1) ans = mul(ans, a);
a = mul(a, a);
k >>= 1;
}
return ans;
}
inline int inv(int a) {
return binPow(a, MOD - 2);
}
int n;
li T;
vector<li> t;
inline bool read() {
if(!(cin >> n >> T))
return false;
t.resize(n);
fore(i, 0, n)
cin >> t[i];
return true;
}
vector<int> f, inf;
int C(int n, li k) {
if(k > n || k < 0)
return 0;
return mul(f[n], mul(inf[k], inf[n - k]));
}
inline void solve() {
f.resize(n + 5);
inf.resize(n + 5);
f[0] = inf[0] = 1;
fore(i, 1, sz(f)) {
f[i] = mul(i, f[i - 1]);
inf[i] = mul(inf[i - 1], inv(i));
}
int sumC = 1;
li bd = T;
int pw2 = 1, i2 = (MOD + 1) / 2;
vector<int> p(n + 1, 0);
fore(i, 0, n) {
pw2 = mul(pw2, i2);
sumC = norm(mul(2, sumC) - C(i, bd));
li need = t[i];
if(bd > i + 1) {
li sub = min(bd - i - 1, need);
bd -= sub, need -= sub;
}
li rem = min(bd + 1, need);
fore(k, 0, rem)
sumC = norm(sumC - C(i + 1, bd - k));
bd -= rem;
p[i] = mul(sumC, pw2);
}
int ans = int(accumulate(p.begin(), p.end(), 0ll) % MOD);
cout << ans << endl;
// cerr << mul(ans, binPow(2, n)) << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1194
|
G
|
Another Meme Problem
|
Let's call a fraction $\frac{x}{y}$ good if there exists at least one another fraction $\frac{x'}{y'}$ such that $\frac{x}{y} = \frac{x'}{y'}$, $1 \le x', y' \le 9$, the digit denoting $x'$ is contained in the decimal representation of $x$, and the digit denoting $y'$ is contained in the decimal representation of $y$. For example, $\frac{26}{13}$ is a good fraction, because $\frac{26}{13} = \frac{2}{1}$.
You are given an integer number $n$. Please calculate the number of good fractions $\frac{x}{y}$ such that $1 \le x \le n$ and $1 \le y \le n$. The answer may be really large, so print it modulo $998244353$.
|
Let's fix an irreducible fraction $\frac{X}{Y}$ such that $1 \le X, Y \le 9$. Obviously, each good fraction is equal to exactly one of such irreducible fractions. So if we iterate on $X$ and $Y$, check that $gcd(X, Y) = 1$ and find the number of good fractions that are equal to $\frac{X}{Y}$, we will solve the problem. Okay, suppose we fixed $X$ and $Y$. Any good fraction can be represented as $\frac{zX}{zY}$, where $z$ is some positive integer. Let's try all possible values of $z$, and for them check whether they correspond to a good fraction. How do we try all values of $z$ without iterating on them? Let's construct the decimal representation of $z$ from the least significant digit to the most. As soon as we fix $k$ least significant digits of $z$, we know $k$ least significant digits of $zX$ and $zY$. So let's try to use digit DP to try all possible values of $z$. Which states do we have to consider? Of course, we need to know the number of digits we already placed, so that will be the first state. After we placed $k$ digits, we know first $k$ digits of the numerator of the fraction; but to get the value of digit $k + 1$, knowing only the value of the corresponding digit in $z$ is not enough: there could be some value carried over after multiplying already placed digits by $X$. For example, if $X = 3$, and we placed the first digit of $z$ and it is $7$, we know that the first (least significant) digit of $zX$ is $1$, and we know that after fixing the second digit of $z$ we should add $2$ to it to get the value of this digit in $zX$, since $2$ is carried over from the first digit. So, the second state of DP should represent the number that is carried over from the previous digit in the numerator, and the third state should do the same for the denominator. Okay, in order to know whether the fraction is good, we have to keep track of some digits in the numerator and denominator. If $\frac{x'}{y'} = \frac{X}{Y}$, $1 \le x' \le 9$ and $1 \le y' \le 9$, then we have to keep track of the digit representing $x'$ in the numerator and the digit representing $y'$ in the denominator. So we have two additional states that represent the masks of "interesting" digits we met in the numerator and in the denominator. The only thing that's left to check is that both $zX$ and $zY$ are not greater than $n$. Let's construct the decimal representation of $n$ and prepend it with some leading zeroes; and keep constructing the numerator and the denominator until they have the same number of digits as the decimal representation as $n$. Then we can compare the representation of, for example, numerator with the representation of $n$ as strings. Comparing can be done with the following technique: let's keep a flag denoting whether the number represented by the least significant digits of the numerator is less or equal than the number represented by the same digits from $n$. When we place another digit of the numerator, we can get the new value of this flag as follows: if new digit of the numerator is not equal to the corresponding digit of $n$, then the value of the flag is defined by comparing this pair of digits; otherwise the value of the flag is the same as it was without this new digit. Of course, we should do the same for the denominator. Okay, now we can actually start coding this DP: $dp[k][carry1][carry2][comp1][comp2][mask1][mask2]$ is the number of possible ways to put $k$ least significant digits in $z$ in such a way that: the value carried over to the next digit of the numerator is $carry1$ (and $carry2$ for the denominator); $comp1$ denotes whether the current numerator is less or equal to the number represented by $k$ least significant digits of $n$ ($comp2$ does the same for the denominator); $mask1$ denotes which "interesting" digits we already met in the numerator (of course, $mask2$ does the same for the denominator). If you are feeling confident in your programming abilities, you can just start implementing this DP on a seven-dimensional array. I was too afraid to do it (but, looking at participants' solutions, I realize that it sounds much more scary than it looks in the code), so I decided to write the model solution using a structure representing each state, and a map to store all these structures. This is a common technique: when a dynamic programming solution you come up with has some really complex states and transitions, it is sometimes better to use some self-implemented structures to define these states and store them in a map or a hashmap. Some advantages of this technique are: it's sometimes much easier to code (the code may be longer than the same solution with regular DP stored in a multi-dimensional array, but it's easier to write and understand this code); if most states are unreachable, they won't even appear in our map, so we skip them altogether; it is easy to add some optimizations related to reducing the number of states. For example, the number of different values for $mask1$ and $mask2$ may be too much, so we can use the following optimization: as soon as we find some pair of numbers in $mask1$ and $mask2$ that can represent $x'$ and $y'$, we can change these masks to some values that will mark that they are "finished" and stop updating them at all.
|
[
"dp"
] | 2,700
|
#include<bits/stdc++.h>
using namespace std;
const int N = 105;
int a[N];
int n;
int numPos[10], denPos[10];
int num, den;
const int MOD = 998244353;
struct halfState
{
int carry;
int mask;
bool comp;
halfState() {};
halfState(int carry, int mask, bool comp) : carry(carry), mask(mask), comp(comp) {};
};
bool operator <(const halfState& x, const halfState& y)
{
if(x.carry != y.carry) return x.carry < y.carry;
if(x.mask != y.mask) return x.mask < y.mask;
return x.comp < y.comp;
}
bool operator ==(const halfState& x, const halfState& y)
{
return x.carry == y.carry && x.mask == y.mask && x.comp == y.comp;
}
bool operator !=(const halfState& x, const halfState& y)
{
return x.carry != y.carry || x.mask != y.mask || x.comp != y.comp;
}
halfState go(const halfState& s, int pos, int digit, bool isNum)
{
int newDigit = digit * (isNum ? num : den) + s.carry;
int newCarry = newDigit / 10;
newDigit %= 10;
int newMask = s.mask;
int maskPos = (isNum ? numPos[newDigit] : denPos[newDigit]);
if(maskPos != -1) newMask |= (1 << maskPos);
bool newComp = (newDigit < a[pos]) || (newDigit == a[pos] && s.comp);
return halfState(newCarry, newMask, newComp);
}
struct state
{
halfState numState;
halfState denState;
state() {};
state(halfState numState, halfState denState) : numState(numState), denState(denState) {};
void norm()
{
if(numState.mask & denState.mask)
numState.mask = denState.mask = 1;
};
bool valid()
{
return bool(numState.mask & denState.mask) && numState.comp && denState.comp && (numState.carry == 0) && (denState.carry == 0);
};
};
bool operator <(const state& x, const state& y)
{
if(x.numState != y.numState) return x.numState < y.numState;
return x.denState < y.denState;
}
state go(const state& s, int pos, int digit)
{
halfState newNum = go(s.numState, pos, digit, true);
halfState denNum = go(s.denState, pos, digit, false);
state res(newNum, denNum);
res.norm();
return res;
}
int add(int x, int y)
{
return (x + y) % MOD;
}
int ans = 0;
void calcFixed(int x, int y)
{
num = x;
den = y;
for(int i = 0; i <= 9; i++)
numPos[i] = denPos[i] = -1;
int cnt = 0;
for(int i = 1; i <= 9; i++)
for(int j = 1; j <= 9; j++)
if(i * y == j * x)
{
numPos[i] = denPos[j] = cnt++;
}
vector<map<state, int> > dp(102);
dp[0][state(halfState(0, 0, true), halfState(0, 0, true))] = 1;
for(int i = 0; i <= 100; i++)
for(auto x : dp[i])
{
state curState = x.first;
int curCount = x.second;
for(int j = 0; j <= 9; j++)
{
state newState = go(curState, i, j);
dp[i + 1][newState] = add(dp[i + 1][newState], curCount);
}
}
for(auto x : dp[101])
{
state curState = x.first;
int curCount = x.second;
if(curState.valid())
ans = add(ans, curCount);
}
}
int main()
{
string s;
cin >> s;
int len = s.size();
reverse(s.begin(), s.end());
for(int i = 0; i < len; i++)
{
a[i] = s[i] - '0';
}
for(int i = 1; i <= 9; i++)
for(int j = 1; j <= 9; j++)
if(__gcd(i, j) == 1)
calcFixed(i, j);
cout << ans << endl;
}
|
1195
|
A
|
Drinks Choosing
|
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are $n$ students living in a building, and for each of them the favorite drink $a_i$ is known. So you know $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ ($1 \le a_i \le k$) is the type of the favorite drink of the $i$-th student. The drink types are numbered from $1$ to $k$.
There are infinite number of drink sets. Each set consists of \textbf{exactly two} portions of the same drink. In other words, there are $k$ types of drink sets, the $j$-th type contains two portions of the drink $j$. The available number of sets of each of the $k$ types is infinite.
You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $\lceil \frac{n}{2} \rceil$, where $\lceil x \rceil$ is $x$ rounded up.
After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $n$ is odd then one portion will remain unused and the students' teacher will drink it.
What is the maximum number of students that can get their favorite drink if $\lceil \frac{n}{2} \rceil$ sets will be chosen optimally and students will distribute portions between themselves optimally?
|
Let's take a look on a students. If two students have the same favorite drink, let's take one set with this drink. Let the number of such students (which we can satisfy as pairs) be $good$. Because the number of sets is $\lceil\frac{n}{2}\rceil$ we always can do it. So there are students which are the only with their favorite drinks remain. It is obvious that if we take one set we can satisfy at most one student (and one of the others will gain not his favorite drink). Let the number of such students (which remain after satisfying pairs of students) be $bad$. Then the answer is $good + \lceil\frac{bad}{2}\rceil$.
|
[
"greedy",
"math"
] | 1,000
|
// Created by Nikolay Budin
#ifdef LOCAL
# define _GLIBCXX_DEBUG
#else
# define cerr __get_ce
#endif
#include <bits/stdc++.h>
#define ff first
#define ss second
#define szof(x) ((int)x.size())
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef unsigned long long ull;
int const INF = (int)1e9 + 1e3;
ll const INFL = (ll)1e18 + 1e6;
#ifdef LOCAL
mt19937 tw(9450189);
#else
mt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif
uniform_int_distribution<ll> ll_distr;
ll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; }
void solve() {
int n, k;
cin >> n >> k;
map<int, int> have;
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
have[num]++;
}
int cnt = 0;
int ans = 0;
for (pii p : have) {
cnt += p.ss % 2;
ans += p.ss / 2 * 2;
}
ans += (cnt + 1) / 2;
cout << ans << "\n";
}
int main() {
#ifdef LOCAL
auto start_time = clock();
cerr << setprecision(3) << fixed;
#endif
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(nullptr);
int test_count = 1;
// cin >> test_count;
for (int test = 1; test <= test_count; ++test) {
solve();
}
#ifdef LOCAL
auto end_time = clock();
cerr << "Execution time: " << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << " ms\n";
#endif
}
|
1195
|
B
|
Sport Mafia
|
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.
For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs $n$ actions. The first action performed is to put a single candy into the box. For each of the remaining moves she can choose from two options:
- the first option, in case the box contains at least one candy, is to take \textbf{exactly one candy out and eat it}. This way the number of candies in the box decreased by $1$;
- the second option is to put candies in the box. In this case, Alya will put $1$ more candy, than she put in the previous time.
Thus, if the box is empty, then it can only use the second option.
For example, one possible sequence of Alya's actions look as follows:
- put one candy into the box;
- put two candies into the box;
- eat one candy from the box;
- eat one candy from the box;
- put three candies into the box;
- eat one candy from the box;
- put four candies into the box;
- eat one candy from the box;
- put five candies into the box;
This way she will perform $9$ actions, the number of candies at the end will be $11$, while Alya will eat $4$ candies in total.
You know the total number of actions $n$ and the number of candies at the end $k$. You need to find the total number of sweets Alya ate. That is the number of moves of the first option. It's guaranteed, that for the given $n$ and $k$ the answer always exists.
Please note, that during an action of the first option, Alya takes out and eats exactly one candy.
|
In fact, we need to solve the following equation: $\frac{x(x+1)}{2} - (n - x) = k$ and when we will find $x$ we need to print $n-x$ as the answer. $\frac{x(x+1)}{2}$ is the number of candies Alya will put into the box with $x$ turns (sum of arithmetic progression). This equation can be solved mathematically. The only problem is getting the square root, it can be avoided with binary search or taking square root in non-integer numbers and checking some amount of integers in small range nearby the obtained root. The other solution is the binary search by $x$.
|
[
"binary search",
"brute force",
"math"
] | 1,000
|
#include <iostream>
#include <cmath>
int main() {
long long n, k;
std::cin >> n >> k;
std::cout << static_cast<long long>(round(n + 1.5 - sqrt(2 * (n + k) + 2.75)));
return 0;
}
|
1195
|
C
|
Basketball Exercise
|
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $2 \cdot n$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $n$ people in each row). Students are numbered from $1$ to $n$ in each row in order from left to right.
Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one \textbf{taken}) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $2n$ students (there are no additional constraints), and a team can consist of any number of students.
Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.
|
This is pretty standard dynamic programming problem. Let $dp_{i, 1}$ be the maximum total height of team members if the last student taken has the position $(i-1, 1)$, $dp_{i, 2}$ is the same but the last student taken has the position $(i-1, 2)$ and $dp_{i, 3}$ the same but we didn't take any student from position $i-1$. Transitions are pretty easy: $dp_{i, 1} = max(dp_{i-1, 2} + h_{i, 1}, dp_{i-1, 3} + h_{i, 1}, h_{i, 1})$; $dp_{i, 2} = max(dp_{i-1, 1} + h_{i, 2}, dp_{i-1, 3} + h_{i, 2}, h_{i, 2})$; $dp_{i, 3} = max(dp_{i-1, 1}, dp_{i-1, 2})$. This dynamic programming can be calculated almost without using memory because we need only the $i-1$-th row to calculate the $i$-th row of this dp. Moreover, we don't actually need $dp_{i, 3}$ if we will add transitions $dp_{i, 1} = max(dp_{i, 1}, dp_{i - 1, 1})$ and $dp_{i, 2} = max(dp_{i, 2}, dp_{i - 1, 2})$. These transition will change our dp a bit. Now $dp_{i, j}$ is the maximum total height of the team members if the last student taken has the position $(i-1,1)$ or less. The same with $dp_{i, 2}$. The answer is $max(dp_{n, 1}, dp_{n, 2})$. Time complexity: $O(n)$.
|
[
"dp"
] | 1,400
|
// Created by Nikolay Budin
#ifdef LOCAL
# define _GLIBCXX_DEBUG
#else
# define cerr __get_ce
#endif
#include <bits/stdc++.h>
#define ff first
#define ss second
#define szof(x) ((int)x.size())
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef unsigned long long ull;
typedef pair<ll, ll> pll;
int const INF = (int)1e9 + 1e3;
ll const INFL = (ll)1e18 + 1e6;
#ifdef LOCAL
mt19937 tw(9450189);
#else
mt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif
uniform_int_distribution<ll> ll_distr;
ll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; }
void solve() {
int n;
cin >> n;
vector<vector<int>> inp;
for (int i = 0; i < 2; ++i) {
inp.push_back(vector<int>());
for (int j = 0; j < n; ++j) {
int num;
cin >> num;
inp[i].push_back(num);
}
}
pll d = {0, 0};
for (int i = 0; i < n; ++i) {
pll next = {max(d.ff, d.ss + inp[0][i]), max(d.ss, d.ff + inp[1][i])};
d = next;
}
cout << max(d.ff, d.ss) << "\n";
}
int main() {
#ifdef LOCAL
auto start_time = clock();
cerr << setprecision(3) << fixed;
#endif
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(nullptr);
int test_count = 1;
// cin >> test_count;
for (int test = 1; test <= test_count; ++test) {
solve();
}
#ifdef LOCAL
auto end_time = clock();
cerr << "Execution time: " << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << " ms\n";
#endif
}
|
1195
|
D1
|
Submarine in the Rybinsk Sea (easy edition)
|
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.
A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.
Let's denote a function that alternates digits of two numbers $f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$, where $a_1 \dots a_p$ and $b_1 \dots b_q$ are digits of two integers written in the decimal notation without leading zeros.
In other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.
For example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$
Formally,
- if $p \ge q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$;
- if $p < q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$.
Mishanya gives you an array consisting of $n$ integers $a_i$. \textbf{All numbers in this array are of equal length (that is, they consist of the same number of digits).} Your task is to help students to calculate $\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$ modulo $998\,244\,353$.
|
Let's take a look into some number $a = a_1, a_2, \dots, a_{len}$, where $len$ is the length of each number in the array. We know that in $n$ cases it will be the first argument of the function $f(a, b)$ (where $b$ is some other number), and in $n$ cases it will be the second argument. What it means? It means that $a_1$ will have multiplier $10^{2len-1} \cdot 10^{2len-2} \cdot n$, $a_2$ will have multiplier $10^{2len-3} \cdot 10^{2len-4} \cdot n$, and so on. If we take a look closer, $a$ will add to the answer exactly $f(a, a) \cdot n$. So the final answer is $n\sum\limits_{i=1}^{n} f(a_i, a_i)$. Don't forget about modulo and overflow (even $64$-bit datatype can overflow in this problem, because $f(10^9, 10^9)$ has $20$ digits in decimal notation).
|
[
"combinatorics",
"math",
"number theory"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int a, int b) {
a += b;
if (a >= MOD) a -= MOD;
if (a < 0) a += MOD;
return a;
}
int mul(int a, int b) {
return a * 1ll * b % MOD;
}
int len;
vector<int> pw10;
int f(int a) {
int pos = 0;
int res = 0;
while (a > 0) {
int cur = a % 10;
a /= 10;
res = add(res, mul(cur, pw10[2 * pos]));
res = add(res, mul(cur, pw10[2 * pos + 1]));
++pos;
}
return res;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
pw10 = vector<int>(30);
pw10[0] = 1;
for (int i = 1; i < 30; ++i) {
pw10[i] = mul(pw10[i - 1], 10);
}
int n;
cin >> n;
int ans = 0;
for (int i = 0; i < n; ++i) {
int a;
cin >> a;
len = to_string(a).size();
ans = add(ans, mul(n, f(a)));
}
cout << ans << endl;
return 0;
}
|
1195
|
D2
|
Submarine in the Rybinsk Sea (hard edition)
|
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$.
A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.
Let's denote a function that alternates digits of two numbers $f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$, where $a_1 \dots a_p$ and $b_1 \dots b_q$ are digits of two integers written in the decimal notation without leading zeros.
In other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.
For example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$
Formally,
- if $p \ge q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$;
- if $p < q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$.
Mishanya gives you an array consisting of $n$ integers $a_i$, your task is to help students to calculate $\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$ modulo $998\,244\,353$.
|
Let $cnt_{len}$ be the number of $a_i$ with length $len$. We will calculate each number's contribution in the answer separately. When we calculate the contribution of the current number in the answer, let's iterate over all lengths $l$ from $1$ to $L$ where $L$ is the maximum length of some number in the array and add the following value to the answer: $cnt_{l} \cdot (fl_{a_i, l} + fr_{a_i, l})$. The function $fl_{x, l}$ means that we merge the number $x$ with some (it does not matter) number of length $l$ and digits of $x$ will be on odd positions in the resulting number (except some leading digits which will be on odd and on even position as well). And the function $fr_{x, l}$ does almost the same thing but it counts digits of $x$ on even positions. Time complexity is $O(n)$ with the constant factor $L^2$.
|
[
"combinatorics",
"math",
"number theory"
] | 1,800
|
// Created by Nikolay Budin
#ifdef LOCAL
# define _GLIBCXX_DEBUG
#else
# define cerr __get_ce
#endif
#include <bits/stdc++.h>
#define ff first
#define ss second
#define szof(x) ((int)x.size())
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef unsigned long long ull;
int const INF = (int)1e9 + 1e3;
ll const INFL = (ll)1e18 + 1e6;
#ifdef LOCAL
mt19937 tw(9450189);
#else
mt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif
uniform_int_distribution<ll> ll_distr;
ll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; }
const int MOD = 998244353;
void add(int& a, int b) {
a += b;
if (a >= MOD) {
a -= MOD;
}
}
int sum(int a, int b) {
add(a, b);
return a;
}
int mult(int a, int b) {
return (ll) a * b % MOD;
}
int f(vector<int> const& a, int l) {
int res = 0;
int p = 1;
for (int i = 0; i < max(szof(a), l); ++i) {
if (i < l) {
p = mult(p, 10);
}
if (i < szof(a)) {
add(res, mult(a[i], p));
p = mult(p, 10);
}
}
return res;
}
int f(int l, vector<int> const& b) {
int res = 0;
int p = 1;
for (int i = 0; i < max(l, szof(b)); ++i) {
if (i < szof(b)) {
add(res, mult(b[i], p));
p = mult(p, 10);
}
if (i < l) {
p = mult(p, 10);
}
}
return res;
}
void solve() {
int n;
cin >> n;
vector<int> arr;
const int MAXL = 11;
vector<int> of_len(MAXL);
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
arr.push_back(num);
int l = 0;
int tmp = num;
while (tmp) {
++l;
tmp /= 10;
}
of_len[l]++;
}
int ans = 0;
for (int i = 0; i < n; ++i) {
vector<int> digits;
int tmp = arr[i];
while (tmp) {
digits.push_back(tmp % 10);
tmp /= 10;
}
for (int l = 1; l < MAXL; ++l) {
int sum = f(digits, l);
add(ans, mult(sum, of_len[l]));
sum = f(l, digits);
add(ans, mult(sum, of_len[l]));
}
}
cout << ans << "\n";
}
int main() {
#ifdef LOCAL
auto start_time = clock();
cerr << setprecision(3) << fixed;
#endif
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(nullptr);
int test_count = 1;
// cin >> test_count;
for (int test = 1; test <= test_count; ++test) {
solve();
}
#ifdef LOCAL
auto end_time = clock();
cerr << "Execution time: " << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << " ms\n";
#endif
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.